umbral-security 0.0.12

Security headers + CSRF middleware plugin for umbral.
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
//! Integration coverage for umbral-security. Exercises the CSRF
//! double-submit flow and the security-header bundle by running
//! requests through `Plugin::wrap_router` against a one-route
//! Router.

use axum::Router;
use axum::body::Body;
use axum::routing::{get, post};
use http::header::{COOKIE, HeaderValue, SET_COOKIE};
use http::{Method, Request, StatusCode};
use http_body_util::BodyExt;
use tower::ServiceExt;
use umbral::prelude::Plugin;
use umbral_security::{SecurityConfig, SecurityPlugin, generate_token};

fn app() -> Router {
    let inner = Router::new()
        .route("/", get(|| async { "ok-get" }))
        .route("/save", post(|| async { "ok-save" }));
    SecurityPlugin::new().wrap_router(inner)
}

async fn body_string(resp: http::Response<Body>) -> (StatusCode, http::HeaderMap, String) {
    let status = resp.status();
    let headers = resp.headers().clone();
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    (
        status,
        headers,
        String::from_utf8_lossy(&bytes).into_owned(),
    )
}

#[tokio::test]
async fn safe_method_without_cookie_gets_one_set() {
    let req = Request::builder()
        .method(Method::GET)
        .uri("/")
        .body(Body::empty())
        .unwrap();
    let (status, headers, body) = body_string(app().oneshot(req).await.unwrap()).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, "ok-get");
    let set_cookie = headers
        .get(SET_COOKIE)
        .expect("first GET should mint a CSRF cookie");
    let s = set_cookie.to_str().unwrap();
    assert!(s.starts_with("umbral_csrf_token="), "got: {s}");
    assert!(s.contains("Path=/"));
    assert!(s.contains("SameSite=Lax"));
}

#[tokio::test]
async fn safe_method_with_existing_cookie_does_not_re_set() {
    let req = Request::builder()
        .method(Method::GET)
        .uri("/")
        .header(COOKIE, "umbral_csrf_token=abcdef")
        .body(Body::empty())
        .unwrap();
    let (status, headers, _) = body_string(app().oneshot(req).await.unwrap()).await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        headers.get(SET_COOKIE).is_none(),
        "cookie was already present"
    );
}

#[tokio::test]
async fn write_request_without_cookie_or_header_is_403() {
    let req = Request::builder()
        .method(Method::POST)
        .uri("/save")
        .body(Body::empty())
        .unwrap();
    let (status, _, body) = body_string(app().oneshot(req).await.unwrap()).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
    assert!(body.contains("CSRF"));
}

