Skip to main content

seiva_http/
lib.rs

1//! Delonix Seiva — the HTTP transport.
2//!
3//! This crate provides the transport-level pieces a module's generated
4//! controller builds on. It is **demo-free and DORM-free**: it links no example
5//! module and no data layer, so it is a publishable building block. A module's
6//! `#[seiva::controller]` router and the composition root (`seiva-server` or a
7//! project's `apps/<name>-api`) merge the module routes into [`router`].
8//!
9//! - [`problem`] — RFC 9457 `application/problem+json` errors ([`Problem`]).
10//! - [`valid`] — a typed, validated JSON body extractor ([`Valid`], [`Validate`]).
11//! - [`guard`] — a descriptor-driven permission guard ([`permission_guard`],
12//!   [`Principal`], [`RequiredPermission`]) plus tenant-ownership checks.
13//! - [`bus`] — the context-bound pipeline behaviors ([`Authorize`],
14//!   [`Idempotent`]) that complete the ADR 0020 chain over the `seiva-cqrs`
15//!   [`Validate`](seiva_cqrs::Validate)/[`Transactional`](seiva_cqrs::Transactional).
16//! - [`security`] — secure-by-default response headers and configurable CORS.
17//! - [`mod@rate_limit`] — a per-client request rate limiter.
18//! - [`health`] — `/health/live` and `/health/ready` over a
19//!   `Starting -> Ready -> Draining` lifecycle ([`Health`]).
20//! - [`docs`] — an interactive `/docs` API reference over `/openapi.json`.
21//! - [`mod@request_id`] — per-request correlation ([`RequestId`]).
22//!
23//! [`router`] assembles the framework surface — health, `/openapi.json`
24//! (generated from every facade linked into the binary) and `/docs` — wrapped in
25//! the security headers, optional CORS, the body-size limit, the rate limiter and
26//! the request-id middleware. It mounts no module route itself; the composition
27//! root merges those in.
28
29#![forbid(unsafe_code)]
30
31pub mod audit;
32pub mod authn;
33pub mod backpressure;
34pub mod bus;
35pub mod ctx;
36pub mod docs;
37pub mod guard;
38pub mod health;
39pub mod idempotency;
40pub mod metrics;
41#[cfg(feature = "mtls")]
42pub mod mtls;
43pub mod problem;
44pub mod rate_limit;
45pub mod request_id;
46pub mod security;
47pub mod valid;
48
49use axum::body::Bytes;
50use axum::extract::DefaultBodyLimit;
51use axum::http::{header, HeaderMap, StatusCode};
52use axum::middleware::{from_fn, from_fn_with_state};
53use axum::response::{IntoResponse, Response};
54use axum::routing::get;
55use axum::Router;
56use sha2::{Digest, Sha256};
57
58pub use audit::audit;
59pub use authn::{authn, AuthConfig, Authn};
60pub use backpressure::{with_route_controls, RouteControls, RouteLimit};
61pub use bus::{Authorize, Idempotent, DEFAULT_IDEMPOTENCY_TTL};
62pub use ctx::Ctx;
63pub use docs::{docs_handler, redoc_handler, scalar_handler, DOCS_HTML};
64pub use guard::{permission_guard, require_permission, PrincipalExt, RequiredPermission, Scoped};
65pub use health::{
66    health_router, health_router_with_dependency, Health, HealthState, ReadinessCheck,
67};
68pub use idempotency::{
69    fingerprint, in_progress_problem, mismatch_problem, scoped_key, IdempotencyKey,
70    OptionalIdempotencyKey, IDEMPOTENCY_HEADER, MAX_KEY_LEN,
71};
72pub use metrics::{track_metrics, REQUESTS_IN_FLIGHT, REQUESTS_TOTAL, REQUEST_DURATION_SECONDS};
73pub use problem::{Problem, ProblemResponse, PROBLEM_JSON};
74pub use rate_limit::{
75    rate_limit, rate_limit_with_store, DistributedRateLimit, RateLimit, RateLimiter,
76};
77pub use request_id::{request_id, RequestId, REQUEST_ID_HEADER};
78pub use security::{cors_layer, security_headers, HttpSecurity};
79pub use seiva_ports::{AuditEntry, AuditSink};
80pub use seiva_ports::{RateLimitDecision, RateLimitStore};
81pub use valid::{Valid, Validate, ValidationError};
82// The identity model is owned by `seiva-identity` (transport-free, shared with
83// MCP); re-exported here so a `seiva_http::Principal` import keeps working.
84pub use seiva_identity::{
85    ApiKeyAuthenticator, AuthError, Authenticator, JwtAuthenticator, Principal, TokenAuthenticator,
86};
87
88/// The default maximum request body size (1 MiB). Oversized bodies are rejected
89/// before a handler runs. Mounted as [`DefaultBodyLimit`] in [`router`].
90pub const DEFAULT_BODY_LIMIT_BYTES: usize = 1024 * 1024;
91
92/// The default per-request timeout (30 s). A request whose handler (or whose slow
93/// client streaming the body) outlives this is cut off with `408 Request Timeout`,
94/// so a slowloris client cannot pin a worker indefinitely (OWASP API4). Mounted as
95/// a [`tower_http::timeout::TimeoutLayer`] in the framework layers.
96pub const DEFAULT_REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
97
98/// Builds the service's OpenAPI 3.1 document from **every facade linked into the
99/// binary**, discovered through [`seiva::contract::registered_facades`]
100/// (each `#[seiva::facade]` registers itself in a link-time inventory). Nothing
101/// here is hand-written and no central list is kept: a module mounted into the
102/// runtime contributes its operations automatically (OWASP API9). This crate
103/// links no facade of its own, so a plain `seiva-http` binary documents nothing;
104/// the full runtime (see `seiva-server`) documents every mounted module.
105pub fn openapi_document() -> serde_json::Value {
106    let facades = seiva::contract::registered_facades();
107    seiva_openapi::openapi_document(
108        seiva_openapi::ApiInfo {
109            title: "Delonix Seiva service".to_string(),
110            version: seiva::VERSION.to_string(),
111        },
112        &facades,
113    )
114}
115
116/// `GET /openapi.json` — serves the generated [`openapi_document`].
117///
118/// The document is derived entirely from the link-time facade inventory, so it is
119/// immutable for the life of the process. It is therefore generated and serialized
120/// **once** (behind a [`OnceLock`](std::sync::OnceLock)) and every request serves
121/// the cached bytes — an `O(1)` [`Bytes`] clone, with no regeneration and no
122/// re-serialization. The response carries a strong `ETag` (SHA-256 of the body)
123/// and `Cache-Control`, and a conditional request whose `If-None-Match` matches is
124/// answered `304 Not Modified`. This keeps an unauthenticated route from being a
125/// cheap regenerate-per-request DoS vector (OWASP API4).
126async fn openapi_handler(headers: HeaderMap) -> Response {
127    let cached = cached_openapi();
128    if let Some(inm) = headers.get(header::IF_NONE_MATCH) {
129        if inm.as_bytes() == cached.etag.as_bytes() {
130            return StatusCode::NOT_MODIFIED.into_response();
131        }
132    }
133    (
134        [
135            (header::CONTENT_TYPE, "application/json"),
136            (header::ETAG, cached.etag.as_str()),
137            (header::CACHE_CONTROL, "public, max-age=300"),
138        ],
139        cached.body.clone(),
140    )
141        .into_response()
142}
143
144/// The generated OpenAPI document, serialized once per process.
145struct CachedOpenApi {
146    /// The serialized `application/json` body. Cloning it per request is an `O(1)`
147    /// reference-count bump, not a copy of the bytes.
148    body: Bytes,
149    /// A strong validator: the quoted SHA-256 hex of `body` (RFC 9110 §8.8.3).
150    /// Deterministic across replicas running the same binary.
151    etag: String,
152}
153
154/// Builds (once) and returns the cached `/openapi.json` payload. The document is
155/// immutable after link time, so the initializer runs exactly once per process.
156fn cached_openapi() -> &'static CachedOpenApi {
157    static CACHE: std::sync::OnceLock<CachedOpenApi> = std::sync::OnceLock::new();
158    CACHE.get_or_init(|| {
159        let body = serde_json::to_vec(&openapi_document())
160            .expect("the generated OpenAPI document always serializes");
161        let etag = format!("\"{}\"", idempotency::hex(Sha256::digest(&body).as_slice()));
162        CachedOpenApi {
163            body: Bytes::from(body),
164            etag,
165        }
166    })
167}
168
169/// The `(version, resource)` route-prefix collisions among **every facade linked
170/// into the binary** — two facades whose generated routers would mount on the same
171/// prefix and make `Router::merge` panic at startup. Empty when the mounted
172/// facades are collision-free. A composition root calls this at boot to fail fast
173/// with a clear message instead of a bare axum panic (see
174/// [`seiva::contract::route_collisions`]).
175#[must_use]
176pub fn route_collisions() -> Vec<String> {
177    seiva::contract::route_collisions(&seiva::contract::registered_facades())
178}
179
180/// Builds the framework router with the **default** security posture
181/// ([`HttpSecurity::default`]: secure response headers on, same-origin only — no
182/// CORS). Equivalent to [`router_with_security`] with the default configuration;
183/// the zero-config entrypoint.
184pub fn router(health: Health) -> Router {
185    router_with_security(health, &HttpSecurity::default())
186}
187
188/// Builds the framework router — the health endpoints, `/openapi.json` and
189/// `/docs`. Request flows through the layers outermost-first:
190/// [`request_id()`] → [`security_headers`] → the rate limiter → the optional CORS
191/// layer → the body-size limit → the route.
192///
193/// `security_headers` and `request_id` are the **outermost** layers on purpose:
194/// every response carries them even when an outer layer short-circuits before the
195/// route runs — a rate-limiter `429` or a CORS preflight included. (With the
196/// headers mounted inside the rate limiter, a `429` went out naked — no CSP, no
197/// `nosniff`, no HSTS — measured end-to-end.)
198///
199/// It mounts no module route; the composition root merges each module's generated
200/// controller router into the result. `security` controls the transport-level
201/// API8 defences: the response headers are always applied, and CORS is mounted
202/// only when [`HttpSecurity::cors_allowed_origins`] is non-empty (otherwise the
203/// browser enforces same-origin).
204pub fn router_with_security(health: Health, security: &HttpSecurity) -> Router {
205    router_with_auth(health, security, AuthConfig::none())
206}
207
208/// Builds the framework router under `security` and an optional authentication
209/// layer, described by `auth` (an [`AuthConfig`], or any `Option<Arc<dyn
210/// Authenticator>>` which converts into a bearer-only one). When it carries any
211/// authenticator, every request is authenticated (ADR 0006) ahead of any route's
212/// [`permission_guard`] — a missing credential becomes [`Principal::anonymous`]
213/// (public routes still serve, guarded routes `403`), a present-but-invalid one
214/// is a `401`. [`AuthConfig::none`] mounts no authn layer (no caller is ever
215/// authenticated, so guarded routes answer `403`): the composition root supplies
216/// an [`Authenticator`] to actually admit callers. Pass
217/// [`AuthConfig::with_api_key`] to also admit opaque `X-API-Key` callers.
218///
219/// Layer order, outermost-first: [`request_id()`] → [`security_headers`] →
220/// [`authn()`] → the rate limiter → CORS → the body-size limit → the route.
221/// `authn` sits inside the header layers (so a `401` still carries them) but
222/// outside the routes (so it runs before each route's guard).
223pub fn router_with_auth(
224    health: Health,
225    security: &HttpSecurity,
226    auth: impl Into<AuthConfig>,
227) -> Router {
228    apply_framework_layers(
229        framework_routes(health, security.expose_docs),
230        security,
231        auth.into(),
232        None,
233    )
234}
235
236/// Builds the full application router: the framework routes **plus the caller's
237/// `modules`**, wrapped in the framework layers — the composition a real
238/// `apps/<name>-api` needs.
239///
240/// Why this exists: axum's [`Router::layer`](axum::Router::layer) wraps only the
241/// routes already present, so `router_with_auth(..).merge(modules)` would leave
242/// the module routes **outside** every middleware — no authn, no security
243/// headers, no rate limit. Merging the modules *before* layering (what this does)
244/// is the only order that applies the framework's guarantees to module routes.
245/// Mount each module's generated controller router into `modules` and pass it here.
246///
247/// `auth` is an [`AuthConfig`] (or any `Option<Arc<dyn Authenticator>>`, which
248/// converts into a bearer-only one): pass [`AuthConfig::with_api_key`] to also
249/// admit opaque `X-API-Key` callers against the module routes.
250pub fn router_with_modules(
251    health: Health,
252    security: &HttpSecurity,
253    auth: impl Into<AuthConfig>,
254    modules: Router,
255) -> Router {
256    apply_framework_layers(
257        framework_routes(health, security.expose_docs).merge(modules),
258        security,
259        auth.into(),
260        None,
261    )
262}
263
264/// Like [`router_with_modules`], but enforces the per-client rate limit with a
265/// **distributed** store ([`DistributedRateLimit`], ADR 0015) instead of the
266/// per-process limiter — the form that holds ONE budget across replicas behind a
267/// load balancer. The distributed limiter takes the in-process one's exact layer
268/// position (inside the security headers, so a `429` still carries them), so a
269/// `429` keeps its correlation id and headers; `security.rate_limit` is ignored
270/// when a distributed limiter is supplied. Set `security.trust_forwarded_for`
271/// (and pass it through on the limiter) only behind a single trusted proxy.
272pub fn router_with_modules_distributed(
273    health: Health,
274    security: &HttpSecurity,
275    auth: impl Into<AuthConfig>,
276    modules: Router,
277    distributed: DistributedRateLimit,
278) -> Router {
279    apply_framework_layers(
280        framework_routes(health, security.expose_docs).merge(modules),
281        security,
282        auth.into(),
283        Some(distributed),
284    )
285}
286
287/// The framework's own routes, unlayered: health, `/openapi.json`, and the three
288/// interactive reference pages (`/docs` = Swagger UI, `/redoc` = ReDoc,
289/// `/scalar` = Scalar) — the FastAPI `/docs` + `/redoc` parity, served by default
290/// with no annotations from the developer (see [`docs`]).
291///
292/// There is deliberately **no** `/admin` here: the admin console is an optional
293/// extension (`seiva-console-admin`, ADR 0008), not part of the base. A backend
294/// built without that crate answers `404` for `/admin`; a composition root that
295/// wants it calls `seiva_console_admin::mount(router)` before serving.
296fn framework_routes(health: Health, expose_docs: bool) -> Router {
297    let mut router = Router::new().merge(health_router(health));
298    // The contract-discovery surface is opt-out: on by default (FastAPI parity),
299    // but a deployment that must not publish its contract to anonymous callers
300    // (OWASP API9) sets `HttpSecurity::expose_docs = false` and these answer `404`.
301    if expose_docs {
302        router = router
303            .route("/openapi.json", get(openapi_handler))
304            .route("/docs", get(docs::docs_handler))
305            .route("/redoc", get(docs::redoc_handler))
306            .route("/scalar", get(docs::scalar_handler));
307    }
308    router
309}
310
311/// Wraps `app` (framework routes, and any merged module routes) in the transport
312/// middleware. Layer order, outermost-first: [`request_id()`] →
313/// [`security_headers`] → [`authn()`] → the rate limiter → CORS → the body-size
314/// limit → the route. `authn` sits inside the header layers (so a `401` still
315/// carries them) but outside the routes (so it runs before each route's guard).
316fn apply_framework_layers(
317    app: Router,
318    security: &HttpSecurity,
319    auth: AuthConfig,
320    distributed: Option<DistributedRateLimit>,
321) -> Router {
322    let mut app = app
323        .layer(DefaultBodyLimit::max(DEFAULT_BODY_LIMIT_BYTES))
324        // Inside the body limit: bound the lifetime of every request so a slow or
325        // stuck handler (or a slowloris client) cannot hold a worker forever. A
326        // breach returns `408 Request Timeout`.
327        .layer(tower_http::timeout::TimeoutLayer::with_status_code(
328            axum::http::StatusCode::REQUEST_TIMEOUT,
329            DEFAULT_REQUEST_TIMEOUT,
330        ));
331
332    if let Some(cors) = cors_layer(security) {
333        app = app.layer(cors);
334    }
335
336    // The distributed limiter, when supplied, takes the in-process one's place at
337    // this exact layer position; otherwise the per-process limiter runs if the
338    // security config enables it.
339    if let Some(dist) = distributed {
340        app = app.layer(from_fn_with_state(dist, rate_limit_with_store));
341    } else if let Some(limit) = security.rate_limit {
342        let limiter = RateLimiter::new(limit).trusting_forwarded_for(security.trust_forwarded_for);
343        app = app.layer(from_fn_with_state(limiter, rate_limit));
344    }
345
346    if let Some(authn_state) = auth.into_authn() {
347        app = app.layer(from_fn_with_state(authn_state, authn));
348    }
349
350    // Outermost: so a short-circuited response (a 429, a 401, a CORS preflight)
351    // still leaves through the security headers and gets a correlation id.
352    app = app
353        .layer(from_fn(security_headers))
354        .layer(from_fn(request_id));
355
356    // The metrics layer is the very outermost so its latency histogram and
357    // in-flight gauge measure the WHOLE handling (rate limit, auth, route). It
358    // reads the matched route TEMPLATE for a low-cardinality label and is a no-op
359    // until a recorder is installed at the root (ADR 0027); health probes are
360    // exempt inside the middleware.
361    app.layer(from_fn(metrics::track_metrics))
362}