llmtrace 0.3.0

Transparent proxy server for LLM API calls
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
//! YAML configuration loading, environment variable overrides, and validation.
//!
//! Loads [`ProxyConfig`] from a YAML file on disk, applies environment variable
//! overrides, and validates the resulting configuration.

use llmtrace_core::{ProxyConfig, TenantId};
use std::path::Path;

/// Tenant name assigned to the catch-all tenant that absorbs all inbound
/// `/v1` traffic which does not identify a tenant (no `X-LLMTrace-Tenant-ID`
/// header and no derivable API key). Shared with the lifecycle (Option A)
/// purely by string value -- keep this in sync if it ever changes.
pub const CATCH_ALL_TENANT_NAME: &str = "catch-all";

/// Load a [`ProxyConfig`] from a YAML file at `path`.
///
/// # Errors
///
/// Returns an error if the file cannot be read or the YAML is invalid.
pub fn load_config(path: &Path) -> anyhow::Result<ProxyConfig> {
    let contents = std::fs::read_to_string(path)
        .map_err(|e| anyhow::anyhow!("Failed to read config file {}: {}", path.display(), e))?;
    let config: ProxyConfig = serde_yaml::from_str(&contents)
        .map_err(|e| anyhow::anyhow!("Failed to parse config YAML: {}", e))?;
    Ok(config)
}