#[tokio::test]
async fn write_request_with_cookie_but_no_header_is_403() {
    let req = Request::builder()
        .method(Method::POST)
        .uri("/save")
        .header(COOKIE, "umbral_csrf_token=tok-1")
        .body(Body::empty())
        .unwrap();
    let (status, _, _) = body_string(app().oneshot(req).await.unwrap()).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn write_request_with_mismatched_tokens_is_403() {
    let req = Request::builder()
        .method(Method::POST)
        .uri("/save")
        .header(COOKIE, "umbral_csrf_token=tok-1")
        .header("x-csrf-token", "tok-2")
        .body(Body::empty())
        .unwrap();
    let (status, _, _) = body_string(app().oneshot(req).await.unwrap()).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn write_request_with_matching_tokens_passes() {
    let req = Request::builder()
        .method(Method::POST)
        .uri("/save")
        .header(COOKIE, "umbral_csrf_token=matching")
        .header("x-csrf-token", "matching")
        .body(Body::empty())
        .unwrap();
    let (status, _, body) = body_string(app().oneshot(req).await.unwrap()).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, "ok-save");
}

#[tokio::test]
async fn default_security_headers_are_set() {
    let req = Request::builder()
        .method(Method::GET)
        .uri("/")
        .body(Body::empty())
        .unwrap();
    let (status, headers, _) = body_string(app().oneshot(req).await.unwrap()).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(
        headers.get("x-content-type-options"),
        Some(&HeaderValue::from_static("nosniff"))
    );
    assert_eq!(
        headers.get("x-frame-options"),
        Some(&HeaderValue::from_static("DENY"))
    );
    assert_eq!(
        headers.get("referrer-policy"),
        Some(&HeaderValue::from_static("strict-origin-when-cross-origin"))
    );
    assert!(
        headers.get("strict-transport-security").is_none(),
        "HSTS should be off by default"
    );
}

#[tokio::test]
async fn hsts_header_appears_when_opted_in() {
    let inner = Router::new().route("/", get(|| async { "ok" }));
    let router = SecurityPlugin::new().with_hsts(true).wrap_router(inner);

    let req = Request::builder()
        .method(Method::GET)
        .uri("/")
        .body(Body::empty())
        .unwrap();
    let (_, headers, _) = body_string(router.oneshot(req).await.unwrap()).await;
    assert!(headers.get("strict-transport-security").is_some());
}

#[tokio::test]
async fn xss_protection_default_is_disabled() {
    let req = Request::builder()
        .method(Method::GET)
        .uri("/")
        .body(Body::empty())
        .unwrap();
    let (_, headers, _) = body_string(app().oneshot(req).await.unwrap()).await;
    assert_eq!(
        headers.get("x-xss-protection"),
        Some(&HeaderValue::from_static("0")),
        "modern guidance disables the legacy XSS auditor"
    );
}

#[tokio::test]
async fn opt_in_headers_appear_when_configured() {
    let inner = Router::new().route("/", get(|| async { "ok" }));
    let router = SecurityPlugin::with_config(SecurityConfig {
        content_security_policy: Some("default-src 'self'".into()),
        permissions_policy: Some("geolocation=()".into()),
        server_header: Some("umbral".into()),
        ..Default::default()
    })
    .wrap_router(inner);

    let req = Request::builder()
        .method(Method::GET)
        .uri("/")
        .body(Body::empty())
        .unwrap();
    let (_, headers, _) = body_string(router.oneshot(req).await.unwrap()).await;
    assert_eq!(
        headers.get("content-security-policy"),
        Some(&HeaderValue::from_static("default-src 'self'"))
    );
    assert_eq!(
        headers.get("permissions-policy"),
        Some(&HeaderValue::from_static("geolocation=()"))
    );
    assert_eq!(
        headers.get("server"),
        Some(&HeaderValue::from_static("umbral"))
    );
}

#[tokio::test]
async fn server_header_can_be_stripped() {
    let inner = Router::new().route(
        "/",
        get(|| async { ([(http::header::SERVER, "leaky/1.2.3")], "ok") }),
    );
    let router = SecurityPlugin::with_config(SecurityConfig {
        // Default sets `Server: umbral`; to strip, clear it and ask to hide.
        server_header: None,
        hide_server_header: true,
        ..Default::default()
    })
    .wrap_router(inner);

    let req = Request::builder()
        .method(Method::GET)
        .uri("/")
        .body(Body::empty())
        .unwrap();
    let (_, headers, _) = body_string(router.oneshot(req).await.unwrap()).await;
    assert!(
        headers.get("server").is_none(),
        "Server header should be stripped"
    );
}

#[tokio::test]
async fn server_and_coop_headers_are_on_by_default() {
    let req = Request::builder()
        .method(Method::GET)
        .uri("/")
        .body(Body::empty())
        .unwrap();
    let (_, headers, _) = body_string(app().oneshot(req).await.unwrap()).await;
    assert_eq!(
        headers.get("server"),
        Some(&HeaderValue::from_static("umbral")),
        "umbral advertises a Server header by default"
    );
    assert_eq!(
        headers.get("cross-origin-opener-policy"),
        Some(&HeaderValue::from_static("same-origin")),
        "COOP on by default"
    );
}

#[tokio::test]
async fn exempt_path_skips_csrf_on_writes() {
    let inner = Router::new().route("/api/save", post(|| async { "ok-api" }));
    let router = SecurityPlugin::with_config(SecurityConfig {
        csrf_exempt_paths: vec!["/api".into()],
        ..Default::default()
    })
    .wrap_router(inner);

    // A cookieless write (bearer-auth API client) that would 403 under CSRF
    // passes because /api is exempt.
    let req = Request::builder()
        .method(Method::POST)
        .uri("/api/save")
        .body(Body::empty())
        .unwrap();
    let (status, _, body) = body_string(router.oneshot(req).await.unwrap()).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, "ok-api");
}

