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
//! End-to-end test of the embedded Tier-2 hooks through the public API.
//!
//! Acceptance-criterion guard: the hook implementations below are written using
//! only `http`, `bytes`, `serde_json`, and `async-trait` (the crates a real
//! embedder uses), and reference **no `axum` type**. The proxy wires them into
//! its router via [`ProxyServer`]; the test then drives that router with axum +
//! tower purely as the assertion harness (that is the proxy's concern, not the
//! embedder's).

use std::sync::Arc;

use async_trait::async_trait;
use http::{HeaderMap, Method, StatusCode};
use structured_proxy::config::ProxyConfig;
use structured_proxy::hooks::{
    AuthDecider, Decision, ExtraRoute, ExtraRouteHandler, MetadataDocument, OidcBackend,
    RequestParts, RouteRequest, RouteResponse,
};
use structured_proxy::ProxyServer;

// --- embedder-supplied hook impls (axum-free) ----------------------------

/// Allows `/v1/public/**`, injects a verified `x-user` for everything else, and
/// redirects an explicit `/login`. Mirrors a real PDP shape (path + headers in,
/// decision out) without any framework types.
struct DemoDecider;

#[async_trait]
impl AuthDecider for DemoDecider {
    async fn decide(&self, req: &RequestParts<'_>) -> Decision {
        if req.path == "/login" {
            return Decision::Redirect {
                location: "https://login.example.com".to_string(),
            };
        }
        if req.path.starts_with("/v1/public/") {
            return Decision::Allow {
                inject_headers: HeaderMap::new(),
            };
        }
        if req.headers.get("authorization").is_some() {
            let mut h = HeaderMap::new();
            h.insert("x-user", "verified-user".parse().unwrap());
            Decision::Allow { inject_headers: h }
        } else {
            Decision::Deny {
                status: StatusCode::UNAUTHORIZED,
                body: bytes::Bytes::from_static(b"{\"error\":\"unauthenticated\"}"),
            }
        }
    }
}

struct DemoOidc;

#[async_trait]
impl OidcBackend for DemoOidc {
    fn metadata_documents(&self) -> Vec<MetadataDocument> {
        vec![MetadataDocument::new(
            "/.well-known/openid-configuration",
            serde_json::json!({ "issuer": "https://idp.example.com" }),
        )]
    }
    fn jwks(&self) -> MetadataDocument {
        MetadataDocument::new("/.well-known/jwks.json", serde_json::json!({ "keys": [] }))
    }
    async fn userinfo(&self, bearer: &str) -> Option<serde_json::Value> {
        (bearer == "token-123").then(|| serde_json::json!({ "sub": "user-1", "email": "u@x" }))
    }
}

struct PingHandler;

#[async_trait]
impl ExtraRouteHandler for PingHandler {
    async fn handle(&self, _req: RouteRequest) -> RouteResponse {
        RouteResponse::new(StatusCode::OK, bytes::Bytes::from_static(b"pong"))
    }
}

// --- harness (axum + tower) ----------------------------------------------

use axum::body::Body;
use tower::ServiceExt;

fn server() -> ProxyServer {
    let config = ProxyConfig::from_yaml_str(
        r#"
upstream:
  default: "http://127.0.0.1:50051"
service:
  name: "hooks-test"
"#,
    )
    .unwrap();

    ProxyServer::from_config(config)
        .with_auth_decider(Arc::new(DemoDecider))
        .with_oidc_backend(Arc::new(DemoOidc))
        .with_verify_path("/auth/verify")
        .with_extra_routes([ExtraRoute::new(Method::GET, "/ping", Arc::new(PingHandler))])
}

async fn body_string(resp: axum::response::Response) -> String {
    let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
        .await
        .unwrap();
    String::from_utf8(bytes.to_vec()).unwrap()
}

