autumn-admin-plugin 0.5.0

Out-of-the-box admin panel plugin for autumn-web applications
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
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
//! Role-check and step-up middleware for the admin router.
//!
//! Wraps the nested admin router with `from_fn` layers that inspect the
//! request's [`Session`] and short-circuit with appropriate error responses
//! when authentication or freshness requirements are not met.

use autumn_web::AutumnError;
use autumn_web::session::Session;
use autumn_web::step_up;
use axum::extract::Request;
use axum::http::{Method, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Redirect, Response};

/// Produce an axum middleware that verifies the incoming request has a
/// logged-in session with the given role.
///
/// Returns 401 if `auth_session_key` is absent from the session, 403 if
/// the role doesn't match. The session key matches Autumn's
/// `auth.session_key` config (default `"user_id"`); deployments that
/// changed it (e.g. to `"uid"`) must pass the same string here via
/// [`crate::AdminPlugin::auth_session_key`].
///
/// Errors are produced via `AutumnError::*_msg` so the framework's
/// error-page filter renders them as branded HTML for browser clients
/// and JSON for API clients.
pub async fn check_role(
    role: String,
    auth_session_key: String,
    req: Request,
    next: Next,
) -> Response {
    let Some(session) = req.extensions().get::<Session>().cloned() else {
        return AutumnError::internal_server_error_msg(
            "SessionLayer not installed; admin plugin requires sessions",
        )
        .into_response();
    };

    if session.get(&auth_session_key).await.is_none() {
        return AutumnError::unauthorized_msg("authentication required").into_response();
    }
    let current = session.get("role").await.unwrap_or_default();
    if current != role {
        return AutumnError::forbidden_msg(format!("'{role}' role required")).into_response();
    }
    next.run(req).await
}

