seiva-http 0.2.2

Delonix Seiva — HTTP transport (axum/tower): RFC 9457 problems, typed/validated bodies, descriptor-driven permission guard, health endpoints. DORM-free.
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
//! End-to-end tests driving the router with `tower::ServiceExt::oneshot` — no
//! live server, no database, no broker, no example module.
//!
//! The framework router (`router`) is demo-free, so these tests cover it on its
//! own (health, `/docs`, `/openapi.json`) and exercise the guard + `Valid`
//! primitives through a small inline route built from the public API — the same
//! shape a generated controller produces, without depending on an example crate.

use axum::body::Body;
use axum::http::{header, Request, StatusCode};
use axum::middleware::{from_fn, from_fn_with_state};
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::{Json, Router};
use serde::Deserialize;
use serde_json::{json, Value};
use tower::ServiceExt;

use std::sync::Arc;

use seiva_http::{
    authn, permission_guard, request_id, router, router_with_modules, ApiKeyAuthenticator,
    AuthConfig, Authenticator, Authn, Health, HttpSecurity, Principal, RequiredPermission,
    TokenAuthenticator, Valid, Validate, ValidationError, PROBLEM_JSON, REQUEST_ID_HEADER,
};

/// Reads a response body into a JSON value.
async fn json_body(body: Body) -> Value {
    let bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
    serde_json::from_slice(&bytes).unwrap()
}

// --- An inline guarded + validated route, built from the public primitives ---

#[derive(Debug, Deserialize)]
struct DemoBody {
    title: String,
}

impl Validate for DemoBody {
    fn validate(&self) -> Result<(), ValidationError> {
        if self.title.trim().is_empty() {
            return Err(ValidationError::new("title must not be empty"));
        }
        Ok(())
    }
}

async fn demo_create(Valid(body): Valid<DemoBody>) -> Response {
    (
        StatusCode::CREATED,
        Json(json!({ "id": 1, "title": body.title })),
    )
        .into_response()
}

/// A route guarded by `demo.create` and validated by `Valid<DemoBody>`, wrapped
/// in the request-id middleware so a problem response carries a correlation id —
/// the exact composition a generated controller uses.
fn guarded_app() -> Router {
    Router::new()
        .route("/demo", post(demo_create))
        .layer(from_fn_with_state(
            RequiredPermission("demo.create"),
            permission_guard,
        ))
        .layer(from_fn(request_id))
}

