Skip to main content

seiva_http/
security.rs

1//! Secure-by-default response headers and configurable CORS.
2//!
3//! The framework's threat model treats a Seiva service as a JSON API sitting
4//! behind a TLS-terminating edge. Two transport-level controls address OWASP API
5//! Security **API8 (Security Misconfiguration)**:
6//!
7//! - [`security_headers`] — a tower middleware that adds a conservative set of
8//!   response headers (content-type sniffing off, framing denied, a locked-down
9//!   Content-Security-Policy, HSTS) to **every** response, problems included. It
10//!   only ever adds a header that is *absent*, so a handler that deliberately set
11//!   its own value (a UI route relaxing the CSP, say) keeps it — no hidden
12//!   override.
13//! - [`cors_layer`] — builds a [`CorsLayer`] from an explicit allowlist of
14//!   origins ([`HttpSecurity::cors_allowed_origins`]). An **empty** allowlist
15//!   means no CORS layer at all, i.e. browsers enforce same-origin — the secure
16//!   default. A cross-origin caller is admitted only when its `Origin` is on the
17//!   list.
18//!
19//! Neither control changes a same-origin, non-browser caller's behaviour beyond
20//! the added response headers, so wiring them into [`router`](crate::router) does
21//! not break an existing request path.
22
23use axum::http::header::{
24    HeaderName, HeaderValue, CONTENT_SECURITY_POLICY, REFERRER_POLICY, STRICT_TRANSPORT_SECURITY,
25    X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS,
26};
27use axum::http::Method;
28use axum::{extract::Request, middleware::Next, response::Response};
29use tower_http::cors::{AllowOrigin, CorsLayer};
30
31use crate::rate_limit::RateLimit;
32
33/// `X-XSS-Protection`, set to `0` to disable the legacy, deprecated and
34/// footgun-prone browser XSS auditor (current guidance; the CSP does the real
35/// work). Not a typed constant in `http`, so named here.
36static X_XSS_PROTECTION: HeaderName = HeaderName::from_static("x-xss-protection");
37
38/// The transport's security configuration: the knobs a deployment turns that are
39/// not safe to hard-code. Read from the environment by the server runtime (see
40/// `seiva-server`) and handed to [`router_with_security`](crate::router_with_security).
41///
42/// [`Default`] is the secure baseline: **no** cross-origin access (same-origin
43/// only) and rate limiting **on** at [`RateLimit::default`]. A deployment opts
44/// origins in and tunes (or disables) the limit explicitly.
45#[derive(Debug, Clone)]
46pub struct HttpSecurity {
47    /// The exact origins allowed to make cross-origin (CORS) requests, e.g.
48    /// `https://app.example.com`. Empty means same-origin only: [`cors_layer`]
49    /// returns `None` and no `Access-Control-Allow-Origin` is ever emitted.
50    pub cors_allowed_origins: Vec<String>,
51    /// The per-client request rate limit, or `None` to disable rate limiting.
52    /// `Some(RateLimit::default())` by default — disabling it is an explicit
53    /// choice, never the default.
54    pub rate_limit: Option<RateLimit>,
55    /// Whether the rate limiter keys on the trusted `X-Forwarded-For` client IP
56    /// instead of the raw TCP peer. Leave `false` (the default) for a directly
57    /// exposed service; set it **only** behind a single trusted reverse proxy, or
58    /// every client collapses into the proxy's single bucket. See
59    /// [`RateLimiter::trusting_forwarded_for`](crate::RateLimiter::trusting_forwarded_for).
60    pub trust_forwarded_for: bool,
61    /// Whether to serve the interactive API reference (`/docs`, `/redoc`,
62    /// `/scalar`) and the generated `/openapi.json`. `true` by default (the
63    /// FastAPI-style discovery that is a product feature). A deployment that does
64    /// not want to publish its full contract to anonymous callers (OWASP API9 —
65    /// improper inventory management) sets it `false`, and those four routes answer
66    /// `404` while every module route keeps working.
67    pub expose_docs: bool,
68}
69
70impl Default for HttpSecurity {
71    fn default() -> Self {
72        Self {
73            cors_allowed_origins: Vec::new(),
74            rate_limit: Some(RateLimit::default()),
75            trust_forwarded_for: false,
76            expose_docs: true,
77        }
78    }
79}
80
81impl HttpSecurity {
82    /// A configuration allowing the given origins for CORS (rate limiting left at
83    /// the default). Each origin must be a full `scheme://host[:port]`, compared
84    /// verbatim against the request's `Origin` header.
85    #[must_use]
86    pub fn with_cors_origins<I, S>(origins: I) -> Self
87    where
88        I: IntoIterator<Item = S>,
89        S: Into<String>,
90    {
91        Self {
92            cors_allowed_origins: origins.into_iter().map(Into::into).collect(),
93            ..Self::default()
94        }
95    }
96}
97
98/// Adds a secure-by-default header only when the response does not already carry
99/// it, so a handler's deliberate choice is never silently overridden.
100fn set_if_absent(response: &mut Response, name: HeaderName, value: &'static str) {
101    let headers = response.headers_mut();
102    if !headers.contains_key(&name) {
103        headers.insert(name, HeaderValue::from_static(value));
104    }
105}
106
107/// Middleware that adds the framework's default security response headers.
108///
109/// Applied to every response (success and [`Problem`](crate::Problem) alike):
110///
111/// - `X-Content-Type-Options: nosniff` — no MIME sniffing.
112/// - `X-Frame-Options: DENY` and `Content-Security-Policy: default-src 'none';
113///   frame-ancestors 'none'` — the response is not framed and loads nothing; a
114///   JSON API needs no richer policy, and a route that does sets its own first.
115/// - `Referrer-Policy: no-referrer` — no referrer leakage.
116/// - `Strict-Transport-Security: max-age=63072000; includeSubDomains` — HSTS,
117///   meaningful once served over TLS (the assumed edge); a browser ignores it
118///   over plain HTTP, so it is harmless in local development.
119/// - `X-XSS-Protection: 0` — disables the deprecated legacy auditor.
120///
121/// Mount it with [`axum::middleware::from_fn`].
122pub async fn security_headers(request: Request, next: Next) -> Response {
123    let mut response = next.run(request).await;
124    set_if_absent(&mut response, X_CONTENT_TYPE_OPTIONS, "nosniff");
125    set_if_absent(&mut response, X_FRAME_OPTIONS, "DENY");
126    set_if_absent(
127        &mut response,
128        CONTENT_SECURITY_POLICY,
129        "default-src 'none'; frame-ancestors 'none'",
130    );
131    set_if_absent(&mut response, REFERRER_POLICY, "no-referrer");
132    set_if_absent(
133        &mut response,
134        STRICT_TRANSPORT_SECURITY,
135        "max-age=63072000; includeSubDomains",
136    );
137    set_if_absent(&mut response, X_XSS_PROTECTION.clone(), "0");
138    response
139}
140
141/// Builds the CORS layer from the configured allowlist, or `None` when the
142/// allowlist is empty (same-origin only — the secure default).
143///
144/// When non-empty, only an exact `Origin` on the list is reflected back in
145/// `Access-Control-Allow-Origin`; every other origin is left without CORS
146/// headers, so the browser blocks the cross-origin read. A malformed origin in
147/// the list is skipped (it can never match a real `Origin` header anyway).
148#[must_use]
149pub fn cors_layer(security: &HttpSecurity) -> Option<CorsLayer> {
150    if security.cors_allowed_origins.is_empty() {
151        return None;
152    }
153    let origins: Vec<HeaderValue> = security
154        .cors_allowed_origins
155        .iter()
156        .filter_map(|o| HeaderValue::from_str(o).ok())
157        .collect();
158    if origins.is_empty() {
159        return None;
160    }
161    Some(
162        CorsLayer::new()
163            .allow_origin(AllowOrigin::list(origins))
164            .allow_methods([
165                Method::GET,
166                Method::POST,
167                Method::PUT,
168                Method::PATCH,
169                Method::DELETE,
170                Method::OPTIONS,
171            ])
172            .allow_headers([
173                axum::http::header::CONTENT_TYPE,
174                axum::http::header::AUTHORIZATION,
175            ]),
176    )
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182    use crate::{router_with_security, Health};
183    use axum::body::Body;
184    use axum::http::{Request, StatusCode};
185    use tower::ServiceExt; // for `oneshot`
186
187    fn ready_app(security: &HttpSecurity) -> axum::Router {
188        let health = Health::starting();
189        health.set_ready();
190        router_with_security(health, security)
191    }
192
193    #[tokio::test]
194    async fn security_headers_are_present_even_on_a_rate_limited_429() {
195        use crate::RateLimit;
196        use std::time::Duration;
197
198        // A limit of one request per minute: the second request in the window is
199        // a 429 that short-circuits before the route. It must STILL carry the
200        // secure-by-default headers (regression: they used to be stripped because
201        // the limiter sat outside the header layer). Uses `/openapi.json` because
202        // the health probes are now exempt from the limiter (§8).
203        let security = HttpSecurity {
204            rate_limit: Some(RateLimit {
205                max_requests: 1,
206                window: Duration::from_secs(60),
207            }),
208            ..HttpSecurity::default()
209        };
210        let app = ready_app(&security);
211
212        let req = || {
213            Request::builder()
214                .uri("/openapi.json")
215                .body(Body::empty())
216                .unwrap()
217        };
218        let ok = app.clone().oneshot(req()).await.unwrap();
219        assert_eq!(ok.status(), StatusCode::OK);
220
221        let limited = app.oneshot(req()).await.unwrap();
222        assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS);
223        let headers = limited.headers();
224        assert_eq!(headers["x-content-type-options"], "nosniff");
225        assert_eq!(headers["x-frame-options"], "DENY");
226        assert!(headers.contains_key("content-security-policy"));
227        assert!(headers.contains_key("strict-transport-security"));
228        // And still the correlation id a problem response needs.
229        assert!(headers.contains_key(crate::REQUEST_ID_HEADER));
230    }
231
232    #[tokio::test]
233    async fn security_headers_are_present_on_every_response() {
234        let app = ready_app(&HttpSecurity::default());
235        let res = app
236            .oneshot(
237                Request::builder()
238                    .uri("/health/ready")
239                    .body(Body::empty())
240                    .unwrap(),
241            )
242            .await
243            .unwrap();
244        assert_eq!(res.status(), StatusCode::OK);
245        let headers = res.headers();
246        assert_eq!(headers["x-content-type-options"], "nosniff");
247        assert_eq!(headers["x-frame-options"], "DENY");
248        assert!(headers["content-security-policy"]
249            .to_str()
250            .unwrap()
251            .contains("default-src 'none'"));
252        assert_eq!(headers["referrer-policy"], "no-referrer");
253        assert!(headers.contains_key("strict-transport-security"));
254        assert_eq!(headers["x-xss-protection"], "0");
255    }
256
257    #[tokio::test]
258    async fn default_posture_emits_no_cors_header() {
259        // Same-origin only: an allowlisted origin is required for any
260        // Access-Control-Allow-Origin to appear.
261        assert!(cors_layer(&HttpSecurity::default()).is_none());
262        let app = ready_app(&HttpSecurity::default());
263        let res = app
264            .oneshot(
265                Request::builder()
266                    .uri("/health/ready")
267                    .header("origin", "https://evil.example")
268                    .body(Body::empty())
269                    .unwrap(),
270            )
271            .await
272            .unwrap();
273        assert!(!res.headers().contains_key("access-control-allow-origin"));
274    }
275
276    #[tokio::test]
277    async fn cors_reflects_an_allowlisted_origin_only() {
278        let security = HttpSecurity::with_cors_origins(["https://app.example.com"]);
279        let app = ready_app(&security);
280
281        // The allowlisted origin is reflected back.
282        let allowed = app
283            .clone()
284            .oneshot(
285                Request::builder()
286                    .uri("/health/ready")
287                    .header("origin", "https://app.example.com")
288                    .body(Body::empty())
289                    .unwrap(),
290            )
291            .await
292            .unwrap();
293        assert_eq!(
294            allowed.headers()["access-control-allow-origin"],
295            "https://app.example.com"
296        );
297
298        // An origin NOT on the list gets no CORS header, so the browser blocks it.
299        let blocked = app
300            .oneshot(
301                Request::builder()
302                    .uri("/health/ready")
303                    .header("origin", "https://evil.example")
304                    .body(Body::empty())
305                    .unwrap(),
306            )
307            .await
308            .unwrap();
309        assert!(!blocked
310            .headers()
311            .contains_key("access-control-allow-origin"));
312    }
313}