footing 0.6.6

Feature-gated foundations for Rust backend services
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
#![cfg(feature = "http")]

use std::collections::BTreeSet;

use axum::{
    Router,
    body::{Body, to_bytes},
    http::{Method, Request, StatusCode, header},
    middleware::from_fn,
    response::{Html, Response},
    routing::{any, get, post},
};
use footing::http::{
    ProblemDetails, REQUEST_ID_HEADER_NAME, RequestContext, RequestId, TraceParent,
    error::PROBLEM_JSON_MEDIA_TYPE, method_not_allowed, request_context_middleware,
    route_not_found,
};
use tower::ServiceExt;

const TRACEPARENT: &str = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
const TRACE_ID: &str = "4bf92f3577b34da6a3ce929d0e0e4736";

async fn problem(response: Response, status: StatusCode, code: &str) -> ProblemDetails {
    assert_eq!(response.status(), status);
    assert_eq!(
        response.headers()[header::CONTENT_TYPE],
        PROBLEM_JSON_MEDIA_TYPE
    );
    assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
    let body = to_bytes(response.into_body(), 4096).await.unwrap();
    let problem: ProblemDetails = serde_json::from_slice(&body).unwrap();
    assert_eq!(problem.status(), status.as_u16());
    assert_eq!(problem.code(), code);
    assert_eq!(problem.type_uri(), "about:blank");
    assert!(problem.instance().is_none());
    assert!(problem.details().is_none());
    problem
}

