structured-proxy 3.0.0

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
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
//! YAML-based proxy configuration.
//!
//! All product-specific behavior is driven by config, not code.
//! Same binary, different YAML = different product proxy.

use serde::Deserialize;
use std::path::PathBuf;

/// Top-level proxy configuration (loaded from YAML).
///
/// This and the wiring structs below (`UpstreamConfig`, `ListenConfig`,
/// `ServiceConfig`, `DescriptorSource`) are intentionally NOT
/// `#[non_exhaustive]`: embedding consumers build them programmatically with
/// runtime values. The leaf auth/shield/oidc config structs are
/// `#[non_exhaustive]` instead, since those are deserialized, not hand-built.
#[derive(Debug, Clone, Deserialize)]
pub struct ProxyConfig {
    /// Upstream gRPC service(s).
    pub upstream: UpstreamConfig,

    /// Proto descriptor sources.
    #[serde(default, deserialize_with = "deserialize_descriptor_sources")]
    pub descriptors: Vec<DescriptorSource>,

    /// Listen addresses.
    #[serde(default)]
    pub listen: ListenConfig,

    /// Service identity (for health endpoint, metrics namespace).
    #[serde(default)]
    pub service: ServiceConfig,

    /// Path aliases (e.g., /oauth2/* → /v1/oauth2/*).
    #[serde(default)]
    pub aliases: Vec<AliasConfig>,

    /// OpenAPI generation.
    #[serde(default)]
    pub openapi: Option<OpenApiConfig>,

    /// Auth configuration (JWT, forward auth, AuthZ).
    #[serde(default)]
    pub auth: Option<AuthConfig>,

    /// Rate limiting (Shield).
    #[serde(default)]
    pub shield: Option<ShieldConfig>,

    /// OIDC discovery (optional — for IdP proxies).
    #[serde(default)]
    pub oidc_discovery: Option<OidcDiscoveryConfig>,

    /// Health-probe endpoints (paths configurable; can be disabled).
    #[serde(default)]
    pub health: HealthConfig,

    /// Prometheus metrics endpoint (path configurable; can be disabled).
    #[serde(default)]
    pub metrics: MetricsConfig,

    /// Maintenance mode.
    #[serde(default)]
    pub maintenance: MaintenanceConfig,

    /// CORS configuration.
    #[serde(default)]
    pub cors: CorsConfig,

    /// Logging.
    #[serde(default)]
    pub logging: LoggingConfig,

    /// Metrics endpoint classification (path patterns → class labels).
    #[serde(default)]
    pub metrics_classes: Vec<MetricsClassConfig>,

    /// Headers to forward from HTTP to gRPC metadata.
    #[serde(default = "default_forwarded_headers")]
    pub forwarded_headers: Vec<String>,

    /// Server-streaming response behavior.
    #[serde(default)]
    pub streaming: StreamingConfig,
}

fn default_forwarded_headers() -> Vec<String> {
    vec![
        "authorization".into(),
        "dpop".into(),
        "x-request-id".into(),
        "x-forwarded-for".into(),
        "x-forwarded-proto".into(),
        "x-real-ip".into(),
        "accept-language".into(),
        "user-agent".into(),
        "idempotency-key".into(),
    ]
}

/// Server-streaming response behavior.
///
/// Server-streaming RPCs are exposed as NDJSON by default and as Server-Sent
/// Events when the client sends `Accept: text/event-stream`. The keep-alive
/// interval applies only to the SSE path.
#[derive(Debug, Clone, Deserialize)]
pub struct StreamingConfig {
    /// SSE keep-alive interval in seconds. Comment frames are emitted on idle
    /// streams to keep intermediaries (load balancers, nginx) from closing the
    /// connection on read timeout. Default: 15.
    #[serde(default = "default_sse_keep_alive_secs")]
    pub sse_keep_alive_secs: u64,
}

fn default_sse_keep_alive_secs() -> u64 {
    15
}

impl Default for StreamingConfig {
    fn default() -> Self {
        Self {
            sse_keep_alive_secs: default_sse_keep_alive_secs(),
        }
    }
}

/// Upstream gRPC service configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct UpstreamConfig {
    /// gRPC upstream address (e.g., "http://localhost:4180").
    pub default: String,
}

