seshcookie 0.1.0

Stateless, encrypted, type-safe session cookies for Rust web applications.
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
//! Full-stack integration tests for the seshcookie-rs Axum extractor.
//!
//! These tests drive an `axum::Router` directly via `tower::ServiceExt::oneshot`
//! so no real network is involved. The acceptance-criteria identifiers
//! (`seshcookie-rs.AC5.1`-`AC5.5`, `seshcookie-rs.AC9.2`-`AC9.3`) appear in
//! the test names so the AC -> test mapping is traceable.
//!
//! AC9.3 requires the entire test suite to run on a multi-threaded tokio
//! runtime with at least 4 worker threads. Every `#[tokio::test]` annotation
//! in this file uses `flavor = "multi_thread", worker_threads = 4`. The
//! self-auditing test `axum_all_integration_tests_run_on_multi_thread_runtime_seshcookie_rs_ac9_3`
//! reads the file and asserts no bare `#[tokio::test]` annotations remain.
//!
//! Cookies for the AC9.2 100-concurrent-request test are constructed via
//! `seshcookie::__testing::encode_cookie_for_layer`, an explicitly
//! `#[doc(hidden)]` helper that lets integration tests build cookie values
//! without re-implementing the AEAD pipeline. The helper is not part of the
//! public API contract.

use std::sync::Arc;
use std::time::SystemTime;

use axum::{
    Router,
    body::Body,
    routing::{get, post},
};
use http::{Request, StatusCode, header::SET_COOKIE};
use http_body_util::BodyExt;
use serde::{Deserialize, Serialize};
use seshcookie::{Session, SessionConfig, SessionKeys, SessionLayer};
use tokio::sync::Mutex;
use tower::ServiceExt;

/// Primary session payload used across the suite. Mirrors the shape an
/// application would store: a numeric user id plus a textual role.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct AppSession {
    user_id: u64,
    role: String,
}

/// Secondary session payload used by the AC5.2 two-layers test. A distinct
/// type plus a distinct cookie name lets two `SessionLayer`s coexist on the
/// same router.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct AppSessionB {
    page: u32,
}

fn build_keys() -> SessionKeys {
    SessionKeys::new(b"fedcba9876543210fedcba9876543210").expect("32-byte key is valid")
}

fn build_layer() -> SessionLayer<AppSession> {
    // `secure(false)` lets the test request reach the handler over plain HTTP
    // (not strictly required when using oneshot, but matches the example's
    // posture). The default 24h max_age means the AC9.2 cookies stay valid
    // for the duration of the test.
    let config = SessionConfig::default().secure(false);
    SessionLayer::<AppSession>::new(build_keys(), config).expect("layer construction succeeds")
}

fn build_app() -> Router {
    Router::new()
        .route("/insert", post(insert_handler))
        .route("/get", get(get_handler))
        .route("/optional", get(optional_handler))
        .route("/required", get(required_handler))
        .route("/two-handles", get(two_handles_handler))
        .layer(build_layer())
}

async fn insert_handler(session: Session<AppSession>) -> &'static str {
    session
        .insert(AppSession {
            user_id: 1,
            role: "admin".into(),
        })
        .await;
    "inserted"
}

async fn get_handler(session: Session<AppSession>) -> String {
    match session.get().await {
        Some(s) => format!("{}:{}", s.user_id, s.role),
        None => "none".into(),
    }
}

async fn optional_handler(session: Option<Session<AppSession>>) -> &'static str {
    if session.is_some() { "some" } else { "none" }
}

async fn required_handler(_session: Session<AppSession>) -> &'static str {
    "required-ok"
}

async fn two_handles_handler(s1: Session<AppSession>, s2: Session<AppSession>) -> String {
    s1.insert(AppSession {
        user_id: 99,
        role: "q".into(),
    })
    .await;
    let seen = s2.get().await.expect("s2 must observe s1's insert");
    format!("{}:{}", seen.user_id, seen.role)
}

/// Read a response body to a `String` for assertions. Integration tests use
/// `String` rather than `Bytes` because every response in this suite is
/// plain UTF-8 text.
async fn body_text(response: http::Response<Body>) -> String {
    let bytes = response
        .into_body()
        .collect()
        .await
        .expect("collecting an in-memory body never fails")
        .to_bytes();
    String::from_utf8(bytes.to_vec()).expect("test handlers all produce UTF-8")
}

/// Extract the first `Set-Cookie` header value from a response. The
/// integration tests target single-cookie responses; if that ever changes,
/// update callers to be explicit about which cookie they want.
fn first_set_cookie(response: &http::Response<Body>) -> String {
    response
        .headers()
        .get(SET_COOKIE)
        .expect("response carries a Set-Cookie header")
        .to_str()
        .expect("Set-Cookie value is ASCII")
        .to_string()
}

