structured-proxy 8.1.4

Universal gRPC→REST transcoding proxy — config-driven, works with any gRPC service
Documentation
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
use super::*;

#[test]
fn test_minimal_config_deserialize() {
    let yaml = r#"
upstream:
  default: "grpc://localhost:4180"
"#;
    let config: ProxyConfig = parse_yaml(yaml).unwrap();
    assert_eq!(config.upstream.unwrap().default, "grpc://localhost:4180");
    assert_eq!(config.listen.http, "0.0.0.0:8080");
    assert_eq!(config.service.name, "structured-proxy");
    assert_eq!(config.streaming.sse_keep_alive_secs, 15);
    assert!(config.descriptors.is_empty());
    assert!(config.auth.is_none());
    assert!(config.shield.is_none());
}

#[test]
fn cors_defaults_cover_grpc_web_and_nothing_extra() {
    // Absent `cors:` and an empty one agree: permissive origins, gRPC-Web
    // included, no extra exposed headers, the browser's own preflight cache.
    for yaml in ["service:\n  name: demo\n", "cors: {}\n"] {
        let cors = parse_yaml::<ProxyConfig>(yaml).unwrap().cors;
        assert!(cors.origins.is_empty(), "{yaml}");
        assert!(cors.expose_headers.is_empty(), "{yaml}");
        assert_eq!(cors.max_age_secs, None, "{yaml}");
        assert!(cors.grpc_web, "{yaml}");
    }
}

#[test]
fn cors_settings_are_read() {
    let yaml = "cors:\n  origins: [\"https://app.example\"]\n  expose_headers: [\"x-request-id\"]\n  max_age_secs: 600\n  grpc_web: false\n";
    let cors = parse_yaml::<ProxyConfig>(yaml).unwrap().cors;
    assert_eq!(cors.origins, ["https://app.example"]);
    assert_eq!(cors.expose_headers, ["x-request-id"]);
    assert_eq!(cors.max_age_secs, Some(600));
    assert!(!cors.grpc_web);
}

#[test]
fn upstream_is_optional() {
    // An embedder whose upstream is in process names no address.
    let config: ProxyConfig = parse_yaml("service:\n  name: demo\n").unwrap();
    assert!(config.upstream.is_none());
}

#[test]
fn upstream_without_its_address_is_rejected() {
    // A present `upstream:` block must say where: an empty one is a mistake,
    // not a request for an in-process upstream.
    let err = parse_yaml::<ProxyConfig>("upstream: {}\n").unwrap_err();
    assert!(err.to_string().contains("default"), "{err}");
}

#[test]
fn jwks_max_age_defaults_and_overrides() {
    let yaml = "upstream:\n  default: \"grpc://x:1\"\nauth:\n  mode: jwt\n  jwt:\n    jwks_uri: \"https://idp/jwks\"\n";
    let cfg: ProxyConfig = parse_yaml(yaml).unwrap();
    assert_eq!(cfg.auth.unwrap().jwt.unwrap().jwks_max_age_secs, 300);

    let yaml = "upstream:\n  default: \"grpc://x:1\"\nauth:\n  mode: jwt\n  jwt:\n    jwks_uri: \"https://idp/jwks\"\n    jwks_max_age_secs: 120\n";
    let cfg: ProxyConfig = parse_yaml(yaml).unwrap();
    assert_eq!(cfg.auth.unwrap().jwt.unwrap().jwks_max_age_secs, 120);
}

#[test]
fn jwt_cache_defaults_and_overrides() {
    // Without a `cache:` block the cache is on with its defaults.
    let yaml = "upstream:\n  default: \"grpc://x:1\"\nauth:\n  mode: jwt\n  jwt:\n    jwks_uri: \"https://idp/jwks\"\n";
    let cfg: ProxyConfig = parse_yaml(yaml).unwrap();
    let cache = &cfg.auth.unwrap().jwt.unwrap().cache;
    assert!(cache.enabled);
    assert_eq!(cache.max_entries, 10_000);
    assert_eq!(cache.max_ttl_secs, 60);
    assert_eq!(cache.max_token_bytes, 4096);

    // Keys given keep the rest at their defaults.
    let yaml = "upstream:\n  default: \"grpc://x:1\"\nauth:\n  mode: jwt\n  jwt:\n    jwks_uri: \"https://idp/jwks\"\n    cache:\n      max_ttl_secs: 15\n      max_token_bytes: 2048\n";
    let cfg: ProxyConfig = parse_yaml(yaml).unwrap();
    let cache = &cfg.auth.unwrap().jwt.unwrap().cache;
    assert!(cache.enabled);
    assert_eq!(cache.max_entries, 10_000);
    assert_eq!(cache.max_ttl_secs, 15);
    assert_eq!(cache.max_token_bytes, 2048);
}