/// Apply environment variable overrides to a [`ProxyConfig`].
///
/// Supported variables:
/// - `LLMTRACE_LISTEN_ADDR` → `listen_addr`
/// - `LLMTRACE_UPSTREAM_URL` → `upstream_url`
/// - `LLMTRACE_STORAGE_PROFILE` → `storage.profile`
/// - `LLMTRACE_STORAGE_DATABASE_PATH` → `storage.database_path`
/// - `LLMTRACE_CLICKHOUSE_URL` → `storage.clickhouse_url`
/// - `LLMTRACE_CLICKHOUSE_DATABASE` → `storage.clickhouse_database`
/// - `LLMTRACE_POSTGRES_URL` → `storage.postgres_url`
/// - `LLMTRACE_REDIS_URL` → `storage.redis_url`
/// - `LLMTRACE_AUTH_ENABLED` → `auth.enabled`
/// - `LLMTRACE_AUTH_ADMIN_KEY` → `auth.admin_key`
/// - `LLMTRACE_RATE_LIMIT_RPS` → `rate_limiting.requests_per_second`
/// - `LLMTRACE_RATE_LIMIT_BURST` → `rate_limiting.burst_size`
/// - `LLMTRACE_ML_MAX_CONCURRENT` → `ml_pipeline.max_concurrent_requests`
/// - `LLMTRACE_DATAMARKING_ENABLED` → `boundary_defense.datamarking.enabled`
/// - `LLMTRACE_DATAMARKING_SHADOW_MODE` → `boundary_defense.datamarking.shadow_mode`
/// - `LLMTRACE_ZONE_DETECTION_ENABLED` → `security_analysis.zone_detection.enabled`
/// - `LLMTRACE_DEFAULT_TENANT_ID` → `default_tenant_id`
///
/// Rate-limit overrides only take effect when the parsed value is `> 0`
/// (a `u32`). Invalid or non-positive values are ignored, leaving the
/// loaded YAML value (or [`RateLimitConfig::default`]) in place.
pub fn apply_env_overrides(config: &mut ProxyConfig) {
    if let Ok(val) = std::env::var("LLMTRACE_LISTEN_ADDR") {
        config.listen_addr = val;
    }
    if let Ok(val) = std::env::var("LLMTRACE_UPSTREAM_URL") {
        config.upstream_url = val;
    }
    if let Ok(val) = std::env::var("LLMTRACE_STORAGE_PROFILE") {
        config.storage.profile = val;
    }
    if let Ok(val) = std::env::var("LLMTRACE_STORAGE_DATABASE_PATH") {
        config.storage.database_path = val;
    }
    if let Ok(val) = std::env::var("LLMTRACE_CLICKHOUSE_URL") {
        config.storage.clickhouse_url = Some(val);
    }
    if let Ok(val) = std::env::var("LLMTRACE_CLICKHOUSE_DATABASE") {
        config.storage.clickhouse_database = Some(val);
    }
    if let Ok(val) = std::env::var("LLMTRACE_POSTGRES_URL") {
        config.storage.postgres_url = Some(val);
    }
    if let Ok(val) = std::env::var("LLMTRACE_REDIS_URL") {
        config.storage.redis_url = Some(val);
    }
    if let Ok(val) = std::env::var("LLMTRACE_AUTH_ENABLED") {
        let val = val.to_lowercase();
        config.auth.enabled = val == "1" || val == "true" || val == "yes";
    }
    if let Ok(val) = std::env::var("LLMTRACE_AUTH_ADMIN_KEY") {
        config.auth.admin_key = Some(val);
    }
    if let Some(rps) = parse_positive_u32("LLMTRACE_RATE_LIMIT_RPS") {
        config.rate_limiting.requests_per_second = rps;
    }
    if let Some(burst) = parse_positive_u32("LLMTRACE_RATE_LIMIT_BURST") {
        config.rate_limiting.burst_size = burst;
    }
    if let Ok(val) = std::env::var("LLMTRACE_DATAMARKING_ENABLED") {
        let val = val.to_lowercase();
        config.boundary_defense.datamarking.enabled = val == "1" || val == "true" || val == "yes";
    }
    if let Ok(val) = std::env::var("LLMTRACE_DATAMARKING_SHADOW_MODE") {
        let val = val.to_lowercase();
        config.boundary_defense.datamarking.shadow_mode =
            val == "1" || val == "true" || val == "yes";
    }
    if let Ok(val) = std::env::var("LLMTRACE_ZONE_DETECTION_ENABLED") {
        let val = val.to_lowercase();
        config.security_analysis.zone_detection.enabled =
            val == "1" || val == "true" || val == "yes";
    }
    if let Ok(val) = std::env::var("LLMTRACE_DEFAULT_TENANT_ID") {
        match uuid::Uuid::parse_str(val.trim()) {
            Ok(uuid) => config.default_tenant_id = Some(llmtrace_core::TenantId(uuid)),
            Err(_) => tracing::warn!(
                value = %val,
                "LLMTRACE_DEFAULT_TENANT_ID must be a valid UUID; ignoring"
            ),
        }
    }
    if let Ok(val) = std::env::var("LLMTRACE_ML_MAX_CONCURRENT") {
        match val.parse::<usize>() {
            Ok(n) if n > 0 => config.ml_pipeline.max_concurrent_requests = n,
            _ => tracing::warn!(
                value = %val,
                "LLMTRACE_ML_MAX_CONCURRENT must be a positive integer; keeping current value"
            ),
        }
    }
}

/// Resolve the effective catch-all tenant id and stamp it onto
/// `config.default_tenant_id`, returning the resolved id.
///
/// Tenant-less `/v1` traffic (no `X-LLMTrace-Tenant-ID` and no derivable
/// API key) is attributed to this catch-all tenant rather than rejected.
/// Resolution order:
///
/// 1. **Option A (lifecycle-supplied):** if `config.default_tenant_id` is
///    already `Some` (set from `LLMTRACE_DEFAULT_TENANT_ID` by
///    [`apply_env_overrides`]), that id is used verbatim.
/// 2. **Option B (self-provisioned fallback):** if it is `None`, a fresh
///    `TenantId(Uuid::new_v4())` is GENERATED at runtime (never a hardcoded
///    literal), stamped onto the config, and logged.
///
/// Must be called AFTER [`apply_env_overrides`] so the env-provided id
/// (Option A) wins. The returned id is the catch-all whose row the caller
/// then ensures exists via `ensure_tenant_exists`.
pub fn resolve_catch_all_tenant_id(config: &mut ProxyConfig) -> TenantId {
    match config.default_tenant_id {
        Some(id) => {
            tracing::info!(
                tenant_id = %id.0,
                "Using configured LLMTRACE_DEFAULT_TENANT_ID as catch-all tenant for tenant-less traffic"
            );
            id
        }
        None => {
            let generated = TenantId(uuid::Uuid::new_v4());
            config.default_tenant_id = Some(generated);
            tracing::info!(
                tenant_id = %generated.0,
                "No LLMTRACE_DEFAULT_TENANT_ID provided; generated catch-all tenant {} for tenant-less traffic",
                generated.0
            );
            generated
        }
    }
}

