structured-proxy 4.3.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
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 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 = serde_yaml::from_str(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 = serde_yaml::from_str(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 = serde_yaml::from_str(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 = serde_yaml::from_str(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 = serde_yaml::from_str::<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 = 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());
}

#[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 =
        serde_yaml::from_str("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: _,
    } = 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",
    ] {
        assert!(KNOWN_TOP_LEVEL_KEYS.contains(&key), "{key}");
    }
    assert_eq!(KNOWN_TOP_LEVEL_KEYS.len(), 19);
}

#[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> {
    serde_yaml::from_str::<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 = serde_yaml::from_str(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}");
}