/// Extract the `name=value` portion of a `Set-Cookie` header. The remainder
/// (Path, HttpOnly, ...) is dropped — only the name=value pair is sent on
/// subsequent requests.
fn cookie_name_value(set_cookie: &str) -> String {
    set_cookie
        .split(';')
        .next()
        .expect("Set-Cookie always has at least name=value")
        .to_string()
}

// --- AC5.4: handler without layer returns HTTP 500 -------------------------

/// seshcookie-rs.AC5.4: a required `Session<T>` extractor on a handler that
/// has no `SessionLayer<T>` mounted produces an HTTP 500 with a body that
/// describes the misconfiguration. The router has no layer at all, so the
/// extension lookup misses and the rejection's `IntoResponse` runs.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn axum_handler_without_layer_returns_http_500_seshcookie_rs_ac5_4() {
    let app: Router = Router::new().route("/required", get(required_handler));

    let req = Request::builder()
        .method("GET")
        .uri("/required")
        .body(Body::empty())
        .expect("test request is well-formed");

    let response = app.oneshot(req).await.expect("oneshot delivers a response");

    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);

    let body = body_text(response).await;
    assert!(
        body.contains("not mounted"),
        "AC5.4 response body must mention the missing layer; got {body:?}"
    );
}

// --- AC5.1: required extractor succeeds, payload round-trips --------------

/// seshcookie-rs.AC5.1: with `SessionLayer<T>` mounted, the handler's
/// required `Session<T>` extractor produces a working handle. A POST to
/// `/insert` writes a payload and emits a `Set-Cookie`. A second GET to
/// `/get` carrying that cookie observes the inserted payload.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn axum_handler_with_layer_extracts_successfully_seshcookie_rs_ac5_1() {
    let app = build_app();

    let req = Request::builder()
        .method("POST")
        .uri("/insert")
        .body(Body::empty())
        .expect("test request is well-formed");
    let response = app.clone().oneshot(req).await.expect("first call succeeds");
    assert_eq!(response.status(), StatusCode::OK);

    let set_cookie = first_set_cookie(&response);
    let cookie_pair = cookie_name_value(&set_cookie);

    let body = body_text(response).await;
    assert_eq!(body, "inserted");

    let req = Request::builder()
        .method("GET")
        .uri("/get")
        .header(http::header::COOKIE, &cookie_pair)
        .body(Body::empty())
        .expect("test request is well-formed");
    let response = app.oneshot(req).await.expect("second call succeeds");
    assert_eq!(response.status(), StatusCode::OK);

    let body = body_text(response).await;
    assert_eq!(
        body, "1:admin",
        "the cookie round-trips the inserted payload"
    );
}

// --- AC5.3: optional extractor returns None on missing layer --------------

/// seshcookie-rs.AC5.3: a handler declaring `Option<Session<T>>` on a router
/// without the matching layer sees `None` rather than producing an HTTP
/// rejection. The handler responds 200 with the literal `"none"`.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn axum_handler_with_option_extractor_gets_none_when_layer_missing_seshcookie_rs_ac5_3() {
    let app: Router = Router::new().route("/optional", get(optional_handler));

    let req = Request::builder()
        .method("GET")
        .uri("/optional")
        .body(Body::empty())
        .expect("test request is well-formed");
    let response = app.oneshot(req).await.expect("oneshot delivers a response");

    assert_eq!(response.status(), StatusCode::OK);
    let body = body_text(response).await;
    assert_eq!(body, "none");
}

/// seshcookie-rs.AC5.3 (companion): with the layer mounted, the optional
/// extractor yields `Some(_)` even when the request carries no cookie. The
/// layer always installs an empty session handle in extensions; only the
/// payload is `None` in that case, not the handle itself.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn axum_handler_with_option_extractor_gets_some_when_layer_present_seshcookie_rs_ac5_3() {
    let app = build_app();

    let req = Request::builder()
        .method("GET")
        .uri("/optional")
        .body(Body::empty())
        .expect("test request is well-formed");
    let response = app.oneshot(req).await.expect("oneshot delivers a response");

    assert_eq!(response.status(), StatusCode::OK);
    let body = body_text(response).await;
    assert_eq!(body, "some");
}

// --- AC5.5: two extractor handles share state inside one request ----------