#[test]
fn jwt_cache_rejects_unknown_keys() {
    // `ttl` for `max_ttl_secs` would otherwise leave the default in force.
    let yaml = "upstream:\n  default: \"grpc://x:1\"\nauth:\n  mode: jwt\n  jwt:\n    cache:\n      ttl: 15\n";
    let err = parse_yaml::<ProxyConfig>(yaml).unwrap_err();
    assert!(err.to_string().contains("ttl"), "{err}");
}

#[test]
fn health_and_metrics_defaults_and_overrides() {
    // Defaults: enabled, conventional paths.
    let min: ProxyConfig = parse_yaml("upstream:\n  default: \"grpc://x:1\"\n").unwrap();
    assert!(min.health.enabled);
    assert_eq!(min.health.path, "/health");
    assert_eq!(min.health.ready_path, "/health/ready");
    assert!(min.metrics.enabled);
    assert_eq!(min.metrics.path, "/metrics");

    // Overrides apply; unspecified sub-paths keep their defaults.
    let yaml = r#"
upstream:
  default: "grpc://x:1"
health:
  path: "/internal/health"
metrics:
  enabled: false
  path: "/internal/metrics"
"#;
    let cfg: ProxyConfig = parse_yaml(yaml).unwrap();
    assert_eq!(cfg.health.path, "/internal/health");
    // live_path was not overridden, so it stays at the default.
    assert_eq!(cfg.health.live_path, "/health/live");
    assert!(!cfg.metrics.enabled);
    assert_eq!(cfg.metrics.path, "/internal/metrics");
}

#[test]
fn duplicate_probe_paths_are_rejected() {
    // health.path set to the default live_path collides on a single GET
    // route; reject at load instead of panicking in the router.
    let yaml = r#"
upstream:
  default: "grpc://x:1"
health:
  path: "/health/live"
"#;
    let err = ProxyConfig::from_yaml_str(yaml).unwrap_err();
    assert!(err.to_string().contains("duplicate endpoint path"));

    // A health path colliding with the metrics path is also rejected.
    let yaml2 = r#"
upstream:
  default: "grpc://x:1"
metrics:
  path: "/health"
"#;
    let err2 = ProxyConfig::from_yaml_str(yaml2).unwrap_err();
    assert!(err2.to_string().contains("duplicate endpoint path"));

    // Disabling a group frees its paths from the collision check.
    let yaml3 = r#"
upstream:
  default: "grpc://x:1"
health:
  enabled: false
  path: "/metrics"
"#;
    assert!(ProxyConfig::from_yaml_str(yaml3).is_ok());
}

#[test]
fn malformed_edge_path_is_rejected() {
    // A path without a leading '/' would make axum reject the route at
    // construction; catch it at config load with a clear message.
    let yaml = r#"
upstream:
  default: "grpc://x:1"
health:
  path: "health"
"#;
    let err = ProxyConfig::from_yaml_str(yaml).unwrap_err();
    assert!(err.to_string().contains("must start with '/'"));
}

#[test]
fn test_zero_sse_keep_alive_is_rejected() {
    // A zero keep-alive would make axum's SSE timer fire continuously
    // instead of acting as a periodic heartbeat — reject it at load time.
    let yaml = r#"
upstream:
  default: "grpc://localhost:4180"
streaming:
  sse_keep_alive_secs: 0
"#;
    let err = ProxyConfig::from_yaml_str(yaml).unwrap_err();
    assert!(err.to_string().contains("sse_keep_alive_secs"));
}