#[tokio::test]
async fn unmatched_route_has_safe_details_and_standalone_context() {
    let app = Router::new().fallback(route_not_found);
    let response = app
        .oneshot(
            Request::get("/sensitive-resource?credential=secret")
                .header(REQUEST_ID_HEADER_NAME, "standalone-request")
                .header("traceparent", TRACEPARENT)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert!(!response.headers().contains_key(header::ALLOW));
    let problem = problem(response, StatusCode::NOT_FOUND, "route_not_found").await;
    assert_eq!(problem.title(), "Not Found");
    assert_eq!(problem.detail(), "route not found");
    assert_eq!(problem.request_id(), Some("standalone-request"));
    assert_eq!(problem.trace_id(), Some(TRACE_ID));
}

#[tokio::test]
async fn routing_errors_reuse_installed_context_and_outer_response_headers() {
    let app = Router::new()
        .route("/resource", get(|| async { "ok" }))
        .fallback(route_not_found)
        .method_not_allowed_fallback(method_not_allowed)
        .layer(from_fn(request_context_middleware));
    for (path, status, code) in [
        ("/missing", StatusCode::NOT_FOUND, "route_not_found"),
        (
            "/resource",
            StatusCode::METHOD_NOT_ALLOWED,
            "method_not_allowed",
        ),
    ] {
        let mut request = Request::post(path)
            .header(REQUEST_ID_HEADER_NAME, "ignored-header-request")
            .body(Body::empty())
            .unwrap();
        request.extensions_mut().insert(
            RequestContext::new(RequestId::new("installed-request").unwrap())
                .with_traceparent(TraceParent::new(TRACEPARENT).unwrap()),
        );
        let response = app.clone().oneshot(request).await.unwrap();
        assert_eq!(
            response.headers()[REQUEST_ID_HEADER_NAME],
            "installed-request"
        );
        let problem = problem(response, status, code).await;
        assert_eq!(problem.request_id(), Some("installed-request"));
        assert_eq!(problem.trace_id(), Some(TRACE_ID));
    }
}

#[tokio::test]
async fn method_error_preserves_axum_allow_and_does_not_echo_input() {
    let app = Router::new()
        .route("/resource", get(|| async { "ok" }))
        .route("/resource", post(|| async { StatusCode::CREATED }))
        .method_not_allowed_fallback(method_not_allowed);
    let response = app
        .oneshot(
            Request::builder()
                .method(Method::from_bytes(b"SECRET-METHOD").unwrap())
                .uri("/resource?secret=value")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    let allowed: BTreeSet<_> = response.headers()[header::ALLOW]
        .to_str()
        .unwrap()
        .split(',')
        .map(str::trim)
        .collect();
    assert_eq!(allowed, BTreeSet::from(["GET", "HEAD", "POST"]));
    let problem = problem(
        response,
        StatusCode::METHOD_NOT_ALLOWED,
        "method_not_allowed",
    )
    .await;
    assert_eq!(problem.title(), "Method Not Allowed");
    assert_eq!(problem.detail(), "method not allowed");
    assert!(problem.request_id().is_some());
}

#[tokio::test]
async fn head_routing_errors_keep_headers_and_never_send_a_body() {
    let api = Router::new()
        .route("/resource", post(|| async { "created" }))
        .fallback(route_not_found)
        .method_not_allowed_fallback(method_not_allowed);
    let app = Router::new()
        .nest("/api", api)
        .fallback(route_not_found)
        .layer(from_fn(request_context_middleware));
    for (path, status) in [
        ("/missing", StatusCode::NOT_FOUND),
        ("/api/missing", StatusCode::NOT_FOUND),
        ("/api/resource", StatusCode::METHOD_NOT_ALLOWED),
    ] {
        let response = app
            .clone()
            .oneshot(
                Request::head(path)
                    .header(REQUEST_ID_HEADER_NAME, "head-request")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), status);
        assert_eq!(
            response.headers()[header::CONTENT_TYPE],
            PROBLEM_JSON_MEDIA_TYPE
        );
        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
        assert_eq!(response.headers()[REQUEST_ID_HEADER_NAME], "head-request");
        assert!(
            response.headers()[header::CONTENT_LENGTH]
                .to_str()
                .unwrap()
                .parse::<usize>()
                .unwrap()
                > 0
        );
        if status == StatusCode::METHOD_NOT_ALLOWED {
            assert_eq!(response.headers()[header::ALLOW], "POST");
        } else {
            assert!(!response.headers().contains_key(header::ALLOW));
        }
        assert!(
            to_bytes(response.into_body(), 4096)
                .await
                .unwrap()
                .is_empty()
        );
    }
}

#[tokio::test]
async fn nested_api_errors_never_fall_through_to_frontend_html() {
    let api = Router::new()
        .route("/resource", get(|| async { "ok" }))
        .fallback(route_not_found)
        .method_not_allowed_fallback(method_not_allowed);
    let app = Router::new()
        .nest("/api", api)
        .route("/api/", any(route_not_found))
        .fallback(|| async { Html("<!doctype html><title>Frontend</title>") })
        .layer(from_fn(request_context_middleware));
    for path in ["/api", "/api/", "/api/missing", "/api/missing/deep"] {
        for method in [Method::GET, Method::POST, Method::HEAD] {
            let response = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method(method.clone())
                        .uri(path)
                        .header(header::ACCEPT, "text/html")
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(response.status(), StatusCode::NOT_FOUND, "{method} {path}");
            assert_eq!(
                response.headers()[header::CONTENT_TYPE],
                PROBLEM_JSON_MEDIA_TYPE
            );
            if method == Method::HEAD {
                assert!(
                    to_bytes(response.into_body(), 4096)
                        .await
                        .unwrap()
                        .is_empty()
                );
            } else {
                problem(response, StatusCode::NOT_FOUND, "route_not_found").await;
            }
        }
    }
    let response = app
        .oneshot(Request::get("/dashboard").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(
        response.headers()[header::CONTENT_TYPE],
        "text/html; charset=utf-8"
    );
    assert_eq!(
        to_bytes(response.into_body(), 4096).await.unwrap(),
        "<!doctype html><title>Frontend</title>"
    );
}

#[tokio::test]
async fn business_responses_and_explicit_method_fallbacks_remain_untouched() {
    let app = Router::new()
        .route(
            "/resource",
            get(|| async { (StatusCode::NOT_FOUND, "business lookup failed") })
                .fallback(|| async { (StatusCode::METHOD_NOT_ALLOWED, "custom method policy") }),
        )
        .fallback(route_not_found)
        .method_not_allowed_fallback(method_not_allowed);
    for (method, status, body) in [
        (Method::GET, StatusCode::NOT_FOUND, "business lookup failed"),
        (
            Method::POST,
            StatusCode::METHOD_NOT_ALLOWED,
            "custom method policy",
        ),
    ] {
        let response = app
            .clone()
            .oneshot(
                Request::builder()
                    .method(method)
                    .uri("/resource")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), status);
        assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), body);
    }
}

#[tokio::test]
async fn endpoint_router_can_install_api_fallbacks_without_the_stack() {
    use footing::http::{EndpointContract, EndpointMethod, EndpointPathPattern, EndpointRouter};

    let (app, contracts) = EndpointRouter::new()
        .route(
            EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::exact("/resource")),
            || async { "ok" },
        )
        .unwrap()
        .with_api_fallbacks()
        .into_parts();
    assert_eq!(contracts.len(), 1);
    assert_eq!(contracts[0].path().as_str(), "/resource");
    for (path, status, code) in [
        ("/missing", StatusCode::NOT_FOUND, "route_not_found"),
        (
            "/resource",
            StatusCode::METHOD_NOT_ALLOWED,
            "method_not_allowed",
        ),
    ] {
        let response = app
            .clone()
            .oneshot(Request::post(path).body(Body::empty()).unwrap())
            .await
            .unwrap();
        if status == StatusCode::METHOD_NOT_ALLOWED {
            assert_eq!(response.headers()[header::ALLOW], "GET,HEAD");
        }
        problem(response, status, code).await;
    }
}