/// Descriptor loading source.
#[derive(Debug, Clone)]
pub enum DescriptorSource {
    /// Pre-compiled descriptor file.
    File { file: PathBuf },
    /// gRPC server reflection (development mode).
    Reflection { reflection: String },
    /// Embedded bytes (set programmatically, not from YAML).
    Embedded { bytes: &'static [u8] },
}

/// Helper for YAML deserialization (only File and Reflection variants).
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
enum DescriptorSourceYaml {
    File { file: PathBuf },
    Reflection { reflection: String },
}

impl From<DescriptorSourceYaml> for DescriptorSource {
    fn from(yaml: DescriptorSourceYaml) -> Self {
        match yaml {
            DescriptorSourceYaml::File { file } => DescriptorSource::File { file },
            DescriptorSourceYaml::Reflection { reflection } => {
                DescriptorSource::Reflection { reflection }
            }
        }
    }
}

fn deserialize_descriptor_sources<'de, D>(
    deserializer: D,
) -> std::result::Result<Vec<DescriptorSource>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let yaml_sources: Vec<DescriptorSourceYaml> = Vec::deserialize(deserializer)?;
    Ok(yaml_sources.into_iter().map(Into::into).collect())
}

/// Listen address configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct ListenConfig {
    /// HTTP listen address (default: "0.0.0.0:8080").
    #[serde(default = "default_http_listen")]
    pub http: String,
}

fn default_http_listen() -> String {
    "0.0.0.0:8080".into()
}

impl Default for ListenConfig {
    fn default() -> Self {
        Self {
            http: default_http_listen(),
        }
    }
}

/// Service identity.
#[derive(Debug, Clone, Deserialize)]
pub struct ServiceConfig {
    /// Service name (appears in /health response and metrics namespace).
    #[serde(default = "default_service_name")]
    pub name: String,
}

fn default_service_name() -> String {
    "structured-proxy".into()
}

impl Default for ServiceConfig {
    fn default() -> Self {
        Self {
            name: default_service_name(),
        }
    }
}

/// Path alias (rewrite before routing).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AliasConfig {
    pub from: String,
    pub to: String,
}

/// OpenAPI generation config.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct OpenApiConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Path for OpenAPI JSON spec (default: "/openapi.json").
    #[serde(default = "default_openapi_path")]
    pub path: String,
    /// Path for interactive API docs UI (default: "/docs").
    #[serde(default = "default_docs_path")]
    pub docs_path: String,
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub version: Option<String>,
}

fn default_openapi_path() -> String {
    "/openapi.json".into()
}

fn default_docs_path() -> String {
    "/docs".into()
}

fn default_true() -> bool {
    true
}

/// Auth configuration.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AuthConfig {
    /// Auth mode: "none", "jwt", "api_key".
    #[serde(default = "default_auth_mode")]
    pub mode: String,

    /// JWT validation config.
    #[serde(default)]
    pub jwt: Option<JwtConfig>,

    /// Forward auth endpoint.
    #[serde(default)]
    pub forward_auth: Option<ForwardAuthConfig>,

    /// AuthZ integration (optional gRPC call).
    #[serde(default)]
    pub authz: Option<AuthzConfig>,
}

fn default_auth_mode() -> String {
    "none".into()
}

/// JWT validation config.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct JwtConfig {
    /// JWKS URI for key discovery.
    #[serde(default)]
    pub jwks_uri: Option<String>,
    /// Expected issuer.
    #[serde(default)]
    pub issuer: Option<String>,
    /// Expected audience.
    #[serde(default)]
    pub audience: Option<String>,
    /// Path to Ed25519 public key PEM file (alternative to JWKS URI).
    #[serde(default)]
    pub public_key_pem_file: Option<PathBuf>,
    /// Claims → HTTP headers mapping.
    #[serde(default)]
    pub claims_headers: std::collections::HashMap<String, String>,
    /// Claim holding the user's roles (array of strings). Supports a dotted
    /// path for nested claims, e.g. "realm_access.roles". Default: "roles".
    #[serde(default = "default_roles_claim")]
    pub roles_claim: String,
}

fn default_roles_claim() -> String {
    "roles".into()
}

/// Forward auth config.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ForwardAuthConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default = "default_forward_auth_path")]
    pub path: String,
    /// Route policies.
    #[serde(default)]
    pub policies: Vec<RoutePolicyConfig>,
    /// Login URL for 401 redirects.
    #[serde(default)]
    pub login_url: Option<String>,
    /// Applications YAML file path.
    #[serde(default)]
    pub applications_path: Option<PathBuf>,
}

