-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsetup_linux.sh
More file actions
executable file
·4051 lines (3480 loc) · 152 KB
/
setup_linux.sh
File metadata and controls
executable file
·4051 lines (3480 loc) · 152 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# setup_linux.sh (API Version with APISIX integration, AI proxy, network fixes, cleanup and deep cleanup options)
# --- Help function ---
show_help() {
echo "ViolentUTF Linux Setup Script"
echo "Usage: $0 [OPTION]"
echo ""
echo "Options:"
echo " (no options) Normal setup - Install and configure ViolentUTF platform"
echo " --cleanup Standard cleanup - Gracefully shutdown ViolentUTF Streamlit, remove containers, volumes, and config files"
echo " --deepcleanup Deep cleanup - Gracefully shutdown ViolentUTF Streamlit, remove ALL Docker containers, images, volumes,"
echo " networks, and cache (complete Docker environment reset)"
echo " --help, -h Show this help message"
echo ""
echo "Note:"
echo " Cleanup operations gracefully shutdown only ViolentUTF-specific Streamlit processes (Home.py, violentutf directory)"
echo " Other Streamlit applications will not be affected. Graceful shutdown allows proper session cleanup."
echo " User configurations (AI tokens, custom routes, app data) are automatically backed up and restored during setup."
echo ""
echo "Examples:"
echo " ./setup_linux.sh # Normal installation"
echo " ./setup_linux.sh --cleanup # Clean ViolentUTF components only"
echo " ./setup_linux.sh --deepcleanup # Complete Docker environment reset"
echo ""
echo "Description:"
echo " This script sets up the ViolentUTF AI red-teaming platform with:"
echo " - Keycloak SSO authentication"
echo " - APISIX API gateway with AI proxy"
echo " - ViolentUTF API (FastAPI) with PyRIT Orchestrator support"
echo " - ViolentUTF Streamlit web interface"
echo " - PyRIT and Garak AI security frameworks"
echo " - PyRIT Orchestrator API for dataset testing and automation"
echo " - PyRIT Orchestrator integration validation for scorer testing"
echo ""
echo "Warning:"
echo " --deepcleanup will remove ALL Docker data on your system!"
echo " Use with caution if you have other Docker projects."
}
# --- Parse command line arguments ---
CLEANUP_MODE=false
DEEPCLEANUP_MODE=false
for arg in "$@"; do
case $arg in
--cleanup)
CLEANUP_MODE=true
shift # Remove --cleanup from processing
;;
--deepcleanup)
DEEPCLEANUP_MODE=true
shift # Remove --deepcleanup from processing
;;
--help|-h)
show_help
exit 0
;;
*)
# Unknown option
echo "Unknown option: $arg"
echo "Usage: $0 [--cleanup|--deepcleanup|--help]"
exit 1
;;
esac
done
# --- Store generated sensitive values for final report ---
SENSITIVE_VALUES=()
# --- Define shared network name globally ---
SHARED_NETWORK_NAME="vutf-network"
# --- AI Configuration via .env file ---
AI_TOKENS_FILE="ai-tokens.env"
# --- Array to track created AI routes ---
CREATED_AI_ROUTES=()
# --- Function to gracefully shutdown ViolentUTF Streamlit server ---
graceful_streamlit_shutdown() {
echo "Gracefully shutting down ViolentUTF Streamlit server..."
# Find ViolentUTF Streamlit processes
STREAMLIT_PIDS=()
# Check for Home.py process (ViolentUTF main entry point)
HOME_PY_PIDS=$(pgrep -f "streamlit.*Home.py" 2>/dev/null || true)
if [ -n "$HOME_PY_PIDS" ]; then
STREAMLIT_PIDS+=($HOME_PY_PIDS)
fi
# Check for violentutf directory processes
VIOLENTUTF_PIDS=$(pgrep -f "streamlit.*violentutf" 2>/dev/null || true)
if [ -n "$VIOLENTUTF_PIDS" ]; then
STREAMLIT_PIDS+=($VIOLENTUTF_PIDS)
fi
# Remove duplicates and process shutdown
UNIQUE_PIDS=($(printf "%s\n" "${STREAMLIT_PIDS[@]}" | sort -u))
if [ ${#UNIQUE_PIDS[@]} -eq 0 ]; then
echo "No ViolentUTF Streamlit processes found running."
return 0
fi
echo "Found ${#UNIQUE_PIDS[@]} ViolentUTF Streamlit process(es) to shutdown: ${UNIQUE_PIDS[*]}"
# Graceful shutdown sequence
for pid in "${UNIQUE_PIDS[@]}"; do
if kill -0 "$pid" 2>/dev/null; then
echo "Sending SIGTERM to process $pid..."
kill -TERM "$pid" 2>/dev/null || true
fi
done
# Wait up to 10 seconds for graceful shutdown
echo "Waiting for graceful shutdown (up to 10 seconds)..."
for i in {1..10}; do
REMAINING_PIDS=()
for pid in "${UNIQUE_PIDS[@]}"; do
if kill -0 "$pid" 2>/dev/null; then
REMAINING_PIDS+=("$pid")
fi
done
if [ ${#REMAINING_PIDS[@]} -eq 0 ]; then
echo "All ViolentUTF Streamlit processes shutdown gracefully."
break
fi
sleep 1
done
# If processes still running, try SIGINT
if [ ${#REMAINING_PIDS[@]} -gt 0 ]; then
echo "Some processes still running. Sending SIGINT..."
for pid in "${REMAINING_PIDS[@]}"; do
if kill -0 "$pid" 2>/dev/null; then
echo "Sending SIGINT to process $pid..."
kill -INT "$pid" 2>/dev/null || true
fi
done
# Wait another 5 seconds
sleep 5
# Check remaining processes
FINAL_REMAINING=()
for pid in "${REMAINING_PIDS[@]}"; do
if kill -0 "$pid" 2>/dev/null; then
FINAL_REMAINING+=("$pid")
fi
done
# Force kill if necessary
if [ ${#FINAL_REMAINING[@]} -gt 0 ]; then
echo "Force killing remaining processes: ${FINAL_REMAINING[*]}"
for pid in "${FINAL_REMAINING[@]}"; do
kill -KILL "$pid" 2>/dev/null || true
done
fi
fi
# Clean up port 8501 if it's still in use
echo "Checking port 8501 for cleanup..."
PORT_PID=$(lsof -ti:8501 2>/dev/null || true)
if [ -n "$PORT_PID" ]; then
echo "Port 8501 still in use by process $PORT_PID. Attempting cleanup..."
kill -TERM "$PORT_PID" 2>/dev/null || true
sleep 2
if kill -0 "$PORT_PID" 2>/dev/null; then
kill -KILL "$PORT_PID" 2>/dev/null || true
fi
fi
echo "ViolentUTF Streamlit shutdown completed."
}
# --- Function to backup user configurations ---
backup_user_configs() {
echo "Backing up user configurations..."
mkdir -p .backup_temp 2>/dev/null || true
# Backup AI tokens file
if [ -f "$AI_TOKENS_FILE" ]; then
cp "$AI_TOKENS_FILE" .backup_temp/ 2>/dev/null || true
echo "Backed up AI tokens configuration"
fi
# Backup custom APISIX routes
if [ -f "apisix/conf/custom_routes.yml" ]; then
cp "apisix/conf/custom_routes.yml" .backup_temp/ 2>/dev/null || true
echo "Backed up custom APISIX routes"
fi
# Backup application data
if [ -d "violentutf/app_data" ]; then
tar -czf .backup_temp/app_data_backup.tar.gz -C violentutf app_data 2>/dev/null || true
echo "Backed up application data"
fi
}
# --- Function to restore user configurations ---
restore_user_configs() {
echo "Restoring user configurations..."
if [ ! -d ".backup_temp" ]; then
echo "No backup found, skipping restoration."
return 0
fi
# Restore AI tokens file
if [ -f ".backup_temp/$AI_TOKENS_FILE" ]; then
cp ".backup_temp/$AI_TOKENS_FILE" . 2>/dev/null || true
echo "Restored AI tokens configuration"
fi
# Restore custom APISIX routes
if [ -f ".backup_temp/custom_routes.yml" ]; then
mkdir -p apisix/conf 2>/dev/null || true
cp ".backup_temp/custom_routes.yml" apisix/conf/ 2>/dev/null || true
echo "Restored custom APISIX routes"
fi
# Restore application data
if [ -f ".backup_temp/app_data_backup.tar.gz" ]; then
mkdir -p violentutf 2>/dev/null || true
tar -xzf ".backup_temp/app_data_backup.tar.gz" -C violentutf 2>/dev/null || true
echo "Restored application data"
fi
# Clean up backup
rm -rf .backup_temp 2>/dev/null || true
echo "Backup cleanup completed."
}
# --- Deep Cleanup function ---
perform_deep_cleanup() {
echo "Starting DEEP cleanup process..."
echo "This will remove ALL Docker containers, images, volumes, networks, and cache!"
echo ""
# Warning prompt
echo "⚠️ WARNING: This will completely clean your Docker environment!"
echo " - All Docker containers will be stopped and removed"
echo " - All Docker images will be removed"
echo " - All Docker volumes will be removed"
echo " - All Docker networks will be removed"
echo " - All Docker build cache will be pruned"
echo " - All Docker system cache will be pruned"
echo ""
read -p "Are you absolutely sure you want to continue? (type 'YES' to confirm): " confirm
if [ "$confirm" != "YES" ]; then
echo "Deep cleanup cancelled."
exit 0
fi
echo ""
echo "Proceeding with deep cleanup..."
# First backup user configs and graceful shutdown
echo "1. Backing up user configurations..."
backup_user_configs
echo "2. Gracefully shutting down ViolentUTF Streamlit..."
graceful_streamlit_shutdown
# Then perform regular cleanup
echo "3. Performing standard cleanup..."
perform_cleanup_internal
# Stop ALL Docker containers
echo ""
echo "4. Stopping ALL Docker containers..."
RUNNING_CONTAINERS=$(docker ps -aq)
if [ -n "$RUNNING_CONTAINERS" ]; then
echo "Stopping containers: $RUNNING_CONTAINERS"
docker stop $RUNNING_CONTAINERS
echo "Removing containers..."
docker rm $RUNNING_CONTAINERS
echo "All containers stopped and removed."
else
echo "No running containers found."
fi
# Remove ALL Docker images
echo ""
echo "5. Removing ALL Docker images..."
ALL_IMAGES=$(docker images -aq)
if [ -n "$ALL_IMAGES" ]; then
echo "Removing images: $(echo $ALL_IMAGES | wc -w) images found"
docker rmi -f $ALL_IMAGES
echo "All Docker images removed."
else
echo "No Docker images found."
fi
# Remove ALL Docker volumes
echo ""
echo "6. Removing ALL Docker volumes..."
ALL_VOLUMES=$(docker volume ls -q)
if [ -n "$ALL_VOLUMES" ]; then
echo "Removing volumes: $(echo $ALL_VOLUMES | wc -w) volumes found"
docker volume rm -f $ALL_VOLUMES
echo "All Docker volumes removed."
else
echo "No Docker volumes found."
fi
# Remove ALL Docker networks (except default ones)
echo ""
echo "7. Removing ALL Docker networks (except defaults)..."
CUSTOM_NETWORKS=$(docker network ls --filter type=custom -q)
if [ -n "$CUSTOM_NETWORKS" ]; then
echo "Removing custom networks: $(echo $CUSTOM_NETWORKS | wc -w) networks found"
docker network rm $CUSTOM_NETWORKS
echo "All custom Docker networks removed."
else
echo "No custom Docker networks found."
fi
# Prune Docker build cache
echo ""
echo "8. Pruning Docker build cache..."
docker builder prune -af
echo "Docker build cache pruned."
# Prune Docker system (everything)
echo ""
echo "9. Pruning Docker system cache..."
docker system prune -af --volumes
echo "Docker system cache pruned."
# Clean up any remaining Docker artifacts
echo ""
echo "10. Final Docker cleanup..."
docker container prune -f
docker image prune -af
docker volume prune -f
docker network prune -f
echo "Final Docker cleanup completed."
# Show final Docker status
echo ""
echo "9. Final Docker status:"
echo "Containers: $(docker ps -aq | wc -l)"
echo "Images: $(docker images -aq | wc -l)"
echo "Volumes: $(docker volume ls -q | wc -l)"
echo "Networks: $(docker network ls -q | wc -l)"
# Show disk space reclaimed
echo ""
echo "10. Docker system disk usage:"
docker system df
echo ""
echo "🧹 DEEP CLEANUP COMPLETED SUCCESSFULLY!"
echo "✅ All Docker containers, images, volumes, networks, and cache have been removed"
echo "✅ Maximum disk space has been reclaimed"
echo "✅ Docker environment is now completely clean"
echo ""
echo "💡 You can now run the script again for a completely fresh setup"
echo "💡 Note: First run after deep cleanup will take longer as images need to be downloaded"
exit 0
}
# --- Internal cleanup function (without exit) ---
perform_cleanup_internal() {
echo "Starting cleanup process..."
# Remember current directory
ORIGINAL_DIR=$(pwd)
# 1. Stop and remove Keycloak containers
echo "Stopping and removing Keycloak containers..."
if [ -d "keycloak" ]; then
cd "keycloak" || { echo "Failed to cd into keycloak directory"; exit 1; }
docker-compose down -v 2>/dev/null || docker compose down -v 2>/dev/null
cd "$ORIGINAL_DIR"
fi
# 2. Stop and remove APISIX containers
echo "Stopping and removing APISIX containers..."
if [ -d "apisix" ]; then
cd "apisix" || { echo "Failed to cd into apisix directory"; exit 1; }
docker-compose down -v 2>/dev/null || docker compose down -v 2>/dev/null
cd "$ORIGINAL_DIR"
fi
# 3. Remove shared network
echo "Removing shared Docker network..."
if docker network ls | grep -q "$SHARED_NETWORK_NAME"; then
docker network rm $SHARED_NETWORK_NAME
echo "Shared network '$SHARED_NETWORK_NAME' removed."
fi
# 4. Clean up volumes
echo "Removing Docker volumes related to ViolentUTF..."
docker volume ls -q | grep -E "(keycloak|apisix|violentutf|fastapi)" | xargs -r docker volume rm
echo "Docker volumes cleaned up."
# 5. Clean PyRIT orchestrator memory databases but preserve user application data
echo "Cleaning PyRIT orchestrator memory databases..."
if [ -d "violentutf/app_data/violentutf/api_memory" ]; then
rm -f violentutf/app_data/violentutf/api_memory/orchestrator_memory*.db*
echo "Removed orchestrator memory databases"
else
echo "No orchestrator memory databases found"
fi
# Configuration file cleanup
if [ -f "keycloak/.env" ]; then
rm "keycloak/.env"
echo "Removed keycloak/.env"
fi
if [ -f "violentutf_api/fastapi_app/.env" ]; then
rm "violentutf_api/fastapi_app/.env"
echo "Removed violentutf_api/fastapi_app/.env"
fi
# Only remove template files in apisix/conf directory
if [ -d "apisix/conf" ]; then
for file in apisix/conf/*.yaml apisix/conf/*.yml apisix/conf/*.conf; do
if [ -f "$file" ] && [[ "$file" != *.template ]]; then
rm "$file"
echo "Removed $file"
fi
done
echo "Restored only template files in apisix/conf directory"
fi
# ViolentUTF files
if [ -f "violentutf/.env" ]; then
rm "violentutf/.env"
echo "Removed violentutf/.env"
fi
if [ -f "violentutf/.streamlit/secrets.toml" ]; then
rm "violentutf/.streamlit/secrets.toml"
echo "Removed violentutf/.streamlit/secrets.toml"
fi
echo "Preserving user's AI tokens file: $AI_TOKENS_FILE"
}
# --- Cleanup function ---
perform_cleanup() {
echo "Starting cleanup process..."
# 1. Backup user configurations before cleanup
backup_user_configs
# 2. Gracefully shutdown ViolentUTF Streamlit before cleanup
graceful_streamlit_shutdown
# Remember current directory
ORIGINAL_DIR=$(pwd)
# 1. Stop and remove Keycloak containers
echo "Stopping and removing Keycloak containers..."
if [ -d "keycloak" ]; then
cd "keycloak" || { echo "Failed to cd into keycloak directory"; exit 1; }
docker-compose down -v 2>/dev/null || docker compose down -v 2>/dev/null
cd "$ORIGINAL_DIR"
fi
# 2. Stop and remove APISIX containers
echo "Stopping and removing APISIX containers..."
if [ -d "apisix" ]; then
cd "apisix" || { echo "Failed to cd into apisix directory"; exit 1; }
docker-compose down -v 2>/dev/null || docker compose down -v 2>/dev/null
cd "$ORIGINAL_DIR"
fi
# 3. Remove shared network if it exists and is not in use
echo "Removing shared Docker network..."
if docker network inspect $SHARED_NETWORK_NAME >/dev/null 2>&1; then
if docker network rm $SHARED_NETWORK_NAME >/dev/null 2>&1; then
echo "Removed shared network '$SHARED_NETWORK_NAME'."
else
echo "Warning: Could not remove shared network '$SHARED_NETWORK_NAME'. It may still be in use."
fi
fi
# 4. Remove configuration files but preserve directories
echo "Removing configuration files..."
# Keycloak files
if [ -f "keycloak/.env" ]; then
rm "keycloak/.env"
echo "Removed keycloak/.env"
fi
# APISIX files - remove all non-template configurations
if [ -d "apisix/conf" ]; then
# Move only template files to a temp directory
mkdir -p "/tmp/apisix_templates"
find "apisix/conf" -name "*.template" -exec cp {} "/tmp/apisix_templates/" \;
# Remove all config files
rm -rf "apisix/conf/"*
# Move templates back
mkdir -p "apisix/conf"
cp "/tmp/apisix_templates/"* "apisix/conf/" 2>/dev/null || true
rm -rf "/tmp/apisix_templates"
echo "Restored only template files in apisix/conf directory"
fi
# ViolentUTF files
if [ -f "violentutf/.env" ]; then
rm "violentutf/.env"
echo "Removed violentutf/.env"
fi
if [ -f "violentutf/.streamlit/secrets.toml" ]; then
rm "violentutf/.streamlit/secrets.toml"
echo "Removed violentutf/.streamlit/secrets.toml"
fi
# AI tokens file (preserve user's configuration)
echo "Preserving user's AI tokens file: $AI_TOKENS_FILE"
# 5. Remove Docker volumes
echo "Removing Docker volumes related to Keycloak and APISIX..."
# Get volume list and filter for keycloak and apisix volumes
VOLUMES_TO_REMOVE=$(docker volume ls -q | grep -E '(keycloak|apisix)')
if [ -n "$VOLUMES_TO_REMOVE" ]; then
# Use xargs with -r to avoid running if VOLUMES_TO_REMOVE is empty
echo "$VOLUMES_TO_REMOVE" | xargs -r docker volume rm
echo "Removed Docker volumes."
else
echo "No relevant Docker volumes found to remove."
fi
echo "Cleanup completed successfully!"
echo "The Python virtual environment has been preserved."
echo "You can now run the script again for a fresh setup."
exit 0
}
# Function to ensure Docker Compose files have shared network configuration
ensure_network_in_compose() {
local compose_file="$1"
local service_name="$2"
# Check if file exists
if [ ! -f "$compose_file" ]; then
echo "Error: Docker Compose file $compose_file not found!"
return 1
fi
# Backup the compose file
local backup_suffix=$(date +"%Y%m%d%H%M%S")
cp "$compose_file" "${compose_file}.bak${backup_suffix}"
# Check if the file already has vutf-network section
if ! grep -q "vutf-network:" "$compose_file"; then
# Add networks section if missing
if ! grep -q "^networks:" "$compose_file"; then
echo "" >> "$compose_file"
echo "networks:" >> "$compose_file"
fi
# Add vutf-network to networks section (Linux sed)
sed -i '/^networks:/a \ \ vutf-network:\n external: true' "$compose_file"
echo "Added vutf-network to networks section in $compose_file"
fi
# Check if service section exists
if ! grep -q "^ $service_name:" "$compose_file"; then
echo "Warning: Service $service_name not found in $compose_file"
return 0 # Not an error, just means we can't add the network to this specific service
fi
# Add network to service if missing
# We check if the service block ($service_name:) contains a line starting with 'vutf-network'
# This is a bit tricky with sed, using awk for block-specific check might be more robust
# For now, we'll use grep with context and a more complex sed
if ! awk -v service=" $service_name:" '
$0 ~ service {in_service=1}
in_service && /^[[:space:]]*networks:/ {in_networks_block=1}
in_networks_block && /^[[:space:]]*- vutf-network/ {found=1; exit}
in_service && NF > 0 && !/^[[:space:]]/ {in_service=0; in_networks_block=0} # Exiting service block
in_networks_block && NF > 0 && !/^[[:space:]]{3,}/ {in_networks_block=0} # Exiting networks block within service
END {exit !found}
' "$compose_file"; then
# Check if networks section exists in the service
if awk -v service=" $service_name:" '
$0 ~ service {in_service=1}
in_service && /^[[:space:]]*networks:/ {found=1; exit}
in_service && NF > 0 && !/^[[:space:]]/ {in_service=0}
END {exit !found}
' "$compose_file"; then
# Add vutf-network to existing networks section (Linux sed)
# This is complex with sed, finding the line number of " service_name:"
# then finding " networks:" after that, and inserting.
# Using a simpler approach: add if not found, may lead to duplicates if not careful
# This sed command attempts to add it under the service's networks block
sed -i "/^ $service_name:/,/^ [^ ]/ s/^[[:space:]]*networks:/&\n - vutf-network/" "$compose_file"
else
# Add a new networks section to the service (Linux sed)
sed -i "/^ $service_name:/a \ \ \ \ networks:\n - vutf-network" "$compose_file"
fi
echo "Added vutf-network to $service_name service in $compose_file"
fi
return 0
}
# Function to create AI tokens template
create_ai_tokens_template() {
if [ ! -f "$AI_TOKENS_FILE" ]; then
echo "Creating AI tokens configuration file: $AI_TOKENS_FILE"
cat > "$AI_TOKENS_FILE" << 'EOF'
# AI Provider Tokens and Settings
# Set to true/false to enable/disable providers
# Add your actual API keys replacing the placeholder values
# OpenAI Configuration
OPENAI_ENABLED=false
OPENAI_API_KEY=your_openai_api_key_here
# Anthropic Configuration
ANTHROPIC_ENABLED=false
ANTHROPIC_API_KEY=your_anthropic_api_key_here
# Ollama Configuration (local, no API key needed)
OLLAMA_ENABLED=true
OLLAMA_ENDPOINT=http://localhost:11434/v1/chat/completions
# Open WebUI Configuration
OPEN_WEBUI_ENABLED=false
OPEN_WEBUI_ENDPOINT=http://localhost:3000/ollama/v1/chat/completions
OPEN_WEBUI_API_KEY=your_open_webui_api_key_here
# AWS Bedrock Configuration
BEDROCK_ENABLED=false
BEDROCK_REGION=us-east-1
AWS_ACCESS_KEY_ID=your_aws_access_key_id_here
AWS_SECRET_ACCESS_KEY=your_aws_secret_access_key_here
AWS_SESSION_TOKEN=your_aws_session_token_here_if_using_temp_credentials
EOF
echo "✅ Created $AI_TOKENS_FILE"
echo "📝 Please edit this file and add your API keys, then re-run the script"
return 1 # Indicate that user action is needed
fi
return 0
}
# Function to load AI tokens from .env file
load_ai_tokens() {
if [ ! -f "$AI_TOKENS_FILE" ]; then
echo "❌ $AI_TOKENS_FILE not found"
return 1
fi
echo "Loading AI configuration from $AI_TOKENS_FILE..."
# Load the .env file
set -a # automatically export all variables
# shellcheck source=/dev/null
source "$AI_TOKENS_FILE"
set +a # stop automatically exporting
echo "✅ AI configuration loaded"
return 0
}
# Function to check if ai-proxy plugin is available
check_ai_proxy_plugin() {
echo "Checking if ai-proxy plugin is available in APISIX..."
local response
local http_code
response=$(curl -w "%{http_code}" -s -X GET "${APISIX_ADMIN_URL}/apisix/admin/plugins/ai-proxy" \
-H "X-API-KEY: ${APISIX_ADMIN_KEY}" 2>&1)
http_code="${response: -3}"
if [ "$http_code" = "200" ]; then
echo "✅ ai-proxy plugin is available"
return 0
else
echo "❌ ai-proxy plugin is not available"
echo " HTTP Code: $http_code"
echo " Make sure you're using APISIX version 3.10.0 or later with ai-proxy plugin enabled"
return 1
fi
}
# Add debugging to the route creation function
create_openai_route() {
local model="$1"
local uri="$2"
local api_key="$3"
echo "🔧 Debug: Creating route for model='$model', uri='$uri'"
# Validate inputs
if [ -z "$model" ] || [ -z "$uri" ] || [ -z "$api_key" ]; then
echo "❌ Error: Missing required parameters"
echo " Model: '$model'"
echo " URI: '$uri'"
echo " API Key length: ${#api_key}"
return 1
fi
local route_id="openai-$(echo "$model" | tr '.' '-' | tr '[:upper:]' '[:lower:]')"
echo "🔧 Debug: Generated route_id='$route_id'"
local route_config
route_config=$(cat <<-EOF
{
"id": "$route_id",
"uri": "$uri",
"methods": ["POST", "GET"],
"plugins": {
"key-auth": {},
"ai-proxy": {
"provider": "openai",
"auth": {
"header": {
"Authorization": "Bearer $api_key"
}
},
"options": {
"model": "$model"
}
}
}
}
EOF
)
echo "🔧 Debug: Route config created"
echo "Creating OpenAI route for model $model at $uri..."
local response
local http_code
# Use the correct URL format - no route ID in path for PUT creation
response=$(curl -w "%{http_code}" -s -X PUT "${APISIX_ADMIN_URL}/apisix/admin/routes/$route_id" \
-H "X-API-KEY: ${APISIX_ADMIN_KEY}" \
-H "Content-Type: application/json" \
-d "${route_config}" 2>&1)
http_code="${response: -3}"
response_body="${response%???}"
echo "🔧 Debug: HTTP Code: $http_code"
if [ "$http_code" = "200" ] || [ "$http_code" = "201" ]; then
echo "✅ Successfully created OpenAI route: $uri -> $model"
CREATED_AI_ROUTES+=("OpenAI: $uri -> $model")
return 0
else
echo "❌ Failed to create OpenAI route for $model"
echo " HTTP Code: $http_code"
echo " Response: $response_body"
echo " Full curl command would be:"
echo " curl -X PUT '${APISIX_ADMIN_URL}/apisix/admin/routes/$route_id' -H 'X-API-KEY: ${APISIX_ADMIN_KEY}' -H 'Content-Type: application/json' -d '$route_config'"
return 1
fi
}
# Function to create Anthropic route
create_anthropic_route() {
local model="$1"
local uri="$2"
local api_key="$3"
local route_id="anthropic-$(echo "$model" | tr '.' '-' | tr '[:upper:]' '[:lower:]')"
local route_config
route_config=$(cat <<-EOF
{
"id": "$route_id",
"uri": "$uri",
"methods": ["POST", "GET"],
"plugins": {
"key-auth": {},
"ai-proxy": {
"provider": "openai-compatible",
"auth": {
"header": {
"x-api-key": "$api_key",
"anthropic-version": "2023-06-01"
}
},
"options": {
"model": "$model"
},
"override": {
"endpoint": "https://api.anthropic.com/v1/messages"
}
}
}
}
EOF
)
echo "Creating Anthropic route for model $model at $uri..."
local response
local http_code
response=$(curl -w "%{http_code}" -s -X PUT "${APISIX_ADMIN_URL}/apisix/admin/routes/$route_id" \
-H "X-API-KEY: ${APISIX_ADMIN_KEY}" \
-H "Content-Type: application/json" \
-d "${route_config}" 2>&1)
http_code="${response: -3}"
response_body="${response%???}"
if [ "$http_code" = "200" ] || [ "$http_code" = "201" ]; then
echo "✅ Successfully created Anthropic route: $uri -> $model"
CREATED_AI_ROUTES+=("Anthropic: $uri -> $model")
return 0
else
echo "❌ Failed to create Anthropic route for $model"
echo " HTTP Code: $http_code"
echo " Response: $response_body"
return 1
fi
}
# Function to create Ollama route
create_ollama_route() {
local model="$1"
local uri="$2"
local endpoint="$3"
local route_id="ollama-$(echo "$model" | tr '.' '-' | tr '[:upper:]' '[:lower:]')"
local route_config
route_config=$(cat <<-EOF
{
"id": "$route_id",
"uri": "$uri",
"methods": ["POST", "GET"],
"plugins": {
"key-auth": {},
"ai-proxy": {
"provider": "openai-compatible",
"options": {
"model": "$model"
},
"override": {
"endpoint": "$endpoint"
}
}
}
}
EOF
)
echo "Creating Ollama route for model $model at $uri..."
local response
local http_code
response=$(curl -w "%{http_code}" -s -X PUT "${APISIX_ADMIN_URL}/apisix/admin/routes/$route_id" \
-H "X-API-KEY: ${APISIX_ADMIN_KEY}" \
-H "Content-Type: application/json" \
-d "${route_config}" 2>&1)
http_code="${response: -3}"
response_body="${response%???}"
if [ "$http_code" = "200" ] || [ "$http_code" = "201" ]; then
echo "✅ Successfully created Ollama route: $uri -> $model"
CREATED_AI_ROUTES+=("Ollama: $uri -> $model")
return 0
else
echo "❌ Failed to create Ollama route for $model"
echo " HTTP Code: $http_code"
echo " Response: $response_body"
return 1
fi
}
# Function to create Open WebUI route
create_open_webui_route() {
local model="$1"
local uri="$2"
local endpoint="$3"
local api_key="$4"
local route_id="webui-$(echo "$model" | tr '.' '-' | tr '[:upper:]' '[:lower:]')"
# Build auth section only if API key is provided and not placeholder
local auth_section_json=""
if [ -n "$api_key" ] && [ "$api_key" != "your_open_webui_api_key_here" ]; then
auth_section_json=$(cat <<-AUTH
"auth": {
"header": {
"Authorization": "Bearer $api_key"
}
},
AUTH
)
fi
local route_config
route_config=$(cat <<-EOF
{
"id": "$route_id",
"uri": "$uri",
"methods": ["POST", "GET"],
"plugins": {
"key-auth": {},
"ai-proxy": {
"provider": "openai-compatible",
${auth_section_json}
"options": {
"model": "$model"
},
"override": {
"endpoint": "$endpoint"
}
}
}
}
EOF
)
echo "Creating Open WebUI route for model $model at $uri..."
local response
local http_code
response=$(curl -w "%{http_code}" -s -X PUT "${APISIX_ADMIN_URL}/apisix/admin/routes/$route_id" \
-H "X-API-KEY: ${APISIX_ADMIN_KEY}" \
-H "Content-Type: application/json" \
-d "${route_config}" 2>&1)
http_code="${response: -3}"
response_body="${response%???}"
if [ "$http_code" = "200" ] || [ "$http_code" = "201" ]; then
echo "✅ Successfully created Open WebUI route: $uri -> $model"
CREATED_AI_ROUTES+=("Open WebUI: $uri -> $model")
return 0
else
echo "❌ Failed to create Open WebUI route for $model"
echo " HTTP Code: $http_code"
echo " Response: $response_body"
return 1
fi
}
# Function to create APISIX API key consumer
create_apisix_consumer() {
local consumer_config
consumer_config=$(cat <<-EOF
{
"username": "violentutf_user",
"plugins": {
"key-auth": {
"key": "$VIOLENTUTF_API_KEY"
}
}
}
EOF
)
echo "Creating APISIX consumer with API key authentication..."
local response
local http_code
response=$(curl -w "%{http_code}" -X PUT "${APISIX_ADMIN_URL}/apisix/admin/consumers/violentutf_user" \
-H "X-API-KEY: ${APISIX_ADMIN_KEY}" \
-H "Content-Type: application/json" \
-d "${consumer_config}" 2>&1)
http_code="${response: -3}"
response_body="${response%???}"
if [ "$http_code" = "200" ] || [ "$http_code" = "201" ]; then
echo "✅ Successfully created API key consumer"
echo " API Key: $VIOLENTUTF_API_KEY"
echo " Use this key in the 'apikey' header for AI Gateway requests"
return 0
else
echo "❌ Failed to create API key consumer"
echo " HTTP Code: $http_code"
echo " Response: $response_body"
return 1
fi
}
# Function to setup OpenAI routes
setup_openai_routes() {
if [ "$OPENAI_ENABLED" != "true" ]; then
echo "OpenAI provider disabled. Skipping setup."
return 0
fi