#[test]
fn test_full_config_deserialize() {
    let yaml = r#"
upstream:
  default: "grpc://sid-identity:4180"

descriptors:
  - file: "/etc/proxy/sid.descriptor.bin"

listen:
  http: "0.0.0.0:9090"

service:
  name: "sid-proxy"

aliases:
  - from: "/oauth2/{path}"
    to: "/v1/oauth2/{path}"

auth:
  mode: "jwt"
  jwt:
    issuer: "https://auth.example.com"
    public_key_pem_file: "/etc/proxy/signing.pub"
    claims_headers:
      sub: "x-forwarded-user"
      acr: "x-sid-auth-level"
  forward_auth:
    enabled: true
    path: "/auth/verify"
    policies:
      - path: "/v1/admin/**"
        require_auth: true
        required_roles: ["admin"]
      - path: "/v1/public/**"
        require_auth: false
  authz:
    enabled: true
    endpoint: "http://opa:9191"   # Envoy ext_authz server (gRPC)
    timeout_ms: 200
    failure_mode_allow: false      # fail closed: deny if authz is unreachable

shield:
  enabled: true
  profiles:
    auth: { rate: "20/min", burst: 5 }
    default: { rate: "100/min" }
    premium: { rate: "1000/min", burst: 50 }
  default_profile: "default"
  jwt_limits:
    tier_claim: "ratelimit_tier"
  rules:
    - pattern: "/v1/auth/**"
      key: { type: ip }
      profile: "auth"
    - pattern: "/v1/**"
      key: { type: jwt_claim, claim: "sub" }

client_address:
  trusted_proxies: ["10.0.0.0/8"]

oidc_discovery:
  enabled: true
  issuer: "https://auth.example.com"

maintenance:
  enabled: false
  exempt_paths:
    - "/health/**"
    - "/.well-known/**"

cors:
  origins:
    - "https://app.example.com"

metrics_classes:
  - pattern: "/v1/auth/**"
    class: "auth"
  - pattern: "/v1/admin/**"
    class: "admin"

forwarded_headers:
  - "authorization"
  - "dpop"
  - "x-request-id"
"#;
    let config: ProxyConfig = parse_yaml(yaml).unwrap();
    assert_eq!(
        config.upstream.as_ref().unwrap().default,
        "grpc://sid-identity:4180"
    );
    assert_eq!(config.listen.http, "0.0.0.0:9090");
    assert_eq!(config.service.name, "sid-proxy");
    assert_eq!(config.aliases.len(), 1);
    assert!(config.auth.is_some());
    let authz = config.auth.as_ref().unwrap().authz.as_ref().unwrap();
    assert!(authz.enabled);
    assert_eq!(authz.endpoint, "http://opa:9191");
    assert_eq!(authz.timeout_ms, 200);
    assert!(!authz.failure_mode_allow);
    assert!(config.shield.is_some());
    assert_eq!(config.client_address.trusted_proxies, ["10.0.0.0/8"]);
    assert!(config.oidc_discovery.is_some());
    assert_eq!(config.cors.origins.len(), 1);
    assert_eq!(config.metrics_classes.len(), 2);
    assert_eq!(config.forwarded_headers.len(), 3);
}

#[test]
fn authz_disabled_without_endpoint_parses() {
    // A disabled authz block need not supply an endpoint.
    let yaml = r#"
upstream:
  default: "grpc://localhost:4180"
descriptors:
  - file: "/x.bin"
auth:
  mode: "jwt"
  authz:
    enabled: false
"#;
    let config: ProxyConfig = parse_yaml(yaml).unwrap();
    let authz = config.auth.unwrap().authz.unwrap();
    assert!(!authz.enabled);
    assert_eq!(authz.endpoint, "");
}

#[test]
fn test_descriptor_source_file() {
    let yaml = r#"
upstream:
  default: "grpc://localhost:4180"
descriptors:
  - file: "/etc/proxy/service.descriptor.bin"
"#;
    let config: ProxyConfig = parse_yaml(yaml).unwrap();
    assert_eq!(config.descriptors.len(), 1);
    match &config.descriptors[0] {
        DescriptorSource::File { file } => {
            assert_eq!(file.to_str().unwrap(), "/etc/proxy/service.descriptor.bin");
        }
        _ => panic!("expected File descriptor source"),
    }
}

#[test]
fn test_descriptor_source_reflection() {
    let yaml = r#"
upstream:
  default: "grpc://localhost:4180"
descriptors:
  - reflection: "grpc://localhost:4180"
"#;
    let config: ProxyConfig = parse_yaml(yaml).unwrap();
    match &config.descriptors[0] {
        DescriptorSource::Reflection { reflection } => {
            assert_eq!(reflection, "grpc://localhost:4180");
        }
        _ => panic!("expected Reflection descriptor source"),
    }
}

#[test]
fn test_parse_rate() {
    assert_eq!(ProxyConfig::parse_rate("20/min"), Some(20));
    assert_eq!(ProxyConfig::parse_rate("100/min"), Some(100));
    assert_eq!(ProxyConfig::parse_rate("5/min"), Some(5));
    assert_eq!(ProxyConfig::parse_rate("invalid"), None);
}

#[test]
fn shield_rejects_unknown_field() {
    // A typo in a shield-config field (here `profil` for `profile`) must be a
    // hard error, not silently ignored: a misspelled security-control key
    // would otherwise leave the intended limit unapplied. `deny_unknown_fields`
    // on the shield structs turns the typo into a startup failure.
    let yaml = r#"
upstream:
  default: "grpc://localhost:4180"
shield:
  enabled: true
  profiles:
    auth: { rate: "20/min", burst: 5 }
  rules:
    - pattern: "/v1/**"
      key: { type: ip }
      profil: "auth"
"#;
    let err = parse_yaml::<ProxyConfig>(yaml);
    assert!(err.is_err(), "unknown shield field must be rejected");
}