fn default_forward_auth_path() -> String {
    "/auth/verify".into()
}

/// Route policy entry.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutePolicyConfig {
    pub path: String,
    #[serde(default = "default_methods_all")]
    pub methods: Vec<String>,
    #[serde(default)]
    pub require_auth: bool,
    #[serde(default)]
    pub required_roles: Vec<String>,
}

fn default_methods_all() -> Vec<String> {
    vec!["*".into()]
}

/// External authorization via the Envoy ext_authz gRPC contract
/// (`envoy.service.auth.v3.Authorization/Check`). Interops with OPA and any
/// ext_authz server.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AuthzConfig {
    /// Enable external authorization for proxied API requests.
    #[serde(default)]
    pub enabled: bool,
    /// gRPC address of the ext_authz server, e.g. `http://opa:9191`. Required
    /// when enabled; defaults to empty so a disabled block can omit it.
    #[serde(default)]
    pub endpoint: String,
    /// Per-request authorization call timeout, in milliseconds.
    #[serde(default = "default_authz_timeout_ms")]
    pub timeout_ms: u64,
    /// When the authz call itself fails (unreachable / timeout), allow the
    /// request through instead of denying. Defaults to false (fail closed).
    #[serde(default)]
    pub failure_mode_allow: bool,
}

fn default_authz_timeout_ms() -> u64 {
    200
}

/// Shield (rate limiting) configuration.
///
/// The proxy runs embedded on each service instance, so every limit decision is
/// made locally with a GCRA shaper (zero blocking latency). A shared store, when
/// configured via [`sync`](ShieldConfig::sync), is reconciled asynchronously off
/// the request path to approximate a fleet-wide limit; the request path never
/// blocks on it.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ShieldConfig {
    #[serde(default)]
    pub enabled: bool,
    /// Named limit tiers referenced by rules and by tier-name resolution (JWT
    /// claim / limit service). Map of profile name → `{ rate, burst }`.
    #[serde(default)]
    pub profiles: std::collections::HashMap<String, LimitProfileConfig>,
    /// Rate-limit rules, evaluated in order; the first whose pattern matches the
    /// request path applies.
    #[serde(default)]
    pub rules: Vec<RateRuleConfig>,
    /// Profile name applied when a matched rule resolves no other limit (JWT and
    /// service resolution absent or empty, and the rule sets no explicit
    /// profile). Must name an entry in `profiles`.
    #[serde(default)]
    pub default_profile: Option<String>,
    /// Resolve a key's limit from claims in the validated JWT. Presence enables
    /// JWT-based resolution (tier name or explicit numbers).
    #[serde(default)]
    pub jwt_limits: Option<JwtLimitConfig>,
    /// Resolve a key's limit from an external service. The lookup is cached and
    /// refreshed in the background; the request path never blocks on it.
    #[serde(default)]
    pub limit_service: Option<LimitServiceConfig>,
    /// Asynchronous cross-instance reconciliation via a shared store. When unset,
    /// each instance limits locally (fleet limit ≈ N × per-instance).
    #[serde(default)]
    pub sync: Option<SyncConfig>,
    /// CIDR ranges of trusted reverse proxies / load balancers (e.g.
    /// "10.0.0.0/8"). `X-Forwarded-For` / `X-Real-IP` are honored only when the
    /// direct peer falls in one of these ranges; otherwise the peer socket
    /// address is used as the client identity. Empty (the default) means do not
    /// trust forwarding headers; set this behind a load balancer.
    #[serde(default)]
    pub trusted_proxies: Vec<String>,
}

/// A named limit tier: a sustained rate plus an instantaneous burst capacity.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct LimitProfileConfig {
    /// Sustained rate as `"<count>/<unit>"` (e.g. `"100/min"`, units
    /// `s`/`min`/`hour`) or a bare count (interpreted per minute).
    pub rate: String,
    /// Maximum requests admitted back-to-back before throttling to the rate.
    /// Defaults to the per-window rate count (one full window of burst).
    #[serde(default)]
    pub burst: Option<u64>,
}

