-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·2362 lines (2072 loc) · 101 KB
/
install.sh
File metadata and controls
executable file
·2362 lines (2072 loc) · 101 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
#!/bin/bash
# Vigil Guard v2.1.0 - Complete Installation Script
# This script automates the installation of all components
set -euo pipefail # Exit on error, undefined vars, pipe failures
IFS=$'\n\t' # Safe word splitting
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Helper functions
log_info() {
echo -e "${BLUE}ℹ${NC} $1"
}
log_success() {
echo -e "${GREEN}✓${NC} $1"
}
log_warning() {
echo -e "${YELLOW}⚠${NC} $1"
}
log_error() {
echo -e "${RED}✗${NC} $1"
}
# Track installation progress
TOTAL_STEPS=17
CURRENT_STEP=0
# Default Docker Compose command (overridden in check_prerequisites)
DOCKER_COMPOSE_CMD=("docker-compose")
print_header() {
CURRENT_STEP=$((CURRENT_STEP + 1))
PROGRESS=$((CURRENT_STEP * 100 / TOTAL_STEPS))
echo ""
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}[$PROGRESS%] $1${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
}
# Check if command exists
command_exists() {
command -v "$1" >/dev/null 2>&1
}
# Detect platform (for permission handling)
detect_platform() {
if [[ "$OSTYPE" == "darwin"* ]]; then
echo "macos"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
echo "linux"
else
echo "unknown"
fi
}
# State file for tracking installation
INSTALL_STATE_FILE=".install-state.lock"
# Check if this is a re-run on existing installation
check_existing_installation() {
if [ -f "$INSTALL_STATE_FILE" ]; then
log_warning "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_warning " Existing Installation Detected"
log_warning "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
log_info "Previous installation: $(cat $INSTALL_STATE_FILE)"
echo ""
log_warning "IMPORTANT: Re-running install.sh on existing installation"
echo ""
log_info "This installation will:"
echo " • ${GREEN}Preserve${NC} all data volumes (ClickHouse, Grafana, Web UI)"
echo " • ${GREEN}Keep${NC} existing passwords (unless you choose to reset)"
echo " • ${YELLOW}Update${NC} configuration files and services"
echo ""
log_warning "Data preservation is the default safe behavior."
echo ""
read -r -p "Continue with update? (y/N): " REPLY
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
log_info "Installation cancelled by user"
exit 0
fi
# Return 0 = existing installation detected (success, but needs update mode)
return 0
else
# Return 1 = fresh installation (no existing state, normal install proceeds)
return 1
fi
}
# Detect existing Docker volumes
detect_volumes() {
local volumes_found=0
if docker volume ls | grep -q "vigil"; then
volumes_found=1
echo ""
log_info "Found existing Docker volumes:"
docker volume ls | grep "vigil" | awk '{print " • " $2}'
echo ""
fi
if [ -d "vigil_data/clickhouse" ]; then
volumes_found=1
local size
size=$(du -sh vigil_data/clickhouse 2>/dev/null | awk '{print $1}')
log_info "Found local ClickHouse data directory: vigil_data/clickhouse ($size)"
fi
return $volumes_found
}
# Confirm data destruction with user
confirm_data_destruction() {
local reason="$1"
echo ""
log_error "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_error " ⚠️ DATA DESTRUCTION WARNING ⚠️"
log_error "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
log_warning "Reason: ${reason}"
echo ""
# Show what will be deleted
detect_volumes
echo ""
log_error "⚠️ ALL DATA IN THESE VOLUMES WILL BE PERMANENTLY DELETED ⚠️"
echo ""
log_info "This includes:"
echo " • All ClickHouse logs (events_raw, events_processed)"
echo " • Security audit trails (30-365 days of data)"
echo " • Grafana dashboards and settings"
echo " • Web UI database (users, sessions)"
echo ""
log_warning "This action CANNOT be undone!"
echo ""
log_info "If you want to preserve data, cancel now and:"
echo " 1. Backup vigil_data/ directory"
echo " 2. Export ClickHouse tables manually"
echo " 3. Use existing passwords (edit .env manually)"
echo ""
read -r -p "Type 'DELETE' (all caps) to confirm data destruction: " CONFIRM
echo
if [ "$CONFIRM" != "DELETE" ]; then
log_info "Data destruction cancelled by user"
log_info "Installation cannot proceed with password rotation"
log_info "To continue, either:"
log_info " 1. Keep existing passwords (edit .env manually)"
log_info " 2. Backup data and re-run with DELETE confirmation"
exit 1
fi
log_warning "Confirmation received - proceeding with data destruction..."
}
# Save installation state
save_install_state() {
local timestamp
timestamp=$(date +%Y-%m-%d_%H:%M:%S)
echo "$timestamp - Vigil Guard installation completed successfully" > "$INSTALL_STATE_FILE"
log_success "Installation state saved to $INSTALL_STATE_FILE"
}
# Check prerequisites
check_prerequisites() {
print_header "Checking Prerequisites"
local missing_deps=0
# Check Node.js
if command_exists node; then
NODE_VERSION=$(node --version | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -ge 18 ]; then
log_success "Node.js $(node --version) is installed"
else
log_error "Node.js version 18 or higher is required (found: $(node --version))"
missing_deps=1
fi
else
log_error "Node.js is not installed"
log_info "Install from: https://nodejs.org/"
missing_deps=1
fi
# Check npm
if command_exists npm; then
log_success "npm $(npm --version) is installed"
else
log_error "npm is not installed"
missing_deps=1
fi
# Check Docker
if command_exists docker; then
DOCKER_VERSION=$(docker --version | cut -d' ' -f3 | cut -d',' -f1)
log_success "Docker $DOCKER_VERSION is installed"
# Check if Docker daemon is running
if docker info >/dev/null 2>&1; then
log_success "Docker daemon is running"
else
log_error "Docker daemon is not running"
log_info "Start Docker Desktop or run: sudo systemctl start docker"
missing_deps=1
fi
else
log_error "Docker is not installed"
log_info "Install from: https://www.docker.com/get-started"
missing_deps=1
fi
# Check Docker Compose and detect version (v1 binary vs v2 plugin)
if command_exists docker-compose; then
DOCKER_COMPOSE_CMD=("docker-compose")
COMPOSE_VERSION=$(docker-compose version --short 2>/dev/null || echo "unknown")
log_success "Docker Compose v1 (standalone) detected: $COMPOSE_VERSION"
elif docker compose version >/dev/null 2>&1; then
DOCKER_COMPOSE_CMD=("docker" "compose")
COMPOSE_VERSION=$(docker compose version --short 2>/dev/null || echo "unknown")
log_success "Docker Compose v2 (plugin) detected: $COMPOSE_VERSION"
else
log_error "Docker Compose is not installed"
log_info "Install instructions: https://docs.docker.com/compose/install/"
missing_deps=1
fi
# Check Git
if command_exists git; then
log_success "Git $(git --version | cut -d' ' -f3) is installed"
else
log_warning "Git is not installed (optional but recommended)"
fi
# Check spaCy models for Presidio PII detection
log_info "Checking spaCy models for PII detection..."
MODELS_DIR="services/presidio-pii-api/models"
if [ -d "$MODELS_DIR" ] && [ -f "$MODELS_DIR/checksums.sha256" ]; then
MODEL_COUNT=$(find "$MODELS_DIR" -maxdepth 1 -name "*.whl" 2>/dev/null | wc -l | tr -d ' ')
if [ "$MODEL_COUNT" -ge 2 ]; then
log_success "spaCy models found ($MODEL_COUNT .whl files)"
else
log_warning "spaCy models incomplete (found $MODEL_COUNT, expected 2)"
log_info "Run: ./scripts/download-pii-models.sh"
fi
else
log_warning "spaCy models not found"
log_info "PII detection will use Presidio with spaCy models"
log_info "Download models: ./scripts/download-pii-models.sh"
fi
# Note: Llama model check is done earlier in check_llama_model() function
# before user confirms installation
# Auto-generate language-detector requirements.lock if missing
# This ensures reproducible builds with pinned dependency versions
LANG_DET_DIR="services/language-detector"
if [ -f "$LANG_DET_DIR/requirements.txt" ]; then
if [ ! -f "$LANG_DET_DIR/requirements.lock" ]; then
log_info "Generating language-detector requirements.lock..."
if docker run --rm -v "$(pwd)/$LANG_DET_DIR:/app" -w /app python:3.11-slim \
sh -c "pip install --quiet -r requirements.txt && pip freeze > requirements.lock" 2>/dev/null; then
if [ -f "$LANG_DET_DIR/requirements.lock" ]; then
log_success "Generated requirements.lock for language-detector"
else
log_warning "Failed to generate requirements.lock - will use requirements.txt"
fi
else
log_warning "Could not generate requirements.lock (Docker not ready) - will use requirements.txt"
fi
else
log_success "Language detector requirements.lock found"
fi
fi
if [ $missing_deps -eq 1 ]; then
log_error "Missing required dependencies. Please install them and try again."
exit 1
fi
echo ""
}
# Check available disk space
check_disk_space() {
print_header "Step 3: Disk Space Check"
local required_gb=35
local current_dir="$PWD"
log_info "Checking available disk space..."
echo ""
# Get available space based on OS
local available_gb
if [[ "$OSTYPE" == "darwin"* ]]; then
# macOS: use df with -g flag for GB
available_gb=$(df -g "$current_dir" | awk 'NR==2 {print $4}')
else
# Linux: use df with --output and convert from KB to GB
available_gb=$(df --output=avail "$current_dir" | awk 'NR==2 {print int($1/1024/1024)}')
fi
log_info "Required disk space: ${required_gb} GB"
log_info "Available disk space: ${available_gb} GB"
echo ""
if [ "$available_gb" -lt "$required_gb" ]; then
log_error "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_error " ⚠️ INSUFFICIENT DISK SPACE ⚠️"
log_error "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
log_error "You have ${available_gb} GB available, but ${required_gb} GB is required."
echo ""
log_info "Disk space breakdown:"
echo " • Docker images: ~3.5 GB (v2.1.0: +heuristics +semantic services)"
echo " • vigil_data volumes: 10-20 GB (logs, databases)"
echo " • Build cache: 3-5 GB (temporary)"
echo " • Reserved safety margin: 5 GB"
echo ""
log_info "To free up space:"
echo " • Remove unused Docker images: docker system prune -a"
echo " • Clean up old logs/data from other projects"
echo " • Move installation to a different disk/partition"
echo ""
log_error "Installation cannot continue. Please free up space and try again."
exit 1
fi
log_success "Sufficient disk space available (${available_gb} GB)"
echo ""
}
# Generate secure random passwords
generate_secure_passwords() {
log_info "Generating cryptographically secure passwords..."
echo ""
if ! command_exists openssl; then
log_error "OpenSSL is required to generate secure passwords"
log_error "Please install OpenSSL and try again"
exit 1
fi
# Generate 4 unique passwords (n8n uses account creation wizard)
CLICKHOUSE_PASSWORD=$(openssl rand -base64 32 | tr -d '/+=\n' | head -c 32)
GRAFANA_PASSWORD=$(openssl rand -base64 32 | tr -d '/+=\n' | head -c 32)
WEB_UI_ADMIN_PASSWORD=$(openssl rand -base64 32 | tr -d '/+=\n' | head -c 32)
SESSION_SECRET=$(openssl rand -base64 64 | tr -d '/+=\n' | head -c 64)
# Replace passwords in .env file
if [[ "$OSTYPE" == "darwin"* ]]; then
# macOS requires empty string after -i
sed -i '' "s|CLICKHOUSE_PASSWORD=.*|CLICKHOUSE_PASSWORD=${CLICKHOUSE_PASSWORD}|g" .env || { log_error "Failed to update CLICKHOUSE_PASSWORD in .env"; exit 1; }
sed -i '' "s|GF_SECURITY_ADMIN_PASSWORD=.*|GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD}|g" .env || { log_error "Failed to update GF_SECURITY_ADMIN_PASSWORD in .env"; exit 1; }
sed -i '' "s|WEB_UI_ADMIN_PASSWORD=.*|WEB_UI_ADMIN_PASSWORD=${WEB_UI_ADMIN_PASSWORD}|g" .env || { log_error "Failed to update WEB_UI_ADMIN_PASSWORD in .env"; exit 1; }
sed -i '' "s|SESSION_SECRET=.*|SESSION_SECRET=${SESSION_SECRET}|g" .env || { log_error "Failed to update SESSION_SECRET in .env"; exit 1; }
else
# Linux sed
sed -i "s|CLICKHOUSE_PASSWORD=.*|CLICKHOUSE_PASSWORD=${CLICKHOUSE_PASSWORD}|g" .env || { log_error "Failed to update CLICKHOUSE_PASSWORD in .env"; exit 1; }
sed -i "s|GF_SECURITY_ADMIN_PASSWORD=.*|GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD}|g" .env || { log_error "Failed to update GF_SECURITY_ADMIN_PASSWORD in .env"; exit 1; }
sed -i "s|WEB_UI_ADMIN_PASSWORD=.*|WEB_UI_ADMIN_PASSWORD=${WEB_UI_ADMIN_PASSWORD}|g" .env || { log_error "Failed to update WEB_UI_ADMIN_PASSWORD in .env"; exit 1; }
sed -i "s|SESSION_SECRET=.*|SESSION_SECRET=${SESSION_SECRET}|g" .env || { log_error "Failed to update SESSION_SECRET in .env"; exit 1; }
fi
log_success "Secure passwords generated and configured"
echo ""
echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${RED}⚠️ CRITICAL: SAVE THESE CREDENTIALS - SHOWN ONLY ONCE! ⚠️${NC}"
echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e "${YELLOW}These credentials have been auto-generated for your installation:${NC}"
echo ""
echo -e "${GREEN}ClickHouse Database:${NC}"
echo -e " Username: ${BLUE}admin${NC}"
echo -e " Password: ${BLUE}${CLICKHOUSE_PASSWORD}${NC}"
echo ""
echo -e "${GREEN}Grafana Dashboard:${NC}"
echo -e " Username: ${BLUE}admin${NC}"
echo -e " Password: ${BLUE}${GRAFANA_PASSWORD}${NC}"
echo ""
echo -e "${GREEN}Web UI Admin Account:${NC}"
echo -e " Username: ${BLUE}admin${NC}"
echo -e " Password: ${BLUE}${WEB_UI_ADMIN_PASSWORD}${NC}"
echo -e " ${YELLOW}Note: You will be forced to change this password on first login${NC}"
echo ""
echo -e "${GREEN}Backend Session Secret:${NC}"
echo -e " ${BLUE}${SESSION_SECRET}${NC}"
echo ""
echo -e "${GREEN}n8n Webhook Security:${NC}"
echo -e " ${YELLOW}⚠️ Generate token in Web UI → Configuration → Webhook and Plugin${NC}"
echo -e " ${YELLOW}Then configure n8n Webhook node with Header Auth (see docs/WEBHOOK_SECURITY.md)${NC}"
echo ""
echo -e "${RED}⚠️ IMPORTANT NEXT STEPS:${NC}"
echo -e " 1. ${YELLOW}COPY${NC} these credentials to a secure password manager ${RED}NOW${NC}"
echo -e " 2. These passwords are ${RED}NOT${NC} shown again after this screen"
echo -e " 3. You will need them to access Web UI, Grafana, and ClickHouse"
echo -e " 4. Web UI: Login at ${BLUE}http://localhost/ui${NC} with admin password above"
echo -e " 5. n8n account: Create via wizard at ${BLUE}http://localhost:5678${NC} on first visit"
echo -e " 6. If lost, you can regenerate by re-running: ${BLUE}./install.sh${NC}"
echo ""
echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
read -r -p "Press Enter after you have SAVED these credentials..."
echo ""
}
# Setup environment
setup_environment() {
print_header "Setting Up Environment"
# CRITICAL: Unset any existing password ENV variables to ensure .env takes priority
# Docker Compose prioritizes: Shell ENV > .env file
# Without this, old passwords from previous sessions would override new .env values
unset WEB_UI_ADMIN_PASSWORD 2>/dev/null || true
unset CLICKHOUSE_PASSWORD 2>/dev/null || true
unset GF_SECURITY_ADMIN_PASSWORD 2>/dev/null || true
unset SESSION_SECRET 2>/dev/null || true
unset JWT_SECRET 2>/dev/null || true
log_info "Cleared environment variables (ensures .env takes priority)"
echo ""
# Check if .env exists
if [ ! -f .env ]; then
log_info "Creating .env file from template..."
cp config/.env.example .env
log_success ".env file created"
echo ""
# CRITICAL SECURITY: Check for existing ClickHouse volume
# User may want to preserve data from previous installation
if [ -d "vigil_data/clickhouse" ]; then
echo ""
log_warning "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_warning " Existing ClickHouse Volume Detected"
log_warning "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
log_info "Found existing ClickHouse data at: vigil_data/clickhouse"
log_info "This volume may contain logs and data from a previous installation."
echo ""
log_warning "IMPORTANT DECISION REQUIRED:"
echo ""
log_info "New passwords will be generated for this installation."
log_info "The existing volume contains authentication data tied to old passwords."
echo ""
log_warning "Options:"
log_info " 1. ${GREEN}Remove volume${NC} - Clean installation with new passwords (RECOMMENDED)"
log_info " • All existing data will be lost"
log_info " • Fresh start with secure passwords"
log_info " • No authentication issues"
echo ""
log_info " 2. ${YELLOW}Keep volume${NC} - Preserve existing data (MAY CAUSE ISSUES)"
log_info " • Existing logs/data preserved"
log_info " • Password mismatch will cause authentication failures"
log_info " • You'll need to manually fix authentication"
echo ""
read -p "Remove existing ClickHouse volume? (Y/n): " -n 1 -r
echo ""
echo ""
if [[ ! $REPLY =~ ^[Nn]$ ]]; then
# User chose to remove volume
log_info "Proceeding with volume cleanup..."
echo ""
# Verify Docker is accessible
if ! docker info >/dev/null 2>&1; then
log_error "Docker daemon is not running or not accessible"
log_error "Cannot stop ClickHouse container"
log_info "Start Docker and try again"
exit 1
fi
# Stop container if running
log_info "Stopping ClickHouse container if running..."
"${DOCKER_COMPOSE_CMD[@]}" stop clickhouse 2>/dev/null || log_info "Container not running"
"${DOCKER_COMPOSE_CMD[@]}" rm -f clickhouse 2>/dev/null || log_info "Container not present"
# Wait for full shutdown
sleep 2
# Remove volume with error handling
log_info "Removing old ClickHouse volume data..."
if ! rm -rf vigil_data/clickhouse 2>&1; then
log_error "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_error " CRITICAL FAILURE: Cannot Remove ClickHouse Volume"
log_error "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
log_error "Failed to delete vigil_data/clickhouse"
log_error "This will cause password authentication failures!"
echo ""
log_info "Possible solutions:"
log_info " 1. Run with elevated permissions: sudo ./install.sh"
log_info " 2. Manually remove: sudo rm -rf vigil_data/clickhouse"
log_info " 3. Check if files are in use: lsof vigil_data/clickhouse"
echo ""
exit 1
fi
# Verify deletion succeeded
if [ -d "vigil_data/clickhouse" ]; then
log_error "CRITICAL: Volume directory still exists after deletion attempt!"
log_error "This indicates a serious filesystem or permission issue."
log_error "Cannot proceed - authentication will fail."
exit 1
fi
log_success "Old volume removed successfully"
echo ""
else
# User chose to keep volume
log_warning "Keeping existing ClickHouse volume as requested"
log_warning "⚠️ WARNING: This WILL cause password authentication failures!"
echo ""
log_info "After installation, you'll need to manually fix ClickHouse authentication:"
log_info " 1. Stop services: ${DOCKER_COMPOSE_CMD[*]} down"
log_info " 2. Remove volume: rm -rf vigil_data/clickhouse"
log_info " 3. Restart with new password: ${DOCKER_COMPOSE_CMD[*]} up -d"
echo ""
log_warning "Continuing with installation (authentication issues expected)..."
echo ""
sleep 3
fi
fi
# MANDATORY: Generate secure passwords for new installations
log_warning "⚠️ Auto-generating secure passwords (no default credentials allowed)..."
echo ""
generate_secure_passwords
# Generate random JWT secret
log_info "Generating secure JWT_SECRET..."
if command_exists openssl; then
JWT_SECRET=$(openssl rand -base64 48 | tr -d '\n')
if [[ "$OSTYPE" == "darwin"* ]]; then
sed -i '' "s|JWT_SECRET=change-this-to-a-secure-random-string-at-least-32-characters-long|JWT_SECRET=$JWT_SECRET|g" .env
else
sed -i "s|JWT_SECRET=change-this-to-a-secure-random-string-at-least-32-characters-long|JWT_SECRET=$JWT_SECRET|g" .env
fi
log_success "JWT_SECRET generated and configured"
else
log_warning "OpenSSL not found. Please manually set JWT_SECRET in .env file!"
fi
else
log_success ".env file already exists"
# Check for default/insecure values
local force_regenerate=0
# Check JWT_SECRET
if grep -q "JWT_SECRET=change-this" .env; then
log_warning "⚠️ JWT_SECRET is using default value - generating new one"
if command_exists openssl; then
JWT_SECRET=$(openssl rand -base64 48 | tr -d '\n')
if [[ "$OSTYPE" == "darwin"* ]]; then
sed -i '' "s|JWT_SECRET=.*|JWT_SECRET=$JWT_SECRET|g" .env
else
sed -i "s|JWT_SECRET=.*|JWT_SECRET=$JWT_SECRET|g" .env
fi
log_success "JWT_SECRET generated automatically"
fi
fi
# Check for default passwords in ACTUAL VALUES (not comments)
# Only check variables that are actually set, ignoring comments and empty lines
if grep -Eq '^(CLICKHOUSE_PASSWORD|GF_SECURITY_ADMIN_PASSWORD|WEB_UI_ADMIN_PASSWORD|N8N_BASIC_AUTH_PASSWORD)=admin123$' .env; then
log_error "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_error " CRITICAL SECURITY ISSUE: Default passwords detected!"
log_error "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
log_warning "Your .env file contains DEFAULT PASSWORDS (admin123)"
log_warning "These are PUBLICLY KNOWN and must be changed immediately!"
echo ""
force_regenerate=1
fi
# Check for missing SESSION_SECRET
if ! grep -q "^SESSION_SECRET=" .env || grep -q "^SESSION_SECRET=$" .env; then
log_error "SESSION_SECRET is missing or empty - this will prevent backend from starting"
force_regenerate=1
fi
if [ "$force_regenerate" -eq 1 ]; then
# Check if this is a re-run on existing installation
if [ -f "$INSTALL_STATE_FILE" ]; then
# Existing installation - user must explicitly choose password rotation
echo ""
log_warning "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_warning " Password Rotation on Existing Installation"
log_warning "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
log_info "Default passwords detected, but this is an EXISTING installation."
log_info "Password rotation will DESTROY all ClickHouse data to prevent auth conflicts."
echo ""
read -r -p "Do you want to rotate passwords? (y/N): " ROTATE_REPLY
echo
if [[ ! $ROTATE_REPLY =~ ^[Yy]$ ]]; then
log_info "Password rotation skipped by user"
log_warning "Installation will continue with existing passwords"
log_warning "⚠️ SECURITY RISK: Default passwords remain in use!"
log_info "To manually change passwords:"
log_info " 1. Edit .env file with strong passwords (32+ chars)"
log_info " 2. Run: ${DOCKER_COMPOSE_CMD[*]} down"
log_info " 3. Run: rm -rf vigil_data/clickhouse"
log_info " 4. Run: ${DOCKER_COMPOSE_CMD[*]} up -d"
force_regenerate=0 # Skip password generation
fi
fi
# If still need to regenerate (either fresh install or user confirmed rotation)
if [ "$force_regenerate" -eq 1 ]; then
echo ""
log_info "Auto-generating secure passwords to replace defaults..."
echo ""
generate_secure_passwords
# CRITICAL: Confirm data destruction before removing volumes
if [ -d "vigil_data/clickhouse" ] || docker volume ls | grep -q "vigil"; then
confirm_data_destruction "Password rotation requires ClickHouse re-initialization"
# Verify Docker is accessible
if ! docker info >/dev/null 2>&1; then
log_error "Docker daemon not accessible - cannot perform cleanup"
log_error "Start Docker and try again"
exit 1
fi
# Stop and remove container
log_info "Stopping ClickHouse container if running..."
"${DOCKER_COMPOSE_CMD[@]}" stop clickhouse 2>/dev/null || log_info "Container not running"
log_info "Removing ClickHouse container if present..."
"${DOCKER_COMPOSE_CMD[@]}" rm -f clickhouse 2>/dev/null || log_info "Container not present"
# Wait for full shutdown
sleep 2
# Remove volume data with error handling
log_info "Removing old ClickHouse volume data..."
if ! rm -rf vigil_data/clickhouse 2>&1; then
log_error "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_error " CRITICAL SECURITY FAILURE: Password Rotation Cannot Complete"
log_error "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
log_error "Cannot remove old ClickHouse volume at vigil_data/clickhouse"
log_error "System CANNOT rotate to secure passwords with old volume present"
echo ""
log_warning "SECURITY IMPACT:"
log_warning " • System will continue using default/insecure passwords"
log_warning " • This is a CRITICAL SECURITY VULNERABILITY"
log_warning " • You MUST resolve this before deploying to production"
echo ""
log_info "Manual intervention required:"
log_info " 1. Stop all services: ${DOCKER_COMPOSE_CMD[*]} down"
log_info " 2. Remove volume: sudo rm -rf vigil_data/clickhouse"
log_info " 3. Re-run installation: ./install.sh"
echo ""
log_error "ABORTING: Cannot proceed with insecure configuration"
exit 1
fi
# Verify deletion succeeded
if [ -d "vigil_data/clickhouse" ]; then
log_error "CRITICAL: Volume directory still exists after deletion!"
log_error "Filesystem error detected - cannot complete password rotation"
exit 1
fi
log_success "Old ClickHouse volume removed - will recreate with new password"
echo ""
else
log_info "No existing ClickHouse volume found - proceeding with password rotation"
echo ""
fi
fi
fi
fi
# Create Grafana ClickHouse datasource configuration from template
log_info "Creating Grafana datasource configuration from template..."
CLICKHOUSE_PASSWORD=$(grep "^CLICKHOUSE_PASSWORD=" .env | cut -d'=' -f2)
CLICKHOUSE_DATASOURCE_TEMPLATE="services/monitoring/grafana/provisioning/datasources/clickhouse.yml.example"
CLICKHOUSE_DATASOURCE_FILE="services/monitoring/grafana/provisioning/datasources/clickhouse.yml"
if [ -f "$CLICKHOUSE_DATASOURCE_TEMPLATE" ]; then
# Copy template and replace placeholder with actual password
cp "$CLICKHOUSE_DATASOURCE_TEMPLATE" "$CLICKHOUSE_DATASOURCE_FILE"
# Note: Grafana provisioning files don't support environment variable substitution for datasource passwords
# Therefore we use sed to inject the password during installation. This is a known Grafana limitation.
# The password is securely sourced from .env and the resulting file is only readable by containers.
if [[ "$OSTYPE" == "darwin"* ]]; then
sed -i '' "s|CLICKHOUSE_PASSWORD_PLACEHOLDER|${CLICKHOUSE_PASSWORD}|g" "$CLICKHOUSE_DATASOURCE_FILE"
else
sed -i "s|CLICKHOUSE_PASSWORD_PLACEHOLDER|${CLICKHOUSE_PASSWORD}|g" "$CLICKHOUSE_DATASOURCE_FILE"
fi
log_success "Grafana datasource configured with ClickHouse password from .env"
else
log_error "Grafana datasource template not found: $CLICKHOUSE_DATASOURCE_TEMPLATE"
exit 1
fi
# Validate environment variables before proceeding
echo ""
log_info "Validating environment variables..."
if ! bash scripts/validate-env.sh; then
log_error "Environment validation failed - cannot proceed with installation"
log_error "Fix the issues above and re-run ./install.sh"
exit 1
fi
log_success "Environment variables validated successfully"
echo ""
}
# Create data directories
create_data_directories() {
print_header "Creating Data Directories"
# CRITICAL: Clean stale databases on fresh installation
# Prevents old credentials from persisting across reinstalls
if [ ! -f "$INSTALL_STATE_FILE" ]; then
log_info "Fresh installation detected: Cleaning stale databases..."
rm -f vigil_data/web-ui/users.db* 2>/dev/null || true
log_success "Stale databases removed"
echo ""
fi
log_info "Creating vigil_data directory structure..."
mkdir -p vigil_data/clickhouse
mkdir -p vigil_data/grafana
mkdir -p vigil_data/n8n
mkdir -p vigil_data/web-ui
mkdir -p vigil_data/prompt-guard-cache
mkdir -p vigil_data/caddy-data
mkdir -p vigil_data/caddy-config
mkdir -p vigil_data/semantic-models
log_success "Data directories created at: $(pwd)/vigil_data/"
# Set secure permissions for Docker containers
log_info "Setting secure permissions for Docker volumes..."
PLATFORM=$(detect_platform)
if [ "$PLATFORM" = "linux" ]; then
# Linux: Use specific UIDs for container users
# ClickHouse runs as UID 101, Grafana as UID 472
log_info "Linux detected: Setting ownership to container UIDs..."
# ClickHouse data (UID 101:101)
if [ -d "vigil_data/clickhouse" ]; then
if ! chown -R 101:101 vigil_data/clickhouse 2>/dev/null; then
log_error "Cannot set ownership for ClickHouse data directory (UID 101:101)"
log_error "ClickHouse may fail to start due to permission issues"
echo ""
log_info "Run with sudo to fix: sudo chown -R 101:101 vigil_data/clickhouse"
log_info "Or: Run full install with sudo: sudo ./install.sh"
echo ""
read -p "Continue anyway? (y/N): " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
exit 1
fi
fi
chmod -R 750 vigil_data/clickhouse 2>/dev/null || true
log_success "ClickHouse: 750 (owner: 101:101)"
fi
# Grafana data (read UID/GID from .env or use defaults)
GRAFANA_UID=${GRAFANA_UID:-472}
GRAFANA_GID=${GRAFANA_GID:-472}
if [ -d "vigil_data/grafana" ]; then
chown -R ${GRAFANA_UID}:${GRAFANA_GID} vigil_data/grafana 2>/dev/null || {
log_warning "Cannot set ownership (need sudo), using fallback permissions"
chmod 755 vigil_data/grafana
}
chmod -R 750 vigil_data/grafana 2>/dev/null || true
log_success "Grafana: 750 (owner: ${GRAFANA_UID}:${GRAFANA_GID})"
fi
elif [ "$PLATFORM" = "macos" ]; then
# macOS: Docker Desktop automatically maps host user to containers
log_info "macOS detected: Using Docker Desktop UID mapping..."
chmod 755 vigil_data/clickhouse 2>/dev/null || true
chmod 755 vigil_data/grafana 2>/dev/null || true
log_success "ClickHouse & Grafana: 755 (Docker Desktop will map UIDs)"
else
# Unknown platform - use safe defaults
log_warning "Unknown platform: Using safe default permissions..."
chmod 755 vigil_data/clickhouse 2>/dev/null || true
chmod 755 vigil_data/grafana 2>/dev/null || true
fi
# Secure other directories (platform-independent)
chmod 755 vigil_data/n8n 2>/dev/null || true
chmod 755 vigil_data/web-ui 2>/dev/null || true
chmod 700 vigil_data/prompt-guard-cache 2>/dev/null || true # Most sensitive
chmod 755 vigil_data/caddy-data 2>/dev/null || true
chmod 755 vigil_data/caddy-config 2>/dev/null || true
log_success "All permissions configured with least-privilege"
echo ""
}
# Create Docker network
create_docker_network() {
print_header "Creating Docker Network"
if docker network inspect vigil-net >/dev/null 2>&1; then
log_info "Docker network 'vigil-net' already exists"
# Remove it and let Docker Compose create it with correct labels
log_info "Removing existing network to ensure correct configuration..."
if ! docker network rm vigil-net 2>&1; then
log_error "Failed to remove existing vigil-net network"
log_error "Network may be in use by running containers"
log_info "Check with: docker network inspect vigil-net"
log_info "Force removal: ${DOCKER_COMPOSE_CMD[*]} down && docker network rm vigil-net"
exit 1
fi
fi
# Let Docker Compose create the network with proper labels during 'up' phase
log_success "Network will be created by Docker Compose"
echo ""
}
# Clean Docker cache and old images
cleanup_docker_cache() {
print_header "Cleaning Docker Cache and Old Images"
log_info "Checking for existing Vigil Guard images..."
# Check if any Vigil images exist
if docker images | grep -q "vigil-"; then
log_warning "Found existing Vigil Guard Docker images"
log_info "Removing old images to prevent cache issues..."
# Stop and remove containers first (if running)
if docker ps -a | grep -q "vigil-"; then
log_info "Stopping existing containers..."
"${DOCKER_COMPOSE_CMD[@]}" down 2>/dev/null || true
fi
# Remove Vigil Guard images
docker images | grep "vigil-" | awk '{print $1":"$2}' | xargs -r docker rmi -f 2>/dev/null || true
log_success "Old images removed"
else
log_info "No existing Vigil Guard images found (fresh installation)"
fi
# Prune build cache to ensure fresh build
log_info "Pruning Docker build cache..."
docker builder prune -f >/dev/null 2>&1 || true
log_success "Docker cache cleaned"
echo ""
}
# Build and start all services
start_all_services() {
print_header "Building and Starting All Services"
log_info "Building Docker images..."
"${DOCKER_COMPOSE_CMD[@]}" build
log_success "Docker images built successfully"
echo ""
log_info "Starting all services..."
"${DOCKER_COMPOSE_CMD[@]}" up -d
log_success "All services started"
echo ""
log_info "Waiting for services to be ready..."
echo ""
# Define all services with their health check endpoints (name|url pairs)
SERVICES=(
"ClickHouse|http://localhost:8123/ping"
"Grafana|http://localhost:3001/api/health"
"n8n|http://localhost:5678/healthz"
"Web UI Backend|http://localhost:8787/health"
"Presidio PII|http://localhost:5001/health"
"Language Detector|http://localhost:5002/health"
"Prompt Guard|http://localhost:8000/health"
)
# Wait for each service with individual timeout
GLOBAL_TIMEOUT=120 # 2 minutes total
START_TIME=$(date +%s)
for SERVICE_ENTRY in "${SERVICES[@]}"; do
IFS='|' read -r SERVICE_NAME SERVICE_URL <<< "$SERVICE_ENTRY"
log_info "Checking $SERVICE_NAME..."
RETRY_COUNT=0
MAX_RETRIES=15
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
# Check global timeout
CURRENT_TIME=$(date +%s)
ELAPSED=$((CURRENT_TIME - START_TIME))
if [ $ELAPSED -ge $GLOBAL_TIMEOUT ]; then
log_warning "$SERVICE_NAME not ready within global timeout (continuing anyway)"
break
fi
# Try health check
if curl -s -f "$SERVICE_URL" >/dev/null 2>&1; then
log_success "$SERVICE_NAME is ready"
break
fi
RETRY_COUNT=$((RETRY_COUNT + 1))
if [ $RETRY_COUNT -lt $MAX_RETRIES ]; then
sleep 2
else
log_warning "$SERVICE_NAME not responding (continuing anyway)"
fi
done
done
echo ""
log_success "Service initialization complete"
echo ""
}
# Initialize ClickHouse database
initialize_clickhouse() {
print_header "Initializing ClickHouse Database"
# Verify all required SQL scripts exist (v2.1.0)
REQUIRED_SQL_FILES=(
"services/monitoring/sql/01-create-tables-v2.sql"
"services/monitoring/sql/02-semantic-embeddings-v2.sql"
"services/monitoring/sql/03-false-positives-views.sql"
"services/monitoring/sql/04-semantic-safe-embeddings.sql"
)
log_info "Verifying SQL files for v2.1.0..."
MISSING_FILES=0
for SQL_FILE in "${REQUIRED_SQL_FILES[@]}"; do
if [ ! -f "$SQL_FILE" ]; then
log_error "Missing SQL file: $SQL_FILE"
MISSING_FILES=$((MISSING_FILES + 1))
fi
done
if [ $MISSING_FILES -gt 0 ]; then
log_error "$MISSING_FILES SQL file(s) missing - cannot proceed"
log_info "Ensure you have the complete v2.1.0 repository"
exit 1
fi
log_success "All v2.1.0 SQL files present"
echo ""
# Load ClickHouse configuration from .env
if [ ! -f .env ]; then
log_error ".env file not found - installation cannot proceed"
log_error "Run: cp config/.env.example .env && ./install.sh"
exit 1
fi
CLICKHOUSE_CONTAINER_NAME=$(grep "^CLICKHOUSE_CONTAINER_NAME=" .env | cut -d'=' -f2)
CLICKHOUSE_USER=$(grep "^CLICKHOUSE_USER=" .env | cut -d'=' -f2)
CLICKHOUSE_PASSWORD=$(grep "^CLICKHOUSE_PASSWORD=" .env | cut -d'=' -f2)
CLICKHOUSE_DB=$(grep "^CLICKHOUSE_DB=" .env | cut -d'=' -f2)
CLICKHOUSE_HTTP_PORT=$(grep "^CLICKHOUSE_HTTP_PORT=" .env | cut -d'=' -f2)
CLICKHOUSE_CONTAINER_NAME=${CLICKHOUSE_CONTAINER_NAME:-vigil-clickhouse}
CLICKHOUSE_USER=${CLICKHOUSE_USER:-admin}
# Password must be set in .env - no fallback for security
if [ -z "$CLICKHOUSE_PASSWORD" ]; then
log_error "CLICKHOUSE_PASSWORD empty in .env - installation cannot proceed"
log_error "Run ./install.sh to generate secure credentials"
exit 1
fi