/// seshcookie-rs.AC5.5: a handler that extracts `Session<T>` twice receives
/// two handles that share underlying state. A mutation through one is
/// visible through the other inside the same request.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn axum_two_handles_share_underlying_state_seshcookie_rs_ac5_5() {
    let app = build_app();

    let req = Request::builder()
        .method("GET")
        .uri("/two-handles")
        .body(Body::empty())
        .expect("test request is well-formed");
    let response = app.oneshot(req).await.expect("oneshot delivers a response");

    assert_eq!(response.status(), StatusCode::OK);
    let body = body_text(response).await;
    assert_eq!(body, "99:q", "AC5.5 demands the two handles share state");
}

// --- AC5.2: two layers with distinct payload types coexist -----------------

async fn insert_a_handler(session: Session<AppSession>) -> &'static str {
    session
        .insert(AppSession {
            user_id: 7,
            role: "alpha".into(),
        })
        .await;
    "a"
}

async fn insert_b_handler(session: Session<AppSessionB>) -> &'static str {
    session.insert(AppSessionB { page: 42 }).await;
    "b"
}

async fn read_a_handler(session: Session<AppSession>) -> String {
    match session.get().await {
        Some(s) => format!("{}:{}", s.user_id, s.role),
        None => "none".into(),
    }
}

async fn read_b_handler(session: Session<AppSessionB>) -> String {
    match session.get().await {
        Some(s) => format!("page={}", s.page),
        None => "none".into(),
    }
}

fn build_two_layer_app() -> Router {
    let config_a = SessionConfig::default()
        .secure(false)
        .cookie_name("session_a");
    let config_b = SessionConfig::default()
        .secure(false)
        .cookie_name("session_b");
    let layer_a = SessionLayer::<AppSession>::new(build_keys(), config_a).expect("layer A");
    let layer_b = SessionLayer::<AppSessionB>::new(build_keys(), config_b).expect("layer B");

    Router::new()
        .route("/insert-a", post(insert_a_handler))
        .route("/insert-b", post(insert_b_handler))
        .route("/read-a", get(read_a_handler))
        .route("/read-b", get(read_b_handler))
        .layer(layer_a)
        .layer(layer_b)
}

/// seshcookie-rs.AC5.2: two `SessionLayer`s with distinct payload types `A`
/// and `B`, distinct cookie names (`session_a` and `session_b`), and the
/// same key material coexist on one router. Each handler sees its own
/// typed payload — no crossover.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn axum_two_layers_with_distinct_types_coexist_seshcookie_rs_ac5_2() {
    let app = build_two_layer_app();

    // Insert into layer A.
    let req = Request::builder()
        .method("POST")
        .uri("/insert-a")
        .body(Body::empty())
        .expect("test request is well-formed");
    let response_a = app
        .clone()
        .oneshot(req)
        .await
        .expect("insert-a delivers a response");
    assert_eq!(response_a.status(), StatusCode::OK);
    let cookie_a = cookie_name_value(&first_set_cookie(&response_a));
    assert!(
        cookie_a.starts_with("session_a="),
        "layer A must emit a cookie under its configured name; got {cookie_a:?}"
    );

    // Insert into layer B.
    let req = Request::builder()
        .method("POST")
        .uri("/insert-b")
        .body(Body::empty())
        .expect("test request is well-formed");
    let response_b = app
        .clone()
        .oneshot(req)
        .await
        .expect("insert-b delivers a response");
    assert_eq!(response_b.status(), StatusCode::OK);
    let cookie_b = cookie_name_value(&first_set_cookie(&response_b));
    assert!(
        cookie_b.starts_with("session_b="),
        "layer B must emit a cookie under its configured name; got {cookie_b:?}"
    );

    // Both cookies on the third request: each handler decodes its own.
    let cookie_header = format!("{cookie_a}; {cookie_b}");

    let req = Request::builder()
        .method("GET")
        .uri("/read-a")
        .header(http::header::COOKIE, &cookie_header)
        .body(Body::empty())
        .expect("test request is well-formed");
    let response = app
        .clone()
        .oneshot(req)
        .await
        .expect("read-a delivers a response");
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(body_text(response).await, "7:alpha");

    let req = Request::builder()
        .method("GET")
        .uri("/read-b")
        .header(http::header::COOKIE, &cookie_header)
        .body(Body::empty())
        .expect("test request is well-formed");
    let response = app.oneshot(req).await.expect("read-b delivers a response");
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(body_text(response).await, "page=42");
}

// --- AC9.2 / AC9.3: 100 concurrent requests on multi-thread runtime -------