/// One rate-limit rule: a path pattern, how to key it, and an optional static
/// profile. The rule's *phase* (before or after auth) is derived from its key
/// alone: a `jwt_claim` key needs validated claims so it runs after auth; `ip`
/// and `header` keys run before auth so anonymous floods are shed before any
/// signature verification. (`jwt_limits` therefore only takes effect on
/// `jwt_claim` rules, the only ones running with claims available.)
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RateRuleConfig {
    /// Glob path pattern (`*` within a segment, `**` across segments).
    pub pattern: String,
    /// How to derive the limit key (who is limited). Defaults to client IP.
    #[serde(default)]
    pub key: KeySourceConfig,
    /// Static profile name for this rule, used when JWT/service resolution does
    /// not apply or yields nothing. Must name an entry in `profiles`.
    #[serde(default)]
    pub profile: Option<String>,
}

/// How a rule derives its limit key. All sources fall back to the client IP when
/// their value is absent, so a limit can't be bypassed by omitting a header or
/// authenticating anonymously. Written as a tagged map, e.g.
/// `key: { type: jwt_claim, claim: sub }`; omitting `key` defaults to `ip`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeySourceConfig {
    /// Client IP (trusted-proxy `X-Forwarded-For` aware). `{ type: ip }`.
    #[default]
    Ip,
    /// Value of a named request header (e.g. an API key).
    /// `{ type: header, name: x-api-key }`.
    Header {
        /// Header whose value identifies the client.
        name: String,
    },
    /// Value of a claim from the validated JWT (provider-agnostic).
    /// `{ type: jwt_claim, claim: sub }`.
    JwtClaim {
        /// Claim whose value identifies the principal.
        claim: String,
    },
}

/// Flat wire form of a rule key. `deny_unknown_fields` rejects any field outside
/// this set, and the manual [`KeySourceConfig`] deserializer additionally rejects
/// a field that belongs to a *different* variant (e.g. `name` on an `ip` key), so
/// a copy-edit leftover can't silently downgrade the intended key source. serde
/// does not honour `deny_unknown_fields` on internally-tagged enums directly,
/// hence this intermediate.
#[derive(Deserialize)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
struct KeySourceRaw {
    #[serde(rename = "type")]
    kind: String,
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    claim: Option<String>,
}

impl<'de> Deserialize<'de> for KeySourceConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::Error;
        let raw = KeySourceRaw::deserialize(deserializer)?;
        match raw.kind.as_str() {
            "ip" => {
                if raw.name.is_some() || raw.claim.is_some() {
                    return Err(D::Error::custom("key type 'ip' takes no other fields"));
                }
                Ok(Self::Ip)
            }
            "header" => {
                if raw.claim.is_some() {
                    return Err(D::Error::custom(
                        "key type 'header' takes 'name', not 'claim'",
                    ));
                }
                let name = raw.name.ok_or_else(|| D::Error::missing_field("name"))?;
                Ok(Self::Header { name })
            }
            "jwt_claim" => {
                if raw.name.is_some() {
                    return Err(D::Error::custom(
                        "key type 'jwt_claim' takes 'claim', not 'name'",
                    ));
                }
                let claim = raw.claim.ok_or_else(|| D::Error::missing_field("claim"))?;
                Ok(Self::JwtClaim { claim })
            }
            other => Err(D::Error::unknown_variant(
                other,
                &["ip", "header", "jwt_claim"],
            )),
        }
    }
}

/// Claims that carry a key's limit inside the JWT itself. A tier-name claim maps
/// to a `profiles` entry (numbers stay tunable in config); direct numeric claims
/// set the limit explicitly.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct JwtLimitConfig {
    /// Claim naming a profile tier (e.g. `"premium"`). Default: `ratelimit_tier`.
    #[serde(default = "default_tier_claim")]
    pub tier_claim: String,
    /// Claim carrying an explicit sustained rate, requests per minute. Default:
    /// `ratelimit_rpm`.
    #[serde(default = "default_rpm_claim")]
    pub rpm_claim: String,
    /// Claim carrying an explicit burst capacity. Default: `ratelimit_burst`.
    #[serde(default = "default_burst_claim")]
    pub burst_claim: String,
}

fn default_tier_claim() -> String {
    "ratelimit_tier".to_string()
}
fn default_rpm_claim() -> String {
    "ratelimit_rpm".to_string()
}
fn default_burst_claim() -> String {
    "ratelimit_burst".to_string()
}