#[test]
fn shield_rejects_unknown_field_in_rule_key() {
    // A stray field inside a rule key (here `name` on an `ip` key, a copy-edit
    // leftover) must be a hard error. Silently ignoring it would keep the rule
    // IP-keyed instead of the intended per-header limit, weakening the control.
    let yaml = r#"
upstream:
  default: "grpc://localhost:4180"
shield:
  enabled: true
  profiles:
    auth: { rate: "20/min", burst: 5 }
  rules:
    - pattern: "/v1/**"
      key: { type: ip, name: x-api-key }
      profile: "auth"
"#;
    let err = parse_yaml::<ProxyConfig>(yaml);
    assert!(err.is_err(), "unknown field in a rule key must be rejected");
}

#[test]
fn test_openapi_config_deserialize() {
    let yaml = r#"
upstream:
  default: "grpc://localhost:4180"
openapi:
  enabled: true
  path: "/api/openapi.json"
  docs_path: "/api/docs"
  title: "Test API"
  version: "2.0.0"
"#;
    let config: ProxyConfig = parse_yaml(yaml).unwrap();
    let openapi = config.openapi.unwrap();
    assert!(openapi.enabled);
    assert_eq!(openapi.path, "/api/openapi.json");
    assert_eq!(openapi.docs_path, "/api/docs");
    assert_eq!(openapi.title.unwrap(), "Test API");
    assert_eq!(openapi.version.unwrap(), "2.0.0");
}

#[test]
fn test_openapi_config_defaults() {
    let yaml = r#"
upstream:
  default: "grpc://localhost:4180"
openapi:
  enabled: true
"#;
    let config: ProxyConfig = parse_yaml(yaml).unwrap();
    let openapi = config.openapi.unwrap();
    assert!(openapi.enabled);
    assert_eq!(openapi.path, "/openapi.json");
    assert_eq!(openapi.docs_path, "/docs");
    assert!(openapi.title.is_none());
    assert!(openapi.version.is_none());
}

#[test]
fn misspelled_top_level_key_is_reported() {
    // `error_detail:` for `error_details:` would leave details on silently;
    // it is reported, while known keys (including the ones read outside
    // ProxyConfig) are not.
    let yaml = r#"
upstream:
  default: "grpc://x:1"
streaming:
  ndjson_envelope: true
error_details:
  enabled: false
error_detail:
  enabled: false
maintenence:
  enabled: true
"#;
    assert_eq!(
        unknown_config_keys(yaml),
        vec!["error_detail".to_string(), "maintenence".to_string()]
    );
}

#[test]
fn misspelled_streaming_key_is_reported() {
    // `streaming:` is read by two structs that must accept each other's keys,
    // so neither rejects a typo such as `ndjson_envelop:`, which would leave
    // unenveloped framing silently in force; it is reported by its path.
    let yaml = r#"
upstream:
  default: "grpc://x:1"
streaming:
  sse_keep_alive_secs: 5
  ndjson_envelope: true
  ndjson_envelop: true
"#;
    assert_eq!(
        unknown_config_keys(yaml),
        vec!["streaming.ndjson_envelop".to_string()]
    );
}

#[test]
fn known_top_level_keys_cover_every_proxy_config_field() {
    // Exhaustive destructuring: adding a ProxyConfig field fails to compile
    // here until the field is also listed as a known top-level key.
    let config: ProxyConfig = parse_yaml("upstream:\n  default: \"grpc://x:1\"\n").unwrap();
    let ProxyConfig {
        upstream: _,
        descriptors: _,
        listen: _,
        service: _,
        aliases: _,
        openapi: _,
        auth: _,
        shield: _,
        oidc_discovery: _,
        health: _,
        metrics: _,
        maintenance: _,
        cors: _,
        logging: _,
        metrics_classes: _,
        forwarded_headers: _,
        streaming: _,
        concurrency: _,
        grpc_web: _,
        transcode: _,
        client_address: _,
    } = config;
    for key in [
        "upstream",
        "descriptors",
        "listen",
        "service",
        "aliases",
        "openapi",
        "auth",
        "shield",
        "oidc_discovery",
        "health",
        "metrics",
        "maintenance",
        "cors",
        "logging",
        "metrics_classes",
        "forwarded_headers",
        "streaming",
        "error_details",
        "response_headers",
        "runtime",
        "concurrency",
        "grpc_web",
        "transcode",
        "client_address",
    ] {
        assert!(KNOWN_TOP_LEVEL_KEYS.contains(&key), "{key}");
    }
    assert_eq!(KNOWN_TOP_LEVEL_KEYS.len(), 24);
}

