seiva-http 0.1.0

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
//! 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::{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, Authenticator, Health,
    HttpSecurity, Principal, Problem, 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>) -> Result<Response, Problem> {
    Ok((
        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(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(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(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(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());
}

// --- 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(
            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);
}

#[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);
}