/// Parse a strictly positive `u32` from an env var. Returns `None` for
/// missing, empty, unparseable, or zero values so the caller leaves the
/// loaded configuration untouched.
fn parse_positive_u32(name: &str) -> Option<u32> {
    let raw = std::env::var(name).ok()?;
    raw.trim().parse::<u32>().ok().filter(|n| *n > 0)
}

/// Validate a [`ProxyConfig`] for common configuration errors.
///
/// Returns `Ok(())` when valid, or an error listing all detected issues.
pub fn validate_config(config: &ProxyConfig) -> anyhow::Result<()> {
    let mut errors: Vec<String> = Vec::new();

    if config.listen_addr.is_empty() {
        errors.push("listen_addr must not be empty".to_string());
    }

    if config.upstream_url.is_empty() {
        errors.push("upstream_url must not be empty".to_string());
    } else if !config.upstream_url.starts_with("http://")
        && !config.upstream_url.starts_with("https://")
    {
        errors.push("upstream_url must start with http:// or https://".to_string());
    }

    // `sqlite` is accepted as a documented alias for `lite` because the
    // basilica example configs default `LLMTRACE_STORAGE_PROFILE` to
    // `sqlite` and tenants rely on that spelling. Keep both spellings
    // wired here AND in the `StorageProfile` factory in `main.rs`.
    match config.storage.profile.as_str() {
        "lite" | "sqlite" | "memory" | "production" => {}
        other => errors.push(format!(
            "storage.profile must be 'lite', 'sqlite', 'memory', or 'production', got '{other}'"
        )),
    }

    match config.logging.level.as_str() {
        "trace" | "debug" | "info" | "warn" | "error" => {}
        other => errors.push(format!(
            "logging.level must be trace/debug/info/warn/error, got '{other}'"
        )),
    }

    match config.logging.format.as_str() {
        "text" | "json" => {}
        other => errors.push(format!(
            "logging.format must be 'text' or 'json', got '{other}'"
        )),
    }

    if config.timeout_ms == 0 {
        errors.push("timeout_ms must be greater than 0".to_string());
    }

    if config.connection_timeout_ms == 0 {
        errors.push("connection_timeout_ms must be greater than 0".to_string());
    }

    if config.enable_tls {
        if config.tls_cert_file.is_none() {
            errors.push("tls_cert_file is required when enable_tls is true".to_string());
        }
        if config.tls_key_file.is_none() {
            errors.push("tls_key_file is required when enable_tls is true".to_string());
        }
    }

    // Boundary defense config validation
    let bd = &config.boundary_defense;
    if bd.enabled {
        if bd.delimiter.is_empty() {
            errors.push("boundary_defense.delimiter must not be empty when enabled".to_string());
        }
        if bd.wrap_roles.is_empty() {
            errors.push("boundary_defense.wrap_roles must not be empty when enabled".to_string());
        }
    }

    // Enforcement config validation
    let enf = &config.enforcement;
    if !(0.0..=1.0).contains(&enf.min_confidence) {
        errors.push(format!(
            "enforcement.min_confidence must be between 0.0 and 1.0, got {}",
            enf.min_confidence
        ));
    }
    if enf.timeout_ms == 0 {
        errors.push("enforcement.timeout_ms must be greater than 0".to_string());
    }

    if config.max_response_size_bytes == 0 {
        errors.push("max_response_size_bytes must be > 0".to_string());
    }

    // ActionRouter config validation
    let ar = &config.action_router;
    if ar.enabled {
        if ar.ip_block.ttl_seconds == 0 {
            errors.push("action_router.ip_block.ttl_seconds must be greater than 0".to_string());
        }
        if ar.ip_block.max_offenses == 0 {
            errors.push("action_router.ip_block.max_offenses must be greater than 0".to_string());
        }
        if ar.webhook.timeout_ms == 0 {
            errors.push("action_router.webhook.timeout_ms must be greater than 0".to_string());
        }
        if ar.judge_route.inline_timeout_ms == 0 {
            errors.push(
                "action_router.judge_route.inline_timeout_ms must be greater than 0".to_string(),
            );
        }
        let webhook_referenced = ar.default_actions.iter().any(|a| a == "webhook")
            || ar
                .rules
                .iter()
                .any(|rule| rule.actions.iter().any(|action| action == "webhook"));
        if ar.webhook.url.is_empty() && webhook_referenced {
            errors.push(
                "action_router.webhook.url must not be empty if webhook action is enabled"
                    .to_string(),
            );
        }
    }

    if config.security_analysis.max_analysis_text_bytes == 0 {
        errors.push("security_analysis.max_analysis_text_bytes must be > 0".to_string());
    }

    if config.ml_pipeline.max_concurrent_requests == 0 {
        errors.push("ml_pipeline.max_concurrent_requests must be >= 1".to_string());
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(anyhow::anyhow!(
            "Configuration errors:\n  - {}",
            errors.join("\n  - ")
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use llmtrace_core::LoggingConfig;
    use std::io::Write;
    use tempfile::NamedTempFile;

    /// Helper to write YAML to a temp file and return the path.
    fn write_yaml(yaml: &str) -> NamedTempFile {
        let mut f = NamedTempFile::new().unwrap();
        f.write_all(yaml.as_bytes()).unwrap();
        f
    }

    #[test]
    fn test_load_config_minimal() {
        let yaml = r#"
listen_addr: "127.0.0.1:9090"
upstream_url: "http://localhost:11434"
timeout_ms: 60000
connection_timeout_ms: 5000
max_connections: 500
enable_tls: false
enable_security_analysis: true
enable_trace_storage: true
enable_streaming: true
max_request_size_bytes: 52428800
security_analysis_timeout_ms: 5000
trace_storage_timeout_ms: 10000
rate_limiting:
  enabled: true
  requests_per_second: 100
  burst_size: 200
  window_seconds: 60
circuit_breaker:
  enabled: true
  failure_threshold: 10
  recovery_timeout_ms: 30000
  half_open_max_calls: 3
health_check:
  enabled: true
  path: "/health"
  interval_seconds: 10
  timeout_ms: 5000
  retries: 3
"#;
        let f = write_yaml(yaml);
        let config = load_config(f.path()).unwrap();
        assert_eq!(config.listen_addr, "127.0.0.1:9090");
        assert_eq!(config.upstream_url, "http://localhost:11434");
        assert_eq!(config.timeout_ms, 60000);
        // logging should use defaults when omitted from YAML
        assert_eq!(config.logging.level, "info");
        assert_eq!(config.logging.format, "text");
    }

    #[test]
    fn test_load_config_with_logging() {
        let yaml = r#"
listen_addr: "0.0.0.0:8080"
upstream_url: "https://api.openai.com"
timeout_ms: 30000
connection_timeout_ms: 5000
max_connections: 1000
enable_tls: false
enable_security_analysis: true
enable_trace_storage: true
enable_streaming: true
max_request_size_bytes: 52428800
security_analysis_timeout_ms: 5000
trace_storage_timeout_ms: 10000
logging:
  level: "debug"
  format: "json"
rate_limiting:
  enabled: true
  requests_per_second: 100
  burst_size: 200
  window_seconds: 60
circuit_breaker:
  enabled: true
  failure_threshold: 10
  recovery_timeout_ms: 30000
  half_open_max_calls: 3
health_check:
  enabled: true
  path: "/health"
  interval_seconds: 10
  timeout_ms: 5000
  retries: 3
"#;
        let f = write_yaml(yaml);
        let config = load_config(f.path()).unwrap();
        assert_eq!(config.logging.level, "debug");
        assert_eq!(config.logging.format, "json");
    }

    #[test]
    fn test_load_config_missing_file() {
        let result = load_config(Path::new("/nonexistent/config.yaml"));
        assert!(result.is_err());
    }

    #[test]
    fn test_load_config_invalid_yaml() {
        let f = write_yaml("not: [valid: yaml: {{{}}}");
        let result = load_config(f.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_apply_env_overrides_listen_addr() {
        let mut config = ProxyConfig::default();
        std::env::set_var("LLMTRACE_LISTEN_ADDR", "127.0.0.1:3000");
        apply_env_overrides(&mut config);
        assert_eq!(config.listen_addr, "127.0.0.1:3000");
        std::env::remove_var("LLMTRACE_LISTEN_ADDR");
    }

    #[test]
    fn test_apply_env_overrides_upstream_url() {
        let mut config = ProxyConfig::default();
        std::env::set_var("LLMTRACE_UPSTREAM_URL", "http://my-llm:8000");
        apply_env_overrides(&mut config);
        assert_eq!(config.upstream_url, "http://my-llm:8000");
        std::env::remove_var("LLMTRACE_UPSTREAM_URL");
    }

    #[test]
    fn test_apply_env_overrides_storage() {
        let mut config = ProxyConfig::default();
        std::env::set_var("LLMTRACE_STORAGE_PROFILE", "memory");
        std::env::set_var("LLMTRACE_STORAGE_DATABASE_PATH", "/tmp/test.db");
        apply_env_overrides(&mut config);
        assert_eq!(config.storage.profile, "memory");
        assert_eq!(config.storage.database_path, "/tmp/test.db");
        std::env::remove_var("LLMTRACE_STORAGE_PROFILE");
        std::env::remove_var("LLMTRACE_STORAGE_DATABASE_PATH");
    }

    /// Serialises tests that mutate the same rate-limit env vars so they
    /// do not race when cargo runs them in parallel.
    static RATE_LIMIT_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn test_apply_env_overrides_rate_limit_rps_and_burst() {
        let _guard = RATE_LIMIT_ENV_LOCK.lock().unwrap();
        let mut config = ProxyConfig::default();
        std::env::set_var("LLMTRACE_RATE_LIMIT_RPS", "250");
        std::env::set_var("LLMTRACE_RATE_LIMIT_BURST", "500");
        apply_env_overrides(&mut config);
        std::env::remove_var("LLMTRACE_RATE_LIMIT_RPS");
        std::env::remove_var("LLMTRACE_RATE_LIMIT_BURST");
        assert_eq!(config.rate_limiting.requests_per_second, 250);
        assert_eq!(config.rate_limiting.burst_size, 500);
    }

    #[test]
    fn test_apply_env_overrides_rate_limit_ignores_invalid() {
        let _guard = RATE_LIMIT_ENV_LOCK.lock().unwrap();
        let baseline = ProxyConfig::default();
        let mut config = ProxyConfig::default();
        std::env::set_var("LLMTRACE_RATE_LIMIT_RPS", "not-a-number");
        std::env::set_var("LLMTRACE_RATE_LIMIT_BURST", "0");
        apply_env_overrides(&mut config);
        std::env::remove_var("LLMTRACE_RATE_LIMIT_RPS");
        std::env::remove_var("LLMTRACE_RATE_LIMIT_BURST");
        // Invalid / zero values must leave the loaded config untouched.
        assert_eq!(
            config.rate_limiting.requests_per_second,
            baseline.rate_limiting.requests_per_second
        );
        assert_eq!(
            config.rate_limiting.burst_size,
            baseline.rate_limiting.burst_size
        );
    }

    #[test]
    fn test_apply_env_overrides_datamarking_and_zone() {
        let mut config = ProxyConfig::default();
        // Defaults: datamarking disabled, shadow_mode true, zone detection off.
        assert!(!config.boundary_defense.datamarking.enabled);
        assert!(config.boundary_defense.datamarking.shadow_mode);
        assert!(!config.security_analysis.zone_detection.enabled);

        std::env::set_var("LLMTRACE_DATAMARKING_ENABLED", "true");
        std::env::set_var("LLMTRACE_DATAMARKING_SHADOW_MODE", "false");
        std::env::set_var("LLMTRACE_ZONE_DETECTION_ENABLED", "1");
        apply_env_overrides(&mut config);
        std::env::remove_var("LLMTRACE_DATAMARKING_ENABLED");
        std::env::remove_var("LLMTRACE_DATAMARKING_SHADOW_MODE");
        std::env::remove_var("LLMTRACE_ZONE_DETECTION_ENABLED");

        assert!(config.boundary_defense.datamarking.enabled);
        assert!(!config.boundary_defense.datamarking.shadow_mode);
        assert!(config.security_analysis.zone_detection.enabled);
    }

    #[test]
    fn test_apply_env_overrides_default_tenant_id() {
        let mut config = ProxyConfig::default();
        assert!(config.default_tenant_id.is_none());
        let id = uuid::Uuid::new_v4();
        std::env::set_var("LLMTRACE_DEFAULT_TENANT_ID", id.to_string());
        apply_env_overrides(&mut config);
        std::env::remove_var("LLMTRACE_DEFAULT_TENANT_ID");
        assert_eq!(config.default_tenant_id.map(|t| t.0), Some(id));
    }

    #[test]
    fn test_apply_env_overrides_default_tenant_id_invalid_ignored() {
        let mut config = ProxyConfig::default();
        std::env::set_var("LLMTRACE_DEFAULT_TENANT_ID", "not-a-uuid");
        apply_env_overrides(&mut config);
        std::env::remove_var("LLMTRACE_DEFAULT_TENANT_ID");
        assert!(config.default_tenant_id.is_none());
    }

    /// Option A: when an id is already configured (lifecycle supplied it
    /// via `LLMTRACE_DEFAULT_TENANT_ID`), it is used verbatim as the
    /// catch-all and the config is left pointing at the same id.
    #[test]
    fn test_resolve_catch_all_uses_configured_id() {
        let configured = TenantId(uuid::Uuid::new_v4());
        let mut config = ProxyConfig {
            default_tenant_id: Some(configured),
            ..ProxyConfig::default()
        };
        let resolved = resolve_catch_all_tenant_id(&mut config);
        assert_eq!(resolved, configured);
        assert_eq!(config.default_tenant_id, Some(configured));
    }

    /// Option B: with no id configured, a fresh non-nil UUID is generated
    /// and stamped onto the config so the request path can read it.
    #[test]
    fn test_resolve_catch_all_generates_fresh_id_when_unset() {
        let mut config = ProxyConfig::default();
        assert!(config.default_tenant_id.is_none());
        let resolved = resolve_catch_all_tenant_id(&mut config);
        assert!(
            !resolved.0.is_nil(),
            "generated catch-all id must not be the nil UUID"
        );
        assert_eq!(
            config.default_tenant_id,
            Some(resolved),
            "resolved id must be stamped back onto the config"
        );
    }

    /// Proves the Option B id is GENERATED at runtime, not a hardcoded
    /// literal: two independent resolutions yield two different ids.
    #[test]
    fn test_resolve_catch_all_generates_distinct_ids_across_builds() {
        let mut a = ProxyConfig::default();
        let mut b = ProxyConfig::default();
        let id_a = resolve_catch_all_tenant_id(&mut a);
        let id_b = resolve_catch_all_tenant_id(&mut b);
        assert_ne!(
            id_a, id_b,
            "fresh resolutions must produce distinct ids (proves runtime generation, not a hardcoded literal)"
        );
        assert!(!id_a.0.is_nil());
        assert!(!id_b.0.is_nil());
    }

    /// The catch-all id must never collapse to the nil UUID nor to the
    /// deterministic "anonymous" sentinel used by the auth-disabled path.
    #[test]
    fn test_resolve_catch_all_never_nil_or_anonymous_sentinel() {
        let anonymous = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, b"llmtrace-anonymous");
        let mut config = ProxyConfig::default();
        let resolved = resolve_catch_all_tenant_id(&mut config);
        assert!(!resolved.0.is_nil());
        assert_ne!(
            resolved.0, anonymous,
            "catch-all must be a fresh tenant, not the anonymous sentinel"
        );
    }

    #[test]
    fn test_validate_config_valid() {
        let config = ProxyConfig::default();
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn test_validate_config_empty_listen_addr() {
        let config = ProxyConfig {
            listen_addr: String::new(),
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        assert!(err.to_string().contains("listen_addr must not be empty"));
    }

    #[test]
    fn test_validate_config_empty_upstream_url() {
        let config = ProxyConfig {
            upstream_url: String::new(),
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        assert!(err.to_string().contains("upstream_url must not be empty"));
    }

    #[test]
    fn test_validate_config_bad_upstream_url_scheme() {
        let config = ProxyConfig {
            upstream_url: "ftp://example.com".to_string(),
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        assert!(err
            .to_string()
            .contains("upstream_url must start with http://"));
    }

    #[test]
    fn test_validate_config_invalid_storage_profile() {
        let config = ProxyConfig {
            storage: llmtrace_core::StorageConfig {
                profile: "postgres".to_string(),
                database_path: String::new(),
                ..llmtrace_core::StorageConfig::default()
            },
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        assert!(err.to_string().contains("storage.profile"));
    }

    /// Regression test for issue #249: `LLMTRACE_STORAGE_PROFILE=sqlite`
    /// must be accepted as a documented alias for `lite`. The basilica
    /// `pro.yaml` example defaults to `sqlite`, so rejecting it caused
    /// the proxy to crash-loop before `/health` ever bound, which the
    /// platform reports as "stuck in starting".
    #[test]
    fn test_validate_config_accepts_sqlite_alias() {
        for profile in ["lite", "sqlite", "memory"] {
            let config = ProxyConfig {
                storage: llmtrace_core::StorageConfig {
                    profile: profile.to_string(),
                    ..llmtrace_core::StorageConfig::default()
                },
                ..ProxyConfig::default()
            };
            validate_config(&config)
                .unwrap_or_else(|e| panic!("profile {profile} must validate cleanly: {e}"));
        }
    }

    #[test]
    fn test_validate_config_invalid_log_level() {
        let config = ProxyConfig {
            logging: LoggingConfig {
                level: "verbose".to_string(),
                format: "text".to_string(),
            },
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        assert!(err.to_string().contains("logging.level"));
    }

    #[test]
    fn test_validate_config_invalid_log_format() {
        let config = ProxyConfig {
            logging: LoggingConfig {
                level: "info".to_string(),
                format: "xml".to_string(),
            },
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        assert!(err.to_string().contains("logging.format"));
    }

    #[test]
    fn test_validate_config_zero_timeout() {
        let config = ProxyConfig {
            timeout_ms: 0,
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        assert!(err.to_string().contains("timeout_ms"));
    }

    #[test]
    fn test_validate_config_action_router_invalid_values() {
        let mut config = ProxyConfig::default();
        config.listen_addr = "127.0.0.1:8080".to_string();
        config.upstream_url = "http://localhost:11434".to_string();
        config.timeout_ms = 1000;
        config.connection_timeout_ms = 1000;
        config.max_response_size_bytes = 1024;
        config.security_analysis.max_analysis_text_bytes = 1024;
        config.action_router.enabled = true;
        config.action_router.ip_block.ttl_seconds = 0;
        config.action_router.ip_block.max_offenses = 0;
        config.action_router.webhook.timeout_ms = 0;
        config.action_router.judge_route.inline_timeout_ms = 0;
        config.action_router.rules = vec![llmtrace_core::ActionRuleConfig {
            finding_type: Some("prompt_injection".to_string()),
            min_severity: llmtrace_core::SecuritySeverity::High,
            min_confidence: 0.8,
            actions: vec!["webhook".to_string()],
        }];

        let err = validate_config(&config).unwrap_err().to_string();
        assert!(err.contains("action_router.ip_block.ttl_seconds"));
        assert!(err.contains("action_router.ip_block.max_offenses"));
        assert!(err.contains("action_router.webhook.timeout_ms"));
        assert!(err.contains("action_router.judge_route.inline_timeout_ms"));
        assert!(err.contains("action_router.webhook.url"));
    }

    #[test]
    fn test_validate_config_tls_without_cert() {
        let config = ProxyConfig {
            enable_tls: true,
            tls_cert_file: None,
            tls_key_file: None,
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("tls_cert_file"));
        assert!(msg.contains("tls_key_file"));
    }

    #[test]
    fn test_validate_config_enforcement_bad_confidence() {
        let config = ProxyConfig {
            enforcement: llmtrace_core::EnforcementConfig {
                min_confidence: 1.5,
                ..llmtrace_core::EnforcementConfig::default()
            },
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        assert!(err.to_string().contains("enforcement.min_confidence"));
    }

    #[test]
    fn test_validate_config_enforcement_negative_confidence() {
        let config = ProxyConfig {
            enforcement: llmtrace_core::EnforcementConfig {
                min_confidence: -0.1,
                ..llmtrace_core::EnforcementConfig::default()
            },
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        assert!(err.to_string().contains("enforcement.min_confidence"));
    }

    #[test]
    fn test_validate_config_enforcement_zero_timeout() {
        let config = ProxyConfig {
            enforcement: llmtrace_core::EnforcementConfig {
                timeout_ms: 0,
                ..llmtrace_core::EnforcementConfig::default()
            },
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        assert!(err.to_string().contains("enforcement.timeout_ms"));
    }

    #[test]
    fn test_validate_config_multiple_errors() {
        let config = ProxyConfig {
            listen_addr: String::new(),
            upstream_url: String::new(),
            timeout_ms: 0,
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("listen_addr"));
        assert!(msg.contains("upstream_url"));
        assert!(msg.contains("timeout_ms"));
    }

    #[test]
    fn test_validate_config_zero_max_response_size() {
        let config = ProxyConfig {
            max_response_size_bytes: 0,
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        assert!(err
            .to_string()
            .contains("max_response_size_bytes must be > 0"));
    }

    #[test]
    fn test_validate_config_zero_max_analysis_text() {
        let config = ProxyConfig {
            security_analysis: llmtrace_core::SecurityAnalysisConfig {
                max_analysis_text_bytes: 0,
                ..llmtrace_core::SecurityAnalysisConfig::default()
            },
            ..ProxyConfig::default()
        };
        let err = validate_config(&config).unwrap_err();
        assert!(err
            .to_string()
            .contains("security_analysis.max_analysis_text_bytes must be > 0"));
    }
}