/// External limit-resolution service. The response names a tier or gives explicit
/// numbers; results are cached and refreshed asynchronously, never on the request
/// path.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct LimitServiceConfig {
    /// HTTP endpoint queried with the limit key; returns `{ tier }` or
    /// `{ rate_per_min, burst }`.
    pub endpoint: String,
    /// How long a resolved limit is cached before a background refresh, in
    /// seconds (default: 300).
    #[serde(default = "default_limit_ttl_secs")]
    pub ttl_secs: u64,
    /// Timeout for the background fetch, in milliseconds (default: 500).
    #[serde(default = "default_limit_timeout_ms")]
    pub timeout_ms: u64,
}

fn default_limit_ttl_secs() -> u64 {
    300
}
fn default_limit_timeout_ms() -> u64 {
    500
}

/// Asynchronous cross-instance reconciliation via a shared store.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct SyncConfig {
    /// Shared-store URL (e.g. `"redis://127.0.0.1/"`). Requires the `redis` build
    /// feature; without it the proxy logs a warning and stays local-only.
    pub redis_url: String,
    /// Background push/pull interval in milliseconds (default: 500). The
    /// worst-case fleet overshoot is bounded by `(N-1) × rate × interval`.
    #[serde(default = "default_sync_interval_ms")]
    pub interval_ms: u64,
}

fn default_sync_interval_ms() -> u64 {
    500
}

/// OIDC discovery config.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct OidcDiscoveryConfig {
    #[serde(default)]
    pub enabled: bool,
    pub issuer: String,
    #[serde(default)]
    pub authorization_endpoint: Option<String>,
    #[serde(default)]
    pub token_endpoint: Option<String>,
    #[serde(default)]
    pub userinfo_endpoint: Option<String>,
    #[serde(default)]
    pub jwks_uri: Option<String>,
    #[serde(default)]
    pub signing_key: Option<SigningKeyConfig>,
}

/// Signing key config for JWKS endpoint.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SigningKeyConfig {
    #[serde(default = "default_algorithm")]
    pub algorithm: String,
    pub public_key_pem_file: PathBuf,
}

fn default_algorithm() -> String {
    "EdDSA".into()
}

/// Health-probe endpoint configuration.
///
/// Paths are configurable so an embedder can relocate the probes (e.g. behind a
/// `/internal/` prefix) or disable them when a fronting platform supplies its
/// own. Defaults match the conventional `/health*` layout.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct HealthConfig {
    /// Mount the health endpoints. Default: true.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Aggregate health endpoint. Default: `/health`.
    #[serde(default = "default_health_path")]
    pub path: String,
    /// Liveness probe. Default: `/health/live`.
    #[serde(default = "default_health_live_path")]
    pub live_path: String,
    /// Readiness probe (checks the upstream gRPC health). Default: `/health/ready`.
    #[serde(default = "default_health_ready_path")]
    pub ready_path: String,
    /// Startup probe. Default: `/health/startup`.
    #[serde(default = "default_health_startup_path")]
    pub startup_path: String,
}

fn default_health_path() -> String {
    "/health".into()
}
fn default_health_live_path() -> String {
    "/health/live".into()
}
fn default_health_ready_path() -> String {
    "/health/ready".into()
}
fn default_health_startup_path() -> String {
    "/health/startup".into()
}

impl Default for HealthConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            path: default_health_path(),
            live_path: default_health_live_path(),
            ready_path: default_health_ready_path(),
            startup_path: default_health_startup_path(),
        }
    }
}

/// Prometheus metrics endpoint configuration.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MetricsConfig {
    /// Mount the metrics endpoint. Default: true.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Scrape path. Default: `/metrics`.
    #[serde(default = "default_metrics_path")]
    pub path: String,
}

fn default_metrics_path() -> String {
    "/metrics".into()
}

impl Default for MetricsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            path: default_metrics_path(),
        }
    }
}

/// Maintenance mode config.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MaintenanceConfig {
    #[serde(default)]
    pub enabled: bool,
    /// Paths exempt from maintenance mode (glob patterns).
    #[serde(default = "default_exempt_paths")]
    pub exempt_paths: Vec<String>,
    #[serde(default = "default_maintenance_message")]
    pub message: String,
}

fn default_exempt_paths() -> Vec<String> {
    vec![
        "/health/**".into(),
        "/.well-known/**".into(),
        "/metrics".into(),
        "/auth/verify".into(),
    ]
}

fn default_maintenance_message() -> String {
    "Service is under maintenance. Please try again later.".into()
}