#[test]
fn client_address_reads_its_section() {
    let config = ProxyConfig::from_yaml_str(
        "client_address:\n  trusted_proxies: [\"10.0.0.0/8\", \"192.0.2.10\"]\n  header: x_real_ip\n  required: true\n",
    )
    .unwrap();
    assert_eq!(
        config.client_address.trusted_proxies,
        ["10.0.0.0/8", "192.0.2.10"]
    );
    assert_eq!(config.client_address.header, ForwardingHeader::XRealIp);
    assert!(config.client_address.required);
    // The defaults trust no proxy: a proxy facing its clients directly.
    let config = ProxyConfig::from_yaml_str("").unwrap();
    assert!(config.client_address.trusted_proxies.is_empty());
    assert_eq!(
        config.client_address.header,
        ForwardingHeader::XForwardedFor
    );
    assert!(!config.client_address.required);
}

#[test]
fn client_address_forward_reads_its_section() {
    let config = ProxyConfig::from_yaml_str(
        "client_address:\n  forward:\n    x_forwarded_for: append\n    client_header: cf-connecting-ip\n    audit_header: x-original-forwarded-for\n",
    )
    .unwrap();
    let forward = &config.client_address.forward;
    assert_eq!(forward.x_forwarded_for, XForwardedFor::Append);
    assert_eq!(forward.client_header.as_deref(), Some("cf-connecting-ip"));
    assert_eq!(
        forward.audit_header.as_deref(),
        Some("x-original-forwarded-for")
    );
    // `null` turns the client header off.
    let config =
        ProxyConfig::from_yaml_str("client_address:\n  forward:\n    client_header: null\n")
            .unwrap();
    assert_eq!(config.client_address.forward.client_header, None);
    // The defaults forward nothing a client can forge, and audit nothing.
    let forward = ProxyConfig::from_yaml_str("")
        .unwrap()
        .client_address
        .forward;
    assert_eq!(forward.x_forwarded_for, XForwardedFor::Verified);
    assert_eq!(forward.client_header.as_deref(), Some("x-real-ip"));
    assert_eq!(forward.audit_header, None);
    for mode in ["verified", "resolved", "append", "preserve", "remove"] {
        let yaml = format!("client_address:\n  forward:\n    x_forwarded_for: {mode}\n");
        assert!(ProxyConfig::from_yaml_str(&yaml).is_ok(), "{mode}");
    }
}

#[test]
fn an_invalid_client_address_section_fails_to_load() {
    for yaml in [
        // Not a range or an address.
        "client_address:\n  trusted_proxies: [\"10.0.0.0/33\"]\n",
        // A header the resolution does not read.
        "client_address:\n  header: forwarded\n",
        // A typo would leave the default in force.
        "client_address:\n  trusted_proxy: [\"10.0.0.0/8\"]\n",
        // A mode that does not exist, a typo inside `forward`.
        "client_address:\n  forward:\n    x_forwarded_for: rewrite\n",
        "client_address:\n  forward:\n    client_headers: x-real-ip\n",
        // A client header the forwarding writes already, or no header at all.
        "client_address:\n  forward:\n    client_header: x-forwarded-for\n",
        "client_address:\n  forward:\n    client_header: \"not a header\"\n",
        // An audit header that would overwrite the client header.
        "client_address:\n  forward:\n    audit_header: x-real-ip\n",
    ] {
        assert!(ProxyConfig::from_yaml_str(yaml).is_err(), "{yaml}");
    }
}

#[test]
fn shield_trusted_proxies_names_its_new_place() {
    // The list moved to `client_address`; the error says where, rather than
    // only that the field is unknown.
    let err = ProxyConfig::from_yaml_str(
        "shield:\n  enabled: true\n  trusted_proxies: [\"10.0.0.0/8\"]\n",
    )
    .unwrap_err();
    assert!(
        err.to_string().contains("client_address.trusted_proxies"),
        "{err}"
    );
    // Any other mistake keeps its own message.
    let err = ProxyConfig::from_yaml_str("shield:\n  enabld: true\n").unwrap_err();
    assert!(err.to_string().contains("enabld"), "{err}");
}

#[test]
fn the_default_forwarded_headers_carry_no_client_address() {
    // The upstream gets the resolved address in their place.
    let config = ProxyConfig::default();
    for owned in ["x-forwarded-for", "x-real-ip", "forwarded"] {
        assert!(
            !config.forwarded_headers.iter().any(|h| h == owned),
            "{owned}"
        );
    }
}