#[tokio::test]
async fn guarded_route_happy_path_is_201_with_a_request_id() {
    let request = Request::builder()
        .method("POST")
        .uri("/demo")
        .header("content-type", "application/json")
        .extension(Arc::new(Principal::new("user-1", ["demo.create"])))
        .body(Body::from(r#"{"title":"first"}"#))
        .unwrap();

    let response = guarded_app().oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
    assert!(response.headers().contains_key(REQUEST_ID_HEADER));
    let body = json_body(response.into_body()).await;
    assert_eq!(body["title"], "first");
    assert_eq!(body["id"], 1);
}

#[tokio::test]
async fn guarded_route_without_permission_is_a_403_problem() {
    let request = Request::builder()
        .method("POST")
        .uri("/demo")
        .header("content-type", "application/json")
        .extension(Arc::new(Principal::new("user-2", ["demo.read"])))
        .body(Body::from(r#"{"title":"blocked"}"#))
        .unwrap();

    let response = guarded_app().oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::FORBIDDEN);
    assert_eq!(response.headers()["content-type"], PROBLEM_JSON);
    let body = json_body(response.into_body()).await;
    assert_eq!(body["status"], 403);
    assert_eq!(body["title"], "Forbidden");
    assert!(body["detail"].as_str().unwrap().contains("demo.create"));
    assert!(body["request_id"].is_string());
}

#[tokio::test]
async fn guarded_route_anonymous_is_denied() {
    let request = Request::builder()
        .method("POST")
        .uri("/demo")
        .header("content-type", "application/json")
        .body(Body::from(r#"{"title":"anon"}"#))
        .unwrap();
    let response = guarded_app().oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn invalid_body_is_a_422_problem() {
    let request = Request::builder()
        .method("POST")
        .uri("/demo")
        .header("content-type", "application/json")
        .extension(Arc::new(Principal::new("user-1", ["demo.create"])))
        .body(Body::from(r#"{"title":"   "}"#))
        .unwrap();

    let response = guarded_app().oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
    assert_eq!(response.headers()["content-type"], PROBLEM_JSON);
    let body = json_body(response.into_body()).await;
    assert_eq!(body["status"], 422);
    assert!(body["detail"].as_str().unwrap().contains("title"));
}

#[tokio::test]
async fn malformed_json_is_a_422() {
    let request = Request::builder()
        .method("POST")
        .uri("/demo")
        .header("content-type", "application/json")
        .extension(Arc::new(Principal::new("user-1", ["demo.create"])))
        .body(Body::from("not json"))
        .unwrap();
    let response = guarded_app().oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

// --- The framework router, demo-free ----------------------------------------

/// `/health/live` is `200` in every state; `/health/ready` tracks the lifecycle.
#[tokio::test]
async fn health_endpoints_track_lifecycle() {
    let health = Health::starting();

    let live = router(health.clone())
        .oneshot(
            Request::builder()
                .uri("/health/live")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(live.status(), StatusCode::OK);

    let ready = router(health.clone())
        .oneshot(
            Request::builder()
                .uri("/health/ready")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(ready.status(), StatusCode::SERVICE_UNAVAILABLE);

    health.set_ready();
    let ready = router(health.clone())
        .oneshot(
            Request::builder()
                .uri("/health/ready")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(ready.status(), StatusCode::OK);
    let body = json_body(ready.into_body()).await;
    assert_eq!(body["state"], "ready");

    health.set_draining();
    let ready = router(health.clone())
        .oneshot(
            Request::builder()
                .uri("/health/ready")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(ready.status(), StatusCode::SERVICE_UNAVAILABLE);
}

/// `/docs` serves the interactive reference over the service's own spec.
#[tokio::test]
async fn docs_page_is_served() {
    let response = router(Health::starting())
        .oneshot(Request::builder().uri("/docs").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert!(response.headers()["content-type"]
        .to_str()
        .unwrap()
        .starts_with("text/html"));
}

/// The base framework serves **no** admin console: `/admin` is a `404`. The
/// console is an optional extension (`seiva-console-admin`, ADR 0008) a
/// composition root mounts explicitly; a plain backend carries none of it.
#[tokio::test]
async fn admin_is_not_part_of_the_base() {
    let response = router(Health::starting())
        .oneshot(
            Request::builder()
                .uri("/admin")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

/// `/openapi.json` is a valid 3.1 document carrying the framework version. The
/// demo-free `seiva-http` links no facade, so `paths` is an empty object here;
/// the full runtime that mounts modules documents their operations.
#[tokio::test]
async fn openapi_document_is_served() {
    let response = router(Health::starting())
        .oneshot(
            Request::builder()
                .uri("/openapi.json")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body = json_body(response.into_body()).await;
    assert_eq!(body["openapi"], "3.1.0");
    assert!(body["info"]["version"].is_string());
    assert!(body["paths"].is_object());
}

#[tokio::test]
async fn openapi_response_is_cacheable_with_a_strong_etag() {
    let response = router(Health::starting())
        .oneshot(
            Request::builder()
                .uri("/openapi.json")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let headers = response.headers();
    assert_eq!(
        headers.get(header::CONTENT_TYPE).unwrap(),
        "application/json"
    );
    let etag = headers
        .get(header::ETAG)
        .unwrap()
        .to_str()
        .unwrap()
        .to_owned();
    assert!(
        etag.starts_with('"') && etag.ends_with('"'),
        "a strong ETag is a quoted validator: {etag}"
    );
    assert!(
        headers.get(header::CACHE_CONTROL).is_some(),
        "the document is cacheable"
    );
    // The cached bytes are exactly what the generator produces: the wire JSON is
    // unchanged by caching.
    let body = json_body(response.into_body()).await;
    assert_eq!(body, seiva_http::openapi_document());
}

#[tokio::test]
async fn openapi_matching_if_none_match_is_304_not_modified() {
    // One request to learn the current ETag.
    let first = router(Health::starting())
        .oneshot(
            Request::builder()
                .uri("/openapi.json")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    let etag = first
        .headers()
        .get(header::ETAG)
        .unwrap()
        .to_str()
        .unwrap()
        .to_owned();

    // A conditional request carrying the matching validator is a 304 with no body.
    let second = router(Health::starting())
        .oneshot(
            Request::builder()
                .uri("/openapi.json")
                .header(header::IF_NONE_MATCH, &etag)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(second.status(), StatusCode::NOT_MODIFIED);
    let bytes = axum::body::to_bytes(second.into_body(), usize::MAX)
        .await
        .unwrap();
    assert!(bytes.is_empty(), "a 304 carries no body");
}

// --- The authn middleware (ADR 0006): deny-by-default, ahead of the guard ------

/// The guarded `/demo` route with the authentication middleware mounted *ahead*
/// of the permission guard, exactly as `router_with_auth` arranges them: authn
/// runs first and inserts the `Principal`, then the guard reads it.
fn authed_app(auth: TokenAuthenticator) -> Router {
    Router::new()
        .route("/demo", post(demo_create))
        .layer(from_fn_with_state(
            RequiredPermission("demo.create"),
            permission_guard,
        ))
        .layer(from_fn_with_state(
            Authn::bearer_only(Arc::new(auth) as Arc<dyn Authenticator>),
            authn,
        ))
        .layer(from_fn(request_id))
}

fn demo_authenticator() -> TokenAuthenticator {
    TokenAuthenticator::new().with_token(
        "good-token",
        Principal::in_tenant("user-1", "acme", ["demo.create"]),
    )
}

#[tokio::test]
async fn no_token_is_anonymous_and_a_guarded_route_is_403() {
    // Deny by default: a missing bearer is the anonymous principal, which holds
    // no permission, so the guard refuses — but the layer itself does not 401
    // (public routes must still serve).
    let request = Request::builder()
        .method("POST")
        .uri("/demo")
        .header("content-type", "application/json")
        .body(Body::from(r#"{"title":"x"}"#))
        .unwrap();
    let response = authed_app(demo_authenticator())
        .oneshot(request)
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::FORBIDDEN);
    assert_eq!(
        response.headers()[axum::http::header::CONTENT_TYPE],
        PROBLEM_JSON
    );
}

#[tokio::test]
async fn an_invalid_bearer_is_401_with_www_authenticate() {
    let request = Request::builder()
        .method("POST")
        .uri("/demo")
        .header("authorization", "Bearer not-a-real-token")
        .header("content-type", "application/json")
        .body(Body::from(r#"{"title":"x"}"#))
        .unwrap();
    let response = authed_app(demo_authenticator())
        .oneshot(request)
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(response.headers()["www-authenticate"], "Bearer");
    // Even a short-circuited 401 carries a correlation id.
    assert!(response.headers().contains_key(REQUEST_ID_HEADER));
}

#[tokio::test]
async fn a_valid_bearer_authenticates_and_the_guard_passes() {
    // The token maps to a Principal holding `demo.create`, so authn inserts it and
    // the guard admits the request: the identity flows end to end.
    let request = Request::builder()
        .method("POST")
        .uri("/demo")
        .header("authorization", "Bearer good-token")
        .header("content-type", "application/json")
        .body(Body::from(r#"{"title":"authed"}"#))
        .unwrap();
    let response = authed_app(demo_authenticator())
        .oneshot(request)
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
    let body = json_body(response.into_body()).await;
    assert_eq!(body["title"], "authed");
}

#[tokio::test]
async fn a_valid_token_without_the_permission_is_403() {
    // Authentication succeeds, authorization does not: a read-only caller is
    // admitted by authn but refused by the guard. AuthN and AuthZ are distinct.
    let auth = TokenAuthenticator::new().with_token(
        "reader",
        Principal::in_tenant("user-2", "acme", ["demo.read"]),
    );
    let request = Request::builder()
        .method("POST")
        .uri("/demo")
        .header("authorization", "Bearer reader")
        .header("content-type", "application/json")
        .body(Body::from(r#"{"title":"x"}"#))
        .unwrap();
    let response = authed_app(auth).oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::FORBIDDEN);
}

// --- The opaque `X-API-Key` path (A1): alongside the bearer path ---------------

/// The guarded `/demo` route with the authn middleware mounted via
/// [`Authn::with_api_key`]: an `X-API-Key` authenticator runs alongside the bearer
/// one, exactly the two-source arrangement the middleware documents.
fn api_key_authed_app(bearer: TokenAuthenticator, api_key: ApiKeyAuthenticator) -> Router {
    let state = Authn::with_api_key(
        Arc::new(bearer) as Arc<dyn Authenticator>,
        Arc::new(api_key) as Arc<dyn Authenticator>,
    );
    Router::new()
        .route("/demo", post(demo_create))
        .layer(from_fn_with_state(
            RequiredPermission("demo.create"),
            permission_guard,
        ))
        .layer(from_fn_with_state(state, authn))
        .layer(from_fn(request_id))
}

fn demo_api_keys() -> ApiKeyAuthenticator {
    ApiKeyAuthenticator::new().with_key(
        "sk_live_good",
        Principal::in_tenant("svc-1", "acme", ["demo.create"]),
    )
}

#[tokio::test]
async fn a_valid_api_key_authenticates_and_the_guard_passes() {
    // `X-API-Key` maps to a Principal holding `demo.create`: authn inserts it and
    // the guard admits the request — the key's scopes flow end to end.
    let request = Request::builder()
        .method("POST")
        .uri("/demo")
        .header("x-api-key", "sk_live_good")
        .header("content-type", "application/json")
        .body(Body::from(r#"{"title":"via-key"}"#))
        .unwrap();
    let response = api_key_authed_app(demo_authenticator(), demo_api_keys())
        .oneshot(request)
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
    let body = json_body(response.into_body()).await;
    assert_eq!(body["title"], "via-key");
}

#[tokio::test]
async fn an_unknown_api_key_is_401_with_www_authenticate_apikey() {
    let request = Request::builder()
        .method("POST")
        .uri("/demo")
        .header("x-api-key", "sk_live_nope")
        .header("content-type", "application/json")
        .body(Body::from(r#"{"title":"x"}"#))
        .unwrap();
    let response = api_key_authed_app(demo_authenticator(), demo_api_keys())
        .oneshot(request)
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(response.headers()["www-authenticate"], "ApiKey");
    assert!(response.headers().contains_key(REQUEST_ID_HEADER));
}

#[tokio::test]
async fn a_revoked_api_key_is_401() {
    // A key that once authenticated is refused after revocation — no stale access.
    let mut keys = demo_api_keys();
    assert!(keys.revoke("sk_live_good"));
    let request = Request::builder()
        .method("POST")
        .uri("/demo")
        .header("x-api-key", "sk_live_good")
        .header("content-type", "application/json")
        .body(Body::from(r#"{"title":"x"}"#))
        .unwrap();
    let response = api_key_authed_app(demo_authenticator(), keys)
        .oneshot(request)
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(response.headers()["www-authenticate"], "ApiKey");
}

#[tokio::test]
async fn the_bearer_path_still_works_alongside_the_api_key_path() {
    // With both sources configured, a request carrying only a bearer still
    // authenticates through the bearer authenticator — the paths are independent.
    let request = Request::builder()
        .method("POST")
        .uri("/demo")
        .header("authorization", "Bearer good-token")
        .header("content-type", "application/json")
        .body(Body::from(r#"{"title":"via-bearer"}"#))
        .unwrap();
    let response = api_key_authed_app(demo_authenticator(), demo_api_keys())
        .oneshot(request)
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
    let body = json_body(response.into_body()).await;
    assert_eq!(body["title"], "via-bearer");
}

#[tokio::test]
async fn module_routes_merged_via_router_with_modules_get_the_authn_layer() {
    // The composition a real apps/<name>-api performs: a guarded module route,
    // merged THROUGH the framework layers (not after them). The authn layer must
    // apply to it — a bad bearer is a 401, proving the middleware is not bypassed.
    let module = Router::new()
        .route("/demo", post(demo_create))
        .layer(from_fn_with_state(
            RequiredPermission("demo.create"),
            permission_guard,
        ));
    let app = router_with_modules(
        Health::starting(),
        &HttpSecurity::default(),
        Some(Arc::new(demo_authenticator()) as Arc<dyn Authenticator>),
        module,
    );

    // Bad bearer → 401 from the authn layer (it reached the module route).
    let bad = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/demo")
                .header("authorization", "Bearer nope")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"title":"x"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(bad.status(), StatusCode::UNAUTHORIZED);
    // And it carries the framework's security headers (the module route is inside them).
    assert_eq!(bad.headers()["x-content-type-options"], "nosniff");

    // Valid bearer → the Principal flows to the guard and the route runs.
    let ok = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/demo")
                .header("authorization", "Bearer good-token")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"title":"authed"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(ok.status(), StatusCode::CREATED);
}

#[tokio::test]
async fn router_with_modules_mounts_the_api_key_path_at_app_level() {
    // A1 fatia 2: the `X-API-Key` path must be reachable through the app-level
    // builder, not only via `Authn::with_api_key` on a hand-rolled layer. A real
    // `apps/<name>-api` hands `router_with_modules` an `AuthConfig::with_api_key`,
    // and a guarded module route then admits a valid key and refuses an unknown one.
    let module = Router::new()
        .route("/demo", post(demo_create))
        .layer(from_fn_with_state(
            RequiredPermission("demo.create"),
            permission_guard,
        ));
    let auth = AuthConfig::bearer(Arc::new(demo_authenticator()) as Arc<dyn Authenticator>)
        .with_api_key(Arc::new(demo_api_keys()) as Arc<dyn Authenticator>);
    let app = router_with_modules(Health::starting(), &HttpSecurity::default(), auth, module);

    // A valid `X-API-Key` authenticates and the guard passes → 201, through the
    // whole framework stack (the module route is inside the authn layer).
    let created = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/demo")
                .header("x-api-key", "sk_live_good")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"title":"via-app-key"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(created.status(), StatusCode::CREATED);
    // And it carries the framework's security headers (the module route is inside them).
    assert_eq!(created.headers()["x-content-type-options"], "nosniff");
    let body = json_body(created.into_body()).await;
    assert_eq!(body["title"], "via-app-key");

    // An unknown key is refused by the authn layer before the route runs → 401.
    let denied = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/demo")
                .header("x-api-key", "sk_live_nope")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"title":"x"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(denied.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(denied.headers()["www-authenticate"], "ApiKey");
}