impl Default for MaintenanceConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            exempt_paths: default_exempt_paths(),
            message: default_maintenance_message(),
        }
    }
}

/// CORS configuration.
#[derive(Debug, Clone, Default, Deserialize)]
#[non_exhaustive]
pub struct CorsConfig {
    /// Allowed origins. Empty = permissive (dev mode).
    #[serde(default)]
    pub origins: Vec<String>,
}

/// Logging configuration.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct LoggingConfig {
    #[serde(default = "default_log_level")]
    pub level: String,
    #[serde(default = "default_log_format")]
    pub format: String,
}

fn default_log_level() -> String {
    "info".into()
}
fn default_log_format() -> String {
    "json".into()
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: default_log_level(),
            format: default_log_format(),
        }
    }
}

/// Metrics endpoint classification.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MetricsClassConfig {
    /// Glob pattern for path matching.
    pub pattern: String,
    /// Label value for this class.
    pub class: String,
}

impl ProxyConfig {
    /// Load configuration from a YAML file.
    pub fn from_file(path: &std::path::Path) -> anyhow::Result<Self> {
        Self::from_yaml_str(&std::fs::read_to_string(path)?)
    }

    /// Parse configuration from a YAML string.
    ///
    /// Useful for embedding the proxy: load a baked-in config (e.g. via
    /// `include_str!`) without touching the filesystem.
    pub fn from_yaml_str(yaml: &str) -> anyhow::Result<Self> {
        let config: Self = serde_yaml::from_str(yaml)?;
        config.validate()?;
        Ok(config)
    }

    /// Validate cross-field constraints that the type system can't express.
    ///
    /// Called automatically by [`from_yaml_str`](Self::from_yaml_str); call it
    /// directly when building a [`ProxyConfig`] programmatically so the same
    /// invariants are enforced on the embedded path.
    pub fn validate(&self) -> anyhow::Result<()> {
        if self.streaming.sse_keep_alive_secs == 0 {
            anyhow::bail!("streaming.sse_keep_alive_secs must be greater than 0");
        }
        self.validate_edge_paths()?;
        Ok(())
    }

    /// Reject malformed or duplicate built-in edge paths up front, so the router
    /// does not panic at construction (axum rejects a route that does not start
    /// with `/`, and panics on a path registered twice, e.g. setting
    /// `health.path` to the default `live_path`).
    fn validate_edge_paths(&self) -> anyhow::Result<()> {
        let mut seen = std::collections::HashSet::new();
        let mut check = |label: &str, path: &str| -> anyhow::Result<()> {
            if !path.starts_with('/') {
                anyhow::bail!("endpoint path {path:?} ({label}) must start with '/'");
            }
            if !seen.insert(path.to_string()) {
                anyhow::bail!("duplicate endpoint path {path:?} ({label}); each built-in endpoint must have a distinct path");
            }
            Ok(())
        };
        if self.health.enabled {
            check("health.path", &self.health.path)?;
            check("health.live_path", &self.health.live_path)?;
            check("health.ready_path", &self.health.ready_path)?;
            check("health.startup_path", &self.health.startup_path)?;
        }
        if self.metrics.enabled {
            check("metrics.path", &self.metrics.path)?;
        }
        if let Some(openapi) = self.openapi.as_ref().filter(|o| o.enabled) {
            check("openapi.path", &openapi.path)?;
            check("openapi.docs_path", &openapi.docs_path)?;
        }
        Ok(())
    }

    /// Parse rate string like "20/min" → requests per window.
    pub fn parse_rate(rate: &str) -> Option<u32> {
        let parts: Vec<&str> = rate.split('/').collect();
        if parts.len() != 2 {
            return None;
        }
        parts[0].trim().parse().ok()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_minimal_config_deserialize() {
        let yaml = r#"
upstream:
  default: "grpc://localhost:4180"
"#;
        let config: ProxyConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.upstream.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 health_and_metrics_defaults_and_overrides() {
        // Defaults: enabled, conventional paths.
        let min: ProxyConfig =
            serde_yaml::from_str("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 = serde_yaml::from_str(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" }
  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 = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.upstream.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!(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 = serde_yaml::from_str(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 = serde_yaml::from_str(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 = serde_yaml::from_str(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 = serde_yaml::from_str::<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 = serde_yaml::from_str::<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 = serde_yaml::from_str(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 = serde_yaml::from_str(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());
    }
}