#[test]
fn runtime_key_is_known() {
    // `runtime:` is the standalone binary's section: the library does not
    // read it, but a file written for the binary must load through the
    // library without a warning, while a misspelling of it is reported.
    let yaml = r#"
upstream:
  default: "grpc://x:1"
runtime:
  worker_threads: 2
runtimes:
  worker_threads: 2
"#;
    assert_eq!(unknown_config_keys(yaml), vec!["runtimes".to_string()]);
}

#[test]
fn response_headers_key_is_known() {
    // The deny-list lives outside ProxyConfig; its key must not be reported
    // as a typo, while a misspelling of it is.
    let yaml = r#"
upstream:
  default: "grpc://x:1"
response_headers:
  deny: ["x-debug-trace"]
response_header:
  deny: ["x-debug-trace"]
"#;
    assert_eq!(
        unknown_config_keys(yaml),
        vec!["response_header".to_string()]
    );
}

#[test]
fn transcode_settings_read_the_response_header_deny_list() {
    // Names are normalized to lowercase header names, in order.
    let options = transcode_options(
        "upstream:\n  default: \"grpc://x:1\"\nresponse_headers:\n  deny: [\"X-Debug-Trace\", \"x-backend\"]\n",
    )
    .unwrap();
    assert_eq!(
        options
            .denied_response_headers
            .iter()
            .map(|name| name.as_str())
            .collect::<Vec<_>>(),
        ["x-debug-trace", "x-backend"]
    );
}

#[test]
fn transcode_settings_without_response_headers_deny_nothing() {
    let options = transcode_options("upstream:\n  default: \"grpc://x:1\"\n").unwrap();
    assert!(options.denied_response_headers.is_empty());
}

#[test]
fn transcode_settings_reject_an_invalid_deny_entry() {
    // A space is not allowed in a header name; the entry could never match.
    let err = transcode_options(
        "upstream:\n  default: \"grpc://x:1\"\nresponse_headers:\n  deny: [\"x debug\"]\n",
    )
    .unwrap_err();
    assert!(err.contains("not a header name"), "{err}");
}

#[test]
fn transcode_settings_reject_unknown_response_headers_key() {
    // `denied` for `deny` would otherwise let the header through silently.
    let err = transcode_options(
        "upstream:\n  default: \"grpc://x:1\"\nresponse_headers:\n  denied: [\"x-debug-trace\"]\n",
    )
    .unwrap_err();
    assert!(err.contains("denied"), "{err}");
}

#[test]
fn known_streaming_keys_cover_both_streaming_structs() {
    // Exhaustive destructuring: a new field in either struct reading
    // `streaming:` fails to compile here until it is listed as known.
    let StreamingConfig {
        sse_keep_alive_secs: _,
    } = StreamingConfig::default();
    let StreamingFileConfig { ndjson_envelope: _ } = StreamingFileConfig::default();
    assert_eq!(
        KNOWN_STREAMING_KEYS,
        &["sse_keep_alive_secs", "ndjson_envelope"]
    );
}

/// The transcoding options a YAML document compiles to.
fn transcode_options(yaml: &str) -> Result<crate::transcode::TranscodeOptions, String> {
    parse_yaml::<TranscodeFileConfig>(yaml)
        .map_err(|e| e.to_string())?
        .options()
}

#[test]
fn transcode_settings_default_to_details_everywhere_and_no_envelope() {
    // A file that names neither key keeps the defaults: details on every
    // route, bare NDJSON lines.
    let options = transcode_options("upstream:\n  default: \"grpc://x:1\"\n").unwrap();
    assert!(options.error_details.enabled_for("/v1/users/{id}"));
    assert!(!options.ndjson_envelope);
}

#[test]
fn transcode_settings_read_error_details_and_the_ndjson_envelope() {
    // Both keys come from the same file as the ProxyConfig, next to its own
    // `streaming` keys, and the route rules keep their order.
    let yaml = r#"
upstream:
  default: "grpc://x:1"
streaming:
  sse_keep_alive_secs: 30
  ndjson_envelope: true
error_details:
  enabled: false
  routes:
    - pattern: "/v1/public/internal/*"
      enabled: false
    - pattern: "/v1/public/**"
      enabled: true
"#;
    let options = transcode_options(yaml).unwrap();
    assert!(options.ndjson_envelope);
    assert!(options.error_details.enabled_for("/v1/public/items"));
    assert!(!options
        .error_details
        .enabled_for("/v1/public/internal/{id}"));
    assert!(!options.error_details.enabled_for("/v1/admin/items"));
    // The ProxyConfig still reads its own streaming key from the same section.
    let config: ProxyConfig = parse_yaml(yaml).unwrap();
    assert_eq!(config.streaming.sse_keep_alive_secs, 30);
}