/// gaps4 #41: `.csrf_exempt([...])` — the chainable shorthand — behaves
/// exactly like the `with_config` struct-update ceremony it replaces, and
/// APPENDS to previously configured exemptions rather than replacing them.
#[tokio::test]
async fn csrf_exempt_shorthand_exempts_and_composes() {
    let inner = Router::new()
        .route("/api/save", post(|| async { "ok-api" }))
        .route("/graphql", post(|| async { "ok-gql" }))
        .route("/form", post(|| async { "never-reached" }));
    let router = SecurityPlugin::with_config(SecurityConfig {
        csrf_exempt_paths: vec!["/api".into()],
        ..Default::default()
    })
    .csrf_exempt(["/graphql"])
    .wrap_router(inner);

    for (path, expected) in [("/api/save", "ok-api"), ("/graphql", "ok-gql")] {
        let req = Request::builder()
            .method(Method::POST)
            .uri(path)
            .body(Body::empty())
            .unwrap();
        let (status, _, body) = body_string(router.clone().oneshot(req).await.unwrap()).await;
        assert_eq!(status, StatusCode::OK, "{path} is exempt");
        assert_eq!(body, expected);
    }

    // A non-exempt cookieless write still trips CSRF — the shorthand
    // widened nothing beyond the named prefixes.
    let req = Request::builder()
        .method(Method::POST)
        .uri("/form")
        .body(Body::empty())
        .unwrap();
    let (status, _, _) = body_string(router.oneshot(req).await.unwrap()).await;
    assert_eq!(
        status,
        StatusCode::FORBIDDEN,
        "non-exempt writes keep CSRF protection"
    );
}

#[tokio::test]
async fn middleware_token_wins_over_handler_minted_cookie() {
    // The middleware is the only mint (docs/decisions/
    // 2026-06-10-automatic-csrf.md): `ensure_csrf_cookie` is gone and a
    // handler that still sets its own CSRF cookie no longer wins. The
    // middleware APPENDS its cookie after the handler's, so the browser
    // (last-wins for same-name cookies) keeps the middleware's token —
    // which is also the ambient token templates render. The two stay
    // consistent without any deference logic; the handler's cookie is
    // appended-around, not clobbered.
    let inner = Router::new().route(
        "/form",
        get(|| async {
            (
                [(
                    SET_COOKIE,
                    "umbral_csrf_token=handler-minted; Path=/; SameSite=Lax",
                )],
                // What `{{ csrf_token }}` would render into the form.
                umbral::templates::current_csrf().unwrap_or_default(),
            )
        }),
    );
    let router = SecurityPlugin::new().wrap_router(inner);
    let req = Request::builder()
        .method(Method::GET)
        .uri("/form")
        .body(Body::empty())
        .unwrap();
    let (_, headers, body) = body_string(router.oneshot(req).await.unwrap()).await;
    let cookies: Vec<&str> = headers
        .get_all(SET_COOKIE)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .collect();
    let last_csrf = cookies
        .iter()
        .filter(|c| c.starts_with("umbral_csrf_token="))
        .next_back()
        .expect("middleware must append its cookie")
        .split(';')
        .next()
        .unwrap()
        .trim_start_matches("umbral_csrf_token=");
    assert_ne!(
        last_csrf, "handler-minted",
        "middleware's token must be the browser-effective (last) cookie"
    );
    assert_eq!(
        body, last_csrf,
        "ambient token rendered into forms must match the effective cookie"
    );
    assert!(
        cookies.iter().any(|c| c.contains("handler-minted")),
        "append must not destroy the handler's header, got: {cookies:?}"
    );
}

#[tokio::test]
async fn request_body_limit_rejects_oversize_body() {
    let inner = Router::new().route("/save", post(|| async { "ok" }));
    let router = SecurityPlugin::with_config(SecurityConfig {
        csrf: false, // isolate the body-limit behaviour from CSRF
        request_body_limit: Some(8),
        ..Default::default()
    })
    .wrap_router(inner);

    let body = "this body is definitely longer than eight bytes";
    let req = Request::builder()
        .method(Method::POST)
        .uri("/save")
        // A declared Content-Length over the cap trips the layer's immediate
        // 413 short-circuit (the realistic path; clients send Content-Length).
        .header(http::header::CONTENT_LENGTH, body.len())
        .body(Body::from(body))
        .unwrap();
    let (status, _, _) = body_string(router.oneshot(req).await.unwrap()).await;
    assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
}

#[tokio::test]
async fn generate_token_is_64_hex_chars_and_unique() {
    let a = generate_token();
    let b = generate_token();
    assert_eq!(a.len(), 64, "32 bytes hex-encoded = 64 chars");
    assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
    assert_ne!(a, b);
}