/// seshcookie-rs.AC9.2: 100 concurrent requests, each carrying a distinct
/// pre-encoded cookie, complete with the correct per-request payload. No
/// cross-request state bleed and no deadlock.
///
/// seshcookie-rs.AC9.3: this test runs on a multi-threaded tokio runtime
/// with 4 worker threads (matching every other test in the file). A
/// single-threaded runtime would mask `!Send` bugs; the multi-thread
/// flavor catches them at runtime.
///
/// Cookies are produced by the `__testing::encode_cookie_for_layer`
/// helper rather than the public POST/extract-cookie dance because the
/// dance would serialize 100 round-trips and ruin the concurrency test.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn axum_100_concurrent_requests_multi_thread_runtime_seshcookie_rs_ac9_2_ac9_3() {
    let layer = build_layer();
    let app: Router = Router::new()
        .route("/get", get(get_handler))
        .layer(layer.clone());

    // Pre-compute one cookie per request so nothing in the per-task
    // critical path touches the OS RNG (the test stays focused on
    // request dispatch concurrency, not RNG contention).
    let now = SystemTime::now();
    let cookies: Vec<(u64, String)> = (0..100u64)
        .map(|i| {
            let payload = AppSession {
                user_id: i,
                role: format!("role-{i}"),
            };
            let cookie = seshcookie::__testing::encode_cookie_for_layer(&layer, &payload, now);
            (i, cookie)
        })
        .collect();

    let mut handles = Vec::with_capacity(cookies.len());
    for (id, cookie_value) in cookies {
        let app = app.clone();
        handles.push(tokio::spawn(async move {
            let req = Request::builder()
                .method("GET")
                .uri("/get")
                .header(http::header::COOKIE, format!("session={cookie_value}"))
                .body(Body::empty())
                .expect("test request is well-formed");
            let response = app.oneshot(req).await.expect("oneshot delivers a response");
            assert_eq!(
                response.status(),
                StatusCode::OK,
                "all 100 requests must succeed"
            );
            let body = body_text(response).await;
            (id, body)
        }));
    }

    for handle in handles {
        let (id, body) = handle.await.expect("task did not panic");
        let expected = format!("{id}:role-{id}");
        assert_eq!(
            body, expected,
            "request {id} must observe its own cookie's payload, no cross-request bleed"
        );
    }
}

/// seshcookie-rs.AC9.3 (self-audit): every `#[tokio::test]` annotation in
/// this file uses `flavor = "multi_thread", worker_threads = 4`. A bare
/// `#[tokio::test]` would silently slip onto a single-threaded runtime
/// and mask `!Send` regressions. This test reads the source file and
/// asserts no bare annotation remains.
///
/// The self-audit only inspects lines that *start with* the attribute
/// (after leading whitespace). Mentions of the attribute name inside
/// doc-comments or string literals — necessary to describe this very
/// rule — are skipped on purpose; an actual `#[tokio::test]` attribute
/// always sits at column 0 of its line in idiomatic Rust.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn axum_all_integration_tests_run_on_multi_thread_runtime_seshcookie_rs_ac9_3() {
    let source = std::fs::read_to_string(file!())
        .expect("test binary can read its own source file at test time");

    let mut total_attrs = 0usize;
    let mut bare_count = 0usize;
    for line in source.lines() {
        let trimmed = line.trim_start();
        // Real attribute uses start at column 0 (leading whitespace tolerated)
        // with the literal `#[tokio::test`. Doc comments (`//!` or `///`)
        // and inline references inside string literals start with other
        // characters and are filtered out here.
        if !trimmed.starts_with("#[tokio::test") {
            continue;
        }
        total_attrs += 1;
        // Anything that is not `#[tokio::test(...)]` counts as bare.
        let after = &trimmed["#[tokio::test".len()..];
        if !after.starts_with('(') {
            bare_count += 1;
        }
    }

    assert!(
        total_attrs > 0,
        "AC9.3 self-audit must observe at least one #[tokio::test] attribute; \
         found {total_attrs} (the regex above is broken if this fires)"
    );
    assert_eq!(
        bare_count, 0,
        "AC9.3: every #[tokio::test] in tests/axum_integration.rs must use \
         flavor = \"multi_thread\", worker_threads = 4 — found {bare_count} bare attribute(s)"
    );
}

// --- Compile-time anchor: the integration suite uses tokio::sync::Mutex ---

/// Anchor an `Arc<tokio::sync::Mutex<_>>` reference at compile time so this
/// test file documents (and a future migration would have to actively
/// remove) the project's async-discipline rule. Production code in
/// `src/extract.rs` already enforces this; the integration suite carries
/// the same constraint by using the same primitive.
#[allow(dead_code)]
fn _async_discipline_anchor() -> Arc<Mutex<u8>> {
    Arc::new(Mutex::new(0))
}