#[test]
fn transcode_settings_reject_unknown_error_details_key() {
    // `enable` for `enabled` would otherwise leave details on silently.
    let err = transcode_options(
        "upstream:\n  default: \"grpc://x:1\"\nerror_details:\n  enable: false\n",
    )
    .unwrap_err();
    assert!(err.contains("enable"), "{err}");
}

#[test]
fn transcode_settings_require_enabled_on_a_route_rule() {
    // A rule without `enabled` states no decision.
    let err = transcode_options(
        "upstream:\n  default: \"grpc://x:1\"\nerror_details:\n  routes:\n    - pattern: \"/v1/**\"\n",
    )
    .unwrap_err();
    assert!(err.contains("enabled"), "{err}");
}

#[test]
fn transcode_settings_reject_a_relative_route_pattern() {
    // `v1/admin/**` never matches a route path; accepting it would leave
    // details on where the operator meant to turn them off.
    let err = transcode_options(
        "upstream:\n  default: \"grpc://x:1\"\nerror_details:\n  routes:\n    - pattern: \"v1/admin/**\"\n      enabled: false\n",
    )
    .unwrap_err();
    assert!(err.contains("must start with '/'"), "{err}");
}

#[test]
fn json_text_reads_as_a_config() {
    // Embedders build configurations as JSON and hand the text to
    // `from_yaml_str`: JSON is YAML, and must stay accepted.
    let json = r#"{"upstream": {"default": "grpc://x:1"}, "service": {"name": "demo"},
        "cors": {"origins": ["https://app.example"], "grpc_web": false},
        "streaming": {"sse_keep_alive_secs": 5, "ndjson_envelope": true}}"#;
    let config = ProxyConfig::from_yaml_str(json).unwrap();
    assert_eq!(config.upstream.unwrap().default, "grpc://x:1");
    assert_eq!(config.service.name, "demo");
    assert_eq!(config.cors.origins, ["https://app.example"]);
    assert!(!config.cors.grpc_web);
    assert_eq!(config.streaming.sse_keep_alive_secs, 5);
    assert!(transcode_options(json).unwrap().ndjson_envelope);
    assert!(unknown_config_keys(json).is_empty());
}

#[test]
fn only_yaml_1_2_booleans_are_booleans() {
    // `yes`, `on` and friends are YAML 1.1; a reader that took them for
    // booleans would turn on settings the format never defined that way.
    for value in ["yes", "no", "on", "off", "Y", "n"] {
        let err = ProxyConfig::from_yaml_str(&format!("cors:\n  grpc_web: {value}\n")).unwrap_err();
        assert!(err.to_string().contains("cors.grpc_web"), "{value}: {err}");
    }
    // The YAML 1.2 core schema spells them in three cases; files written for
    // the earlier reader use all of them.
    for (value, expected) in [
        ("true", true),
        ("True", true),
        ("TRUE", true),
        ("false", false),
        ("False", false),
        ("FALSE", false),
    ] {
        let config = ProxyConfig::from_yaml_str(&format!("cors:\n  grpc_web: {value}\n")).unwrap();
        assert_eq!(config.cors.grpc_web, expected, "{value}");
    }
}

#[test]
fn the_packaged_config_template_loads() {
    // The RPM/DEB packages install it as the starting config.
    let yaml = include_str!("../../packaging/config.yaml");
    let config = ProxyConfig::from_yaml_str(yaml).unwrap();
    assert_eq!(config.service.name, "structured-proxy");
    assert!(unknown_config_keys(yaml).is_empty());
}

#[test]
fn a_number_or_boolean_is_not_taken_for_text() {
    // A setting that names something (a service, a header) holds text; an
    // unquoted `true` or `123` there is a mistake to report, not a name to
    // start with. Quoted, it is the text it spells.
    for yaml in [
        "service:\n  name: true\n",
        "service:\n  name: 8080\n",
        "service:\n  name: 1.5\n",
        "forwarded_headers: [123]\n",
        "cors:\n  origins: [false]\n",
    ] {
        assert!(ProxyConfig::from_yaml_str(yaml).is_err(), "{yaml}");
    }
    let config = ProxyConfig::from_yaml_str("service:\n  name: \"8080\"\n").unwrap();
    assert_eq!(config.service.name, "8080");
    let config = ProxyConfig::from_yaml_str("forwarded_headers: ['123', x-request-id]\n").unwrap();
    assert_eq!(config.forwarded_headers, ["123", "x-request-id"]);
}