#[cfg(feature = "http-stack")]
async fn assert_stacked_routing_problem(
    app: &Router,
    path: &str,
    status: StatusCode,
    code: &str,
    allow: Option<&str>,
) {
    let response = app
        .clone()
        .oneshot(
            Request::delete(path)
                .header(REQUEST_ID_HEADER_NAME, "stack-request")
                .header("traceparent", TRACEPARENT)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.headers()[REQUEST_ID_HEADER_NAME], "stack-request");
    assert_eq!(response.headers()["x-content-type-options"], "nosniff");
    assert_eq!(response.headers()["x-frame-options"], "DENY");
    assert_eq!(
        response
            .headers()
            .get(header::ALLOW)
            .map(|value| value.to_str().unwrap()),
        allow
    );
    let problem = problem(response, status, code).await;
    assert_eq!(problem.request_id(), Some("stack-request"));
    assert_eq!(problem.trace_id(), Some(TRACE_ID));
}

#[cfg(feature = "http-stack")]
#[tokio::test]
async fn endpoint_router_installs_api_fallbacks_inside_the_standard_stack() {
    use footing::http::{
        EndpointContract, EndpointMethod, EndpointPathPattern, EndpointRouter,
        HttpMiddlewareConfig, HttpMiddlewareStack,
    };

    let stack = HttpMiddlewareStack::builder(HttpMiddlewareConfig::standard())
        .build()
        .unwrap();
    let app = EndpointRouter::new()
        .route(
            EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::exact("/resource")),
            || async { "ok" },
        )
        .unwrap()
        .with_api_fallbacks()
        .into_router(stack)
        .unwrap();
    assert_stacked_routing_problem(
        &app,
        "/missing",
        StatusCode::NOT_FOUND,
        "route_not_found",
        None,
    )
    .await;
    assert_stacked_routing_problem(
        &app,
        "/resource",
        StatusCode::METHOD_NOT_ALLOWED,
        "method_not_allowed",
        Some("GET,HEAD"),
    )
    .await;
}

#[cfg(all(feature = "openapi", feature = "http-stack"))]
#[tokio::test]
async fn openapi_fallbacks_cover_composed_routes_inside_the_stack_without_new_operations() {
    use footing::http::{
        EndpointPolicy, HttpMiddlewareConfig, HttpMiddlewareStack,
        openapi::{OpenApiRouter, route, utoipa},
    };
    use utoipa::openapi::{Info, OpenApi, path::Paths};

    #[utoipa::path(get, path = "/direct", responses((status = 200)))]
    async fn direct() -> &'static str {
        "direct"
    }

    #[utoipa::path(post, path = "/merged", responses((status = 200)))]
    async fn merged() -> &'static str {
        "merged"
    }

    #[utoipa::path(get, path = "/nested", responses((status = 200)))]
    async fn nested() -> &'static str {
        "nested"
    }

    let document = || OpenApi::new(Info::new("Test API", "1"), Paths::new());
    let merged = OpenApiRouter::new(document())
        .unwrap()
        .route(
            route!(merged)
                .unwrap()
                .with_contract(|_| EndpointPolicy::new())
                .unwrap(),
        )
        .unwrap();
    let nested = OpenApiRouter::new(document())
        .unwrap()
        .route(
            route!(nested)
                .unwrap()
                .with_contract(|_| EndpointPolicy::new())
                .unwrap(),
        )
        .unwrap();
    let stack = HttpMiddlewareStack::builder(HttpMiddlewareConfig::standard())
        .build()
        .unwrap();
    let (app, document) = OpenApiRouter::new(document())
        .unwrap()
        .route(
            route!(direct)
                .unwrap()
                .with_contract(|_| EndpointPolicy::new())
                .unwrap(),
        )
        .unwrap()
        .merge(merged)
        .unwrap()
        .nest("/v1", nested)
        .unwrap()
        .with_api_fallbacks()
        .into_parts_with_stack(stack)
        .unwrap();

    let document = serde_json::to_value(document).unwrap();
    let paths = document["paths"].as_object().unwrap();
    assert_eq!(paths.len(), 3);
    for (path, method) in [
        ("/direct", "get"),
        ("/merged", "post"),
        ("/v1/nested", "get"),
    ] {
        let operations: Vec<_> = paths[path]
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        assert_eq!(operations, [method]);
    }
    for path in ["/missing", "/v1/missing"] {
        assert_stacked_routing_problem(&app, path, StatusCode::NOT_FOUND, "route_not_found", None)
            .await;
    }
    for (path, allow) in [
        ("/direct", "GET,HEAD"),
        ("/merged", "POST"),
        ("/v1/nested", "GET,HEAD"),
    ] {
        assert_stacked_routing_problem(
            &app,
            path,
            StatusCode::METHOD_NOT_ALLOWED,
            "method_not_allowed",
            Some(allow),
        )
        .await;
    }
}