/// Middleware that requires step-up (fresh) authentication for mutating
/// HTTP methods (POST, PUT, PATCH, DELETE).
///
/// When the session's `last_strong_auth_at` claim is missing or stale:
/// - Browser clients are redirected to `/reauth?return_to=<path>`.
/// - JSON/API clients receive a `401` with `WWW-Authenticate: StepUp`.
///
/// GET requests are passed through unconditionally.
///
/// `max_age_secs` is the freshness window configured at admin plugin build
/// time via [`AdminPlugin::with_step_up_mutations`] or
/// [`AdminPlugin::with_step_up_max_age`]. It is captured in the closure
/// registered in `routes::admin_router` and passed directly here so this
/// function does not need access to `AppState` at request time.
///
/// **Known limitation**: this middleware calls `check_step_up` directly and
/// therefore does **not** emit `auth.step_up.success` / `auth.step_up.failure`
/// audit events. `AppState` (needed to resolve the `AuditLogger`) is not
/// available to `from_fn` middleware — that would require `from_fn_with_state`,
/// which needs the state value at layer-registration time, before the framework
/// finalises `AppState`. Route-level `#[step_up]` attributes do emit full audit
/// events via `__check_step_up_with_config`.
pub async fn check_step_up_mutations(max_age_secs: u64, req: Request, next: Next) -> Response {
    // Only guard mutating methods.
    if !matches!(
        req.method(),
        &Method::POST | &Method::PUT | &Method::PATCH | &Method::DELETE
    ) {
        return next.run(req).await;
    }

    let Some(session) = req.extensions().get::<Session>().cloned() else {
        return AutumnError::internal_server_error_msg(
            "SessionLayer not installed; admin step-up requires sessions",
        )
        .into_response();
    };

    if step_up::check_step_up(&session, max_age_secs)
        .await
        .is_err()
    {
        // Detect JSON clients via Accept header.
        let wants_json = req
            .headers()
            .get(header::ACCEPT)
            .and_then(|v| v.to_str().ok())
            .is_some_and(|s| s.contains("application/json"));

        if wants_json {
            return step_up::__step_up_json_response(max_age_secs);
        }

        // For mutating requests, prefer the Referer (the page with the action
        // button) over the current URI so that after reauth the user lands back
        // on a GET page — not a POST/DELETE-only endpoint with no GET handler.
        let path = req
            .headers()
            .get(header::REFERER)
            .and_then(|v| v.to_str().ok())
            .and_then(step_up::referer_path)
            .unwrap_or_else(|| {
                req.uri()
                    .path_and_query()
                    .map_or_else(|| req.uri().path(), axum::http::uri::PathAndQuery::as_str)
                    .to_owned()
            });
        let encoded = step_up::encode_return_to(&path);
        return Redirect::to(&format!("/reauth?return_to={encoded}")).into_response();
    }

    next.run(req).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use autumn_web::session::Session;
    use axum::Router;
    use axum::body::Body;
    use axum::http::StatusCode;
    use axum::middleware::from_fn;
    use axum::routing::get;
    use std::collections::HashMap;
    use tower::ServiceExt;

    fn app_with_role_gate(session: Session) -> Router {
        app_with_role_gate_and_key(session, "user_id")
    }

    fn app_with_role_gate_and_key(session: Session, auth_session_key: &'static str) -> Router {
        async fn ok() -> &'static str {
            "ok"
        }
        let role = "admin".to_owned();
        let key = auth_session_key.to_owned();
        Router::new()
            .route("/", get(ok))
            .layer(from_fn(move |mut req: Request, next: Next| {
                let session = session.clone();
                let role = role.clone();
                let key = key.clone();
                async move {
                    req.extensions_mut().insert(session);
                    check_role(role, key, req, next).await
                }
            }))
    }

    #[tokio::test]
    async fn no_session_returns_401() {
        let session = Session::new_for_test("sid".into(), HashMap::new());
        let app = app_with_role_gate(session);
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn wrong_role_returns_403() {
        let session = Session::new_for_test(
            "sid".into(),
            HashMap::from([
                ("user_id".into(), "1".into()),
                ("role".into(), "viewer".into()),
            ]),
        );
        let app = app_with_role_gate(session);
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn correct_role_passes_through() {
        let session = Session::new_for_test(
            "sid".into(),
            HashMap::from([
                ("user_id".into(), "1".into()),
                ("role".into(), "admin".into()),
            ]),
        );
        let app = app_with_role_gate(session);
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn custom_auth_session_key_is_honored() {
        // Deployment configured `auth.session_key = "uid"`. A session with
        // "uid" populated must authenticate; a session with only the
        // default "user_id" must NOT (because the deployment's auth
        // pipeline never writes "user_id").
        let with_uid = Session::new_for_test(
            "sid".into(),
            HashMap::from([("uid".into(), "42".into()), ("role".into(), "admin".into())]),
        );
        let app = app_with_role_gate_and_key(with_uid, "uid");
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            res.status(),
            StatusCode::OK,
            "uid-keyed session should pass"
        );

        // Inverse: only the default "user_id" present, but the deployment
        // is configured for "uid" — must reject as unauthenticated.
        let with_user_id = Session::new_for_test(
            "sid".into(),
            HashMap::from([
                ("user_id".into(), "42".into()),
                ("role".into(), "admin".into()),
            ]),
        );
        let app = app_with_role_gate_and_key(with_user_id, "uid");
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            res.status(),
            StatusCode::UNAUTHORIZED,
            "wrong-key session must NOT authenticate"
        );
    }

    #[tokio::test]
    async fn missing_session_extension_returns_500() {
        async fn ok() -> &'static str {
            "ok"
        }
        let role = "admin".to_owned();
        let key = "user_id".to_owned();
        let app =
            Router::new()
                .route("/", get(ok))
                .layer(from_fn(move |req: Request, next: Next| {
                    let role = role.clone();
                    let key = key.clone();
                    async move { check_role(role, key, req, next).await }
                }));
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    // ── check_step_up_mutations ───────────────────────────────────────────────

    fn step_up_app(session: Session) -> Router {
        step_up_app_with_max_age(session, autumn_web::step_up::DEFAULT_MAX_AGE_SECS)
    }

    fn step_up_app_with_max_age(session: Session, max_age_secs: u64) -> Router {
        async fn ok() -> &'static str {
            "ok"
        }
        Router::new()
            .route("/resource", get(ok).post(ok).delete(ok))
            .layer(from_fn(move |mut req: Request, next: Next| {
                let session = session.clone();
                async move {
                    req.extensions_mut().insert(session);
                    check_step_up_mutations(max_age_secs, req, next).await
                }
            }))
    }

    #[tokio::test]
    async fn step_up_allows_get_without_claim() {
        let session = Session::new_for_test("sid".into(), HashMap::new());
        let app = step_up_app(session);
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .method("GET")
                    .uri("/resource")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            res.status(),
            StatusCode::OK,
            "GET should pass without step-up"
        );
    }

    #[tokio::test]
    async fn step_up_blocks_post_without_claim_html_client() {
        let session = Session::new_for_test("sid".into(), HashMap::new());
        let app = step_up_app(session);
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .method("POST")
                    .uri("/resource")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        // HTML clients get a redirect (302/303)
        assert!(
            res.status().is_redirection(),
            "POST without step-up should redirect HTML client: {}",
            res.status()
        );
        let location = res.headers().get("location").unwrap().to_str().unwrap();
        assert!(
            location.contains("/reauth"),
            "redirect should go to /reauth: {location}"
        );
    }

    #[tokio::test]
    async fn step_up_blocks_post_without_claim_json_client() {
        let session = Session::new_for_test("sid".into(), HashMap::new());
        let app = step_up_app(session);
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .method("POST")
                    .uri("/resource")
                    .header("Accept", "application/json")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            res.status(),
            StatusCode::UNAUTHORIZED,
            "JSON POST without step-up should return 401"
        );
        let www_auth = res
            .headers()
            .get("www-authenticate")
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            www_auth.contains("StepUp"),
            "should include WWW-Authenticate: StepUp header: {www_auth}"
        );
    }

    #[tokio::test]
    async fn step_up_allows_post_with_fresh_claim() {
        use autumn_web::step_up::STEP_UP_SESSION_KEY;
        let now_ts = chrono::Utc::now().timestamp().to_string();
        let session = Session::new_for_test(
            "sid".into(),
            HashMap::from([(STEP_UP_SESSION_KEY.to_string(), now_ts)]),
        );
        let app = step_up_app(session);
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .method("POST")
                    .uri("/resource")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            res.status(),
            StatusCode::OK,
            "POST with fresh step-up claim should pass"
        );
    }

    #[tokio::test]
    async fn step_up_blocks_delete_without_claim() {
        let session = Session::new_for_test("sid".into(), HashMap::new());
        let app = step_up_app(session);
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .method("DELETE")
                    .uri("/resource")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert!(
            res.status().is_redirection(),
            "DELETE without step-up should redirect: {}",
            res.status()
        );
    }

    #[tokio::test]
    async fn step_up_uses_referer_as_return_to_for_post() {
        let session = Session::new_for_test("sid".into(), HashMap::new());
        let app = step_up_app(session);
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .method("POST")
                    .uri("/resource")
                    .header("Referer", "https://example.com/admin/users")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert!(res.status().is_redirection(), "should redirect");
        let location = res.headers().get("location").unwrap().to_str().unwrap();
        assert!(
            location.contains("/admin/users"),
            "return_to should use Referer path, not POST URI: {location}"
        );
    }

    #[tokio::test]
    async fn step_up_custom_max_age_is_honored() {
        use autumn_web::step_up::STEP_UP_SESSION_KEY;
        // Claim set 10 seconds ago — within the default 5-min window but outside
        // a tighter 5-second window. Verifies that the captured max_age_secs is
        // actually used rather than a hard-coded constant.
        let stale_ts = (chrono::Utc::now() - chrono::Duration::seconds(10))
            .timestamp()
            .to_string();
        let session = Session::new_for_test(
            "sid".into(),
            HashMap::from([(STEP_UP_SESSION_KEY.to_string(), stale_ts)]),
        );
        let app = step_up_app_with_max_age(session, 5);
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .method("POST")
                    .uri("/resource")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert!(
            res.status().is_redirection(),
            "10-second-old claim should be blocked by max_age=5s"
        );
    }
}