#[tokio::test]
async fn verify_endpoint_is_backed_by_the_decider() {
    let app = server().router().unwrap();

    // Authenticated original request → 200 with the injected identity.
    let ok = app
        .clone()
        .oneshot(
            axum::http::Request::get("/auth/verify")
                .header("x-forwarded-method", "GET")
                .header("x-forwarded-uri", "/v1/things")
                .header("authorization", "Bearer whatever")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(ok.status(), StatusCode::OK);
    assert_eq!(ok.headers()["x-user"], "verified-user");

    // No credentials → the decider denies.
    let denied = app
        .oneshot(
            axum::http::Request::get("/auth/verify")
                .header("x-forwarded-method", "GET")
                .header("x-forwarded-uri", "/v1/things")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(denied.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn verify_redirect_becomes_401_with_location() {
    let app = server().router().unwrap();
    let resp = app
        .oneshot(
            axum::http::Request::get("/auth/verify")
                .header("x-forwarded-method", "GET")
                .header("x-forwarded-uri", "/login")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(resp.headers()["location"], "https://login.example.com");
}

#[tokio::test]
async fn oidc_backend_surface_is_served() {
    let app = server().router().unwrap();

    let disc = app
        .clone()
        .oneshot(
            axum::http::Request::get("/.well-known/openid-configuration")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(disc.status(), StatusCode::OK);
    assert!(body_string(disc).await.contains("idp.example.com"));

    let jwks = app
        .clone()
        .oneshot(
            axum::http::Request::get("/.well-known/jwks.json")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(jwks.status(), StatusCode::OK);
    assert_eq!(jwks.headers()["content-type"], "application/jwk-set+json");

    let userinfo = app
        .oneshot(
            axum::http::Request::get("/userinfo")
                .header("authorization", "Bearer token-123")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(userinfo.status(), StatusCode::OK);
    assert!(body_string(userinfo).await.contains("user-1"));
}

#[tokio::test]
async fn verify_path_defaults_when_not_configured() {
    // No with_verify_path and no JWT forward_auth config: the decider still
    // answers at the default /auth/verify.
    let config =
        ProxyConfig::from_yaml_str("upstream:\n  default: \"http://127.0.0.1:50051\"\n").unwrap();
    let app = ProxyServer::from_config(config)
        .with_auth_decider(Arc::new(DemoDecider))
        .router()
        .unwrap();
    let resp = app
        .oneshot(
            axum::http::Request::get("/auth/verify")
                .header("x-forwarded-uri", "/v1/public/info")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
}

#[tokio::test]
async fn health_and_metrics_paths_are_configurable() {
    // Relocate the probes and metrics, and confirm the defaults no longer exist.
    let config = ProxyConfig::from_yaml_str(
        r#"
upstream:
  default: "http://127.0.0.1:50051"
health:
  path: "/internal/health"
  live_path: "/internal/health/live"
metrics:
  path: "/internal/metrics"
"#,
    )
    .unwrap();
    let app = ProxyServer::from_config(config).router().unwrap();

    for path in [
        "/internal/health",
        "/internal/health/live",
        "/internal/metrics",
    ] {
        let resp = app
            .clone()
            .oneshot(axum::http::Request::get(path).body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK, "expected route at {path}");
    }

    // The default paths are gone now that they were relocated.
    let default_health = app
        .oneshot(
            axum::http::Request::get("/health")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(default_health.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn health_and_metrics_can_be_disabled() {
    let config = ProxyConfig::from_yaml_str(
        r#"
upstream:
  default: "http://127.0.0.1:50051"
health:
  enabled: false
metrics:
  enabled: false
"#,
    )
    .unwrap();
    let app = ProxyServer::from_config(config).router().unwrap();

    for path in ["/health", "/health/live", "/metrics"] {
        let resp = app
            .clone()
            .oneshot(axum::http::Request::get(path).body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::NOT_FOUND,
            "{path} should be unmounted when disabled"
        );
    }
}

#[tokio::test]
async fn config_forward_auth_path_colliding_with_probe_is_a_clean_error() {
    // The same collision guard must cover plain JWT forward-auth (no decider):
    // a forward_auth.path equal to a built-in GET path is a clean error, not an
    // axum duplicate-route panic.
    const PUB_PEM: &str = "-----BEGIN PUBLIC KEY-----\n\
        MCowBQYDK2VwAyEARCMxEnaM2/dblLuPNgBZpTvSUXO5ir+XQ1nyzJm4CFw=\n\
        -----END PUBLIC KEY-----\n";
    let pem_path = std::env::temp_dir().join(format!("sp_hooks_fa_{}.pem", std::process::id()));
    std::fs::write(&pem_path, PUB_PEM).unwrap();

    let config = ProxyConfig::from_yaml_str(&format!(
        r#"
upstream:
  default: "http://127.0.0.1:50051"
auth:
  mode: "jwt"
  jwt:
    public_key_pem_file: "{}"
  forward_auth:
    enabled: true
    path: "/health"
"#,
        // Forward slashes are valid in file paths on every platform and, unlike
        // Windows backslashes, are not escape sequences in a double-quoted YAML
        // scalar, so the generated config parses on Windows runners too.
        pem_path.display().to_string().replace('\\', "/")
    ))
    .unwrap();
    let result = ProxyServer::from_config(config).router();
    let _ = std::fs::remove_file(&pem_path);
    assert!(result.is_err());
    assert!(result
        .unwrap_err()
        .to_string()
        .contains("registered by more than one endpoint"));
}

#[tokio::test]
async fn verify_path_colliding_with_openapi_docs_is_a_clean_error() {
    // The collision guard must cover every built-in GET route mounted before
    // verify, including the OpenAPI spec/docs paths (not just health/metrics).
    let config = ProxyConfig::from_yaml_str(
        r#"
upstream:
  default: "http://127.0.0.1:50051"
openapi:
  enabled: true
"#,
    )
    .unwrap();
    let result = ProxyServer::from_config(config)
        .with_auth_decider(Arc::new(DemoDecider))
        .with_verify_path("/docs")
        .router();
    assert!(result.is_err());
    assert!(result
        .unwrap_err()
        .to_string()
        .contains("registered by more than one endpoint"));
}

#[tokio::test]
async fn verify_path_colliding_with_oidc_route_is_a_clean_error() {
    // The reserved-path set must include OIDC backend routes; a verify path on
    // top of the discovery document is a clean error, not a panic.
    let config =
        ProxyConfig::from_yaml_str("upstream:\n  default: \"http://127.0.0.1:50051\"\n").unwrap();
    let result = ProxyServer::from_config(config)
        .with_oidc_backend(Arc::new(DemoOidc))
        .with_auth_decider(Arc::new(DemoDecider))
        .with_verify_path("/.well-known/openid-configuration")
        .router();
    assert!(result.is_err());
    assert!(result
        .unwrap_err()
        .to_string()
        .contains("registered by more than one endpoint"));
}

#[tokio::test]
async fn extra_route_colliding_with_builtin_is_a_clean_error() {
    // A collision BETWEEN mounted routes (here an extra route over the health
    // endpoint), not involving verify, is also a clean error rather than a panic.
    let config =
        ProxyConfig::from_yaml_str("upstream:\n  default: \"http://127.0.0.1:50051\"\n").unwrap();
    let result = ProxyServer::from_config(config)
        .with_extra_routes([ExtraRoute::new(
            Method::GET,
            "/health",
            Arc::new(PingHandler),
        )])
        .router();
    assert!(result.is_err());
    assert!(result
        .unwrap_err()
        .to_string()
        .contains("registered by more than one endpoint"));
}

#[tokio::test]
async fn extra_routes_sharing_a_path_with_different_methods_are_allowed() {
    // GET /c and POST /c are a legal shape (the adapter merges them by method);
    // the collision guard must key on (method, path) and NOT reject them.
    let config =
        ProxyConfig::from_yaml_str("upstream:\n  default: \"http://127.0.0.1:50051\"\n").unwrap();
    let app = ProxyServer::from_config(config)
        .with_extra_routes([
            ExtraRoute::new(Method::GET, "/c", Arc::new(PingHandler)),
            ExtraRoute::new(Method::POST, "/c", Arc::new(PingHandler)),
        ])
        .router()
        .unwrap();
    for method in [Method::GET, Method::POST] {
        let resp = app
            .clone()
            .oneshot(
                axum::http::Request::builder()
                    .method(method.clone())
                    .uri("/c")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "{method} /c should be served"
        );
    }
}

#[tokio::test]
async fn structurally_identical_dynamic_routes_are_a_clean_error() {
    // `/x/{a}` and `/x/{b}` are the same shape to axum/matchit (differ only in
    // param name) and would panic when merged. The guard normalizes shape, so
    // this is a clean build error.
    let config =
        ProxyConfig::from_yaml_str("upstream:\n  default: \"http://127.0.0.1:50051\"\n").unwrap();
    let result = ProxyServer::from_config(config)
        .with_extra_routes([
            ExtraRoute::new(Method::GET, "/x/{a}", Arc::new(PingHandler)),
            ExtraRoute::new(Method::GET, "/x/{b}", Arc::new(PingHandler)),
        ])
        .router();
    assert!(result.is_err());
    assert!(result
        .unwrap_err()
        .to_string()
        .contains("registered by more than one endpoint"));
}

#[tokio::test]
async fn malformed_extra_route_path_is_a_clean_error() {
    // A consumer-supplied path without a leading '/' (here an extra route) would
    // panic axum at registration; it must be a clean build error instead.
    let config =
        ProxyConfig::from_yaml_str("upstream:\n  default: \"http://127.0.0.1:50051\"\n").unwrap();
    let result = ProxyServer::from_config(config)
        .with_extra_routes([ExtraRoute::new(Method::GET, "ping", Arc::new(PingHandler))])
        .router();
    assert!(result.is_err());
    assert!(result
        .unwrap_err()
        .to_string()
        .contains("must start with '/'"));
}

#[tokio::test]
async fn malformed_verify_path_is_a_clean_error() {
    let config =
        ProxyConfig::from_yaml_str("upstream:\n  default: \"http://127.0.0.1:50051\"\n").unwrap();
    let result = ProxyServer::from_config(config)
        .with_auth_decider(Arc::new(DemoDecider))
        .with_verify_path("auth/verify") // missing leading '/'
        .router();
    assert!(result.is_err());
    assert!(result
        .unwrap_err()
        .to_string()
        .contains("must start with '/'"));
}

#[tokio::test]
async fn config_forward_auth_guard_uses_config_path_not_override() {
    // With no decider, config-driven JWT forward-auth mounts at
    // auth.forward_auth.path; the with_verify_path override does NOT apply there.
    // The guard must validate the CONFIG path (which collides with /health), not
    // be fooled by the override pointing somewhere harmless.
    const PUB_PEM: &str = "-----BEGIN PUBLIC KEY-----\n\
        MCowBQYDK2VwAyEARCMxEnaM2/dblLuPNgBZpTvSUXO5ir+XQ1nyzJm4CFw=\n\
        -----END PUBLIC KEY-----\n";
    let pem_path = std::env::temp_dir().join(format!("sp_hooks_ov_{}.pem", std::process::id()));
    std::fs::write(&pem_path, PUB_PEM).unwrap();

    let config = ProxyConfig::from_yaml_str(&format!(
        r#"
upstream:
  default: "http://127.0.0.1:50051"
auth:
  mode: "jwt"
  jwt:
    public_key_pem_file: "{}"
  forward_auth:
    enabled: true
    path: "/health"
"#,
        // Forward slashes are valid in file paths on every platform and, unlike
        // Windows backslashes, are not escape sequences in a double-quoted YAML
        // scalar, so the generated config parses on Windows runners too.
        pem_path.display().to_string().replace('\\', "/")
    ))
    .unwrap();
    // Override points elsewhere, but it is ignored for config-driven forward-auth.
    let result = ProxyServer::from_config(config)
        .with_verify_path("/elsewhere")
        .router();
    let _ = std::fs::remove_file(&pem_path);
    assert!(result.is_err());
    assert!(result
        .unwrap_err()
        .to_string()
        .contains("registered by more than one endpoint"));
}

#[tokio::test]
async fn verify_path_colliding_with_probe_is_a_clean_error() {
    // A verify path that collides with a built-in GET route must surface a
    // config error, not an axum duplicate-route panic.
    let config =
        ProxyConfig::from_yaml_str("upstream:\n  default: \"http://127.0.0.1:50051\"\n").unwrap();
    let result = ProxyServer::from_config(config)
        .with_auth_decider(Arc::new(DemoDecider))
        .with_verify_path("/health")
        .router();
    assert!(result.is_err());
    assert!(result
        .unwrap_err()
        .to_string()
        .contains("registered by more than one endpoint"));
}

#[tokio::test]
async fn relocated_paths_stay_exempt_under_maintenance() {
    // With maintenance enabled, relocated probe / metrics / verify paths must
    // stay reachable (they were exempt at their default locations).
    let config = ProxyConfig::from_yaml_str(
        r#"
upstream:
  default: "http://127.0.0.1:50051"
maintenance:
  enabled: true
health:
  path: "/internal/health"
metrics:
  path: "/internal/metrics"
"#,
    )
    .unwrap();
    let app = ProxyServer::from_config(config)
        .with_auth_decider(Arc::new(DemoDecider))
        .with_verify_path("/internal/verify")
        .router()
        .unwrap();

    // Probe + metrics reachable despite maintenance.
    for path in ["/internal/health", "/internal/metrics"] {
        let resp = app
            .clone()
            .oneshot(axum::http::Request::get(path).body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "{path} blocked by maintenance"
        );
    }

    // Relocated verify endpoint is exempt and answers the decider's decision.
    let verify = app
        .clone()
        .oneshot(
            axum::http::Request::get("/internal/verify")
                .header("x-forwarded-uri", "/v1/public/info")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(verify.status(), StatusCode::OK);

    // A non-exempt proxied path still gets the 503 maintenance response.
    let blocked = app
        .oneshot(
            axum::http::Request::get("/v1/anything")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(blocked.status(), StatusCode::SERVICE_UNAVAILABLE);
}

#[tokio::test]
async fn extra_route_is_mounted() {
    let app = server().router().unwrap();
    let resp = app
        .oneshot(
            axum::http::Request::get("/ping")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    assert_eq!(body_string(resp).await, "pong");
}