#[test]
fn a_parse_error_names_the_key_path_on_one_line() {
    // The key path tells the operator where the mistake is; the message stays
    // on one line so a log record holds all of it.
    let err = ProxyConfig::from_yaml_str("cors:\n  max_age_secs: soon\n").unwrap_err();
    let message = err.to_string();
    assert!(message.starts_with("cors.max_age_secs: "), "{message}");
    assert!(!message.contains('\n'), "{message}");

    // Inside a list, the index is part of the path.
    let yaml =
        "shield:\n  rules:\n    - pattern: \"/**\"\n      key: { type: ip }\n      profil: anon\n";
    let message = ProxyConfig::from_yaml_str(yaml).unwrap_err().to_string();
    assert!(message.contains("shield.rules[0]"), "{message}");
    assert!(message.contains("profil"), "{message}");
}

#[test]
fn a_document_that_is_not_a_config_map_is_refused_without_a_path() {
    // Nothing inside the document is at fault, so no path is named.
    for yaml in ["just text", "[1, 2]", "upstream: [unclosed"] {
        let message = parse_yaml::<ProxyConfig>(yaml).unwrap_err().to_string();
        assert!(!message.is_empty(), "{yaml}");
        assert!(!message.starts_with(':'), "{yaml}: {message}");
        assert!(!message.contains('\n'), "{yaml}: {message}");
    }
}

#[test]
fn an_empty_document_is_the_default_config() {
    // A file with only comments, like an empty one, sets nothing.
    for yaml in ["", "# nothing set yet\n", "---\n"] {
        let config = ProxyConfig::from_yaml_str(yaml).unwrap();
        assert!(config.upstream.is_none(), "{yaml:?}");
        assert_eq!(config.listen.http, "0.0.0.0:8080", "{yaml:?}");
        assert!(unknown_config_keys(yaml).is_empty(), "{yaml:?}");
    }
}

#[test]
fn a_repeated_key_is_refused() {
    // Which of two values would win is not something to guess for a config.
    let err = ProxyConfig::from_yaml_str("service:\n  name: a\nservice:\n  name: b\n").unwrap_err();
    assert!(err.to_string().contains("service"), "{err}");
}

#[test]
fn more_than_one_document_is_refused() {
    // Only the first would be read; the rest would be silently dropped.
    assert!(ProxyConfig::from_yaml_str("service:\n  name: a\n---\nservice:\n  name: b\n").is_err());
}

#[test]
fn unknown_keys_keep_the_document_order() {
    // Reported in the order the operator wrote them, streaming ones by path.
    let yaml =
        "zeta: 1\nupstream:\n  default: \"grpc://x:1\"\nalpha: 2\nstreaming:\n  zz: 1\n  aa: 2\n";
    assert_eq!(
        unknown_config_keys(yaml),
        ["zeta", "alpha", "streaming.zz", "streaming.aa"]
    );
}

#[test]
fn unknown_keys_of_an_unreadable_document_are_none() {
    // The parse error is the one to report; there is no key list to warn on.
    for yaml in [
        "just text",
        "[1, 2]",
        "upstream: [unclosed",
        "streaming: 5\n",
    ] {
        assert!(unknown_config_keys(yaml).is_empty(), "{yaml}");
    }
}

#[test]
fn an_empty_streaming_section_has_no_unknown_keys() {
    // `streaming:` with no value sets nothing; it is no typo.
    assert!(unknown_config_keys("streaming:\nstreamin:\n") == ["streamin"]);
}

#[test]
fn a_number_or_boolean_key_leaves_the_other_keys_reported() {
    // No setting is named by a number or a boolean, so such a key is skipped,
    // and the typos beside it are still reported.
    assert_eq!(
        unknown_config_keys(
            "8080: listen\ntrue: 1\nmaintenence: {}\nstreaming:\n  5: x\n  ndjson_envelop: true\n"
        ),
        ["maintenence", "streaming.ndjson_envelop"]
    );
}

#[test]
fn shield_trusted_proxies_names_its_new_place_even_when_empty() {
    // An empty value still shows where the operator meant to set the list.
    let err = ProxyConfig::from_yaml_str("shield:\n  trusted_proxies:\n").unwrap_err();
    assert!(
        err.to_string().contains("client_address.trusted_proxies"),
        "{err}"
    );
    // A `shield:` that is not a map has its own error, not this one.
    let err = ProxyConfig::from_yaml_str("shield: 5\n").unwrap_err();
    assert!(
        !err.to_string().contains("client_address.trusted_proxies"),
        "{err}"
    );
}