autumn-web 0.2.0

An opinionated, convention-over-configuration web framework for Rust
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
//! Authentication utilities for Autumn applications.
//!
//! Provides password hashing, an [`Auth<T>`] extractor for retrieving the
//! authenticated user, and a [`RequireAuth`] middleware layer for protecting
//! routes.
//!
//! ## Quick start
//!
//! ```rust,no_run
//! use autumn_web::prelude::*;
//! use autumn_web::auth::{Auth, hash_password, verify_password};
//! use autumn_web::session::Session;
//!
//! #[derive(Clone)]
//! struct User { id: i64, name: String }
//!
//! #[post("/register")]
//! async fn register() -> AutumnResult<&'static str> {
//!     let hashed = hash_password("secret123").await?;
//!     // Save hashed password to database...
//!     Ok("registered")
//! }
//!
//! #[post("/login")]
//! async fn login(session: Session) -> AutumnResult<&'static str> {
//!     // Verify credentials...
//!     let stored_hash = "$2b$12$..."; // from database
//!     if verify_password("secret123", stored_hash).await? {
//!         session.insert("user_id", "42").await;
//!         Ok("logged in")
//!     } else {
//!         Err(AutumnError::bad_request_msg("invalid credentials"))
//!     }
//! }
//! ```
//!
//! ## Password hashing
//!
//! Uses bcrypt with a default cost of 12. The [`hash_password`] and
//! [`verify_password`] functions are simple wrappers that return
//! [`AutumnResult`](crate::AutumnResult).
//!
//! ## The `Auth<T>` extractor
//!
//! [`Auth<T>`] extracts the authenticated user from request extensions.
//! It is typically populated by a custom middleware which might call
//! `request.extensions_mut().insert(user)` in a handler. Returns `401 Unauthorized` if no
//! user is present.
//!
//! ## Route protection with `RequireAuth`
//!
//! The [`RequireAuth`] layer rejects unauthenticated requests with
//! `401 Unauthorized` before they reach the handler. It checks for the
//! presence of a session key (default: `"user_id"`).

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use axum::extract::FromRequestParts;
use axum::response::{IntoResponse, Response};
use http::StatusCode;
use http::request::Parts;

// ── Password hashing ────────────────────────────────────────────

/// Default bcrypt cost factor.
const DEFAULT_BCRYPT_COST: u32 = 12;

/// Hash a plaintext password using bcrypt.
///
/// Returns the hashed password string suitable for database storage.
///
/// # Errors
///
/// Returns an error if bcrypt hashing fails (extremely unlikely).
///
/// # Examples
///
/// ```rust
/// use autumn_web::auth::hash_password;
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let hashed = hash_password("my_secret").await.unwrap();
/// assert!(hashed.starts_with("$2b$"));
/// # });
/// ```
pub async fn hash_password(password: &str) -> crate::AutumnResult<String> {
    let password = password.to_string();
    tokio::task::spawn_blocking(move || {
        bcrypt::hash(password, DEFAULT_BCRYPT_COST)
            .map_err(|e| crate::AutumnError::from(std::io::Error::other(e.to_string())))
    })
    .await
    .map_err(|e| crate::AutumnError::from(std::io::Error::other(e.to_string())))?
}

/// Verify a plaintext password against a bcrypt hash.
///
/// Returns `true` if the password matches the hash.
///
/// # Errors
///
/// Returns an error if bcrypt verification fails (e.g., invalid hash format).
///
/// # Examples
///
/// ```rust
/// use autumn_web::auth::{hash_password, verify_password};
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let hashed = hash_password("my_secret").await.unwrap();
/// assert!(verify_password("my_secret", &hashed).await.unwrap());
/// assert!(!verify_password("wrong_password", &hashed).await.unwrap());
/// # });
/// ```
pub async fn verify_password(password: &str, hash: &str) -> crate::AutumnResult<bool> {
    let password = password.to_string();

    // Parse the hash format outside the blocking task.
    // A valid bcrypt hash is typically 60 characters and starts with "$".
    let is_valid_format = hash.len() == 60 && hash.starts_with('$');

    let hash_to_verify = if is_valid_format {
        hash.to_string()
    } else {
        // To prevent timing attacks, perform a dummy verification against a known hash.
        "$2b$12$KIXe8K4j1sH6/xH.x9d71uJ5Jk8t6O4m6Q110g4H8y1r6J6O6O6O6".to_string()
    };

    let result = tokio::task::spawn_blocking(move || bcrypt::verify(&password, &hash_to_verify))
        .await
        .map_err(|e| crate::AutumnError::from(std::io::Error::other(e.to_string())))?;

    if !is_valid_format {
        return Ok(false);
    }

    result.map_err(|e| crate::AutumnError::from(std::io::Error::other(e.to_string())))
}

// ── Runtime check for #[secured] macro ──────────────────────────

/// Runtime authentication and authorization check used by the
/// `#[secured]` proc macro. **Not intended for direct use** -- use
/// `#[secured]` instead.
///
/// Checks the session for the configured auth key (default: `"user_id"`).
/// If `roles` is non-empty, also checks that the session's `"role"` value
/// matches at least one of the given roles.
///
/// Returns `401 Unauthorized` if not authenticated, or `403 Forbidden`
/// if the user lacks the required role.
#[doc(hidden)]
pub async fn __check_secured(
    session: &crate::session::Session,
    roles: &[&str],
) -> crate::AutumnResult<()> {
    // Check authentication: session must contain the auth key
    if session.get("user_id").await.is_none() {
        return Err(crate::AutumnError::unauthorized_msg(
            "authentication required",
        ));
    }

    // Check authorization: if roles are specified, the session's "role"
    // must match at least one of them
    if !roles.is_empty() {
        let user_role = session.get("role").await.unwrap_or_default();
        if !roles.iter().any(|&r| r == user_role) {
            return Err(crate::AutumnError::forbidden_msg(
                "insufficient permissions",
            ));
        }
    }

    Ok(())
}

// ── Auth<T> extractor ───────────────────────────────────────────

/// Extractor that retrieves the authenticated user from request extensions.
///
/// Handlers can declare `Auth<MyUser>` as a parameter to access the
/// current user. If no user is present in the request extensions,
/// a `401 Unauthorized` response is returned automatically.
///
/// ## Populating the user
///
/// The user is typically inserted into request extensions by middleware.
/// For example, a custom middleware can load the user from the session
/// and call `request.extensions_mut().insert(user)`.
///
/// ## Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
/// use autumn_web::auth::Auth;
///
/// #[derive(Clone)]
/// struct CurrentUser { id: i64, name: String }
///
/// #[get("/profile")]
/// async fn profile(Auth(user): Auth<CurrentUser>) -> String {
///     format!("Hello, {}!", user.name)
/// }
/// ```
pub struct Auth<T>(pub T);

impl<T, S> FromRequestParts<S> for Auth<T>
where
    T: Clone + Send + Sync + 'static,
    S: Send + Sync,
{
    type Rejection = AuthRejection;

    fn from_request_parts(
        parts: &mut Parts,
        _state: &S,
    ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
        let user = parts.extensions.get::<T>().cloned();
        async move { user.map_or_else(|| Err(AuthRejection), |user| Ok(Self(user))) }
    }
}

/// Rejection type for [`Auth<T>`] when no authenticated user is present.
#[derive(Debug)]
pub struct AuthRejection;

impl IntoResponse for AuthRejection {
    fn into_response(self) -> Response {
        (
            StatusCode::UNAUTHORIZED,
            axum::Json(serde_json::json!({
                "error": {
                    "status": 401,
                    "message": "authentication required"
                }
            })),
        )
            .into_response()
    }
}

impl std::fmt::Display for AuthRejection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("authentication required")
    }
}

// ── RequireAuth middleware ───────────────────────────────────────

/// Tower [`tower::Layer`] that rejects unauthenticated requests with `401`.
///
/// Checks for a specific key in the session to determine if the request
/// is authenticated. If the key is missing, the request is rejected before
/// reaching the handler.
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::auth::RequireAuth;
/// use autumn_web::reexports::axum::{Router, routing::get};
/// use autumn_web::AppState;
///
/// // Protect all routes under /admin
/// let admin_routes = Router::<AppState>::new()
///     .route("/dashboard", get(|| async { "admin" }))
///     .layer(RequireAuth::new("user_id"));
/// ```
#[derive(Clone)]
pub struct RequireAuth {
    session_key: Arc<str>,
}

impl RequireAuth {
    /// Create a new `RequireAuth` layer that checks for the given session key.
    pub fn new(session_key: impl Into<String>) -> Self {
        Self {
            session_key: Arc::from(session_key.into()),
        }
    }
}

impl<S> tower::Layer<S> for RequireAuth {
    type Service = RequireAuthService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        RequireAuthService {
            inner,
            session_key: Arc::clone(&self.session_key),
        }
    }
}

/// Tower [`tower::Service`] produced by [`RequireAuth`].
#[derive(Clone)]
pub struct RequireAuthService<S> {
    inner: S,
    session_key: Arc<str>,
}

impl<S, ResBody> tower::Service<axum::extract::Request> for RequireAuthService<S>
where
    S: tower::Service<axum::extract::Request, Response = Response<ResBody>>
        + Clone
        + Send
        + 'static,
    S::Future: Send + 'static,
    S::Error: Send + 'static,
    ResBody: From<String> + Default + Send + 'static,
{
    type Response = Response<ResBody>;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: axum::extract::Request) -> Self::Future {
        let session_key = Arc::clone(&self.session_key);
        let mut inner = self.inner.clone();
        std::mem::swap(&mut self.inner, &mut inner);

        Box::pin(async move {
            // Check if session has the required key
            let session = req.extensions().get::<crate::session::Session>().cloned();

            let is_authenticated = if let Some(ref session) = session {
                session.contains_key(&session_key).await
            } else {
                false
            };

            if is_authenticated {
                inner.call(req).await
            } else {
                let body = serde_json::json!({
                    "error": {
                        "status": 401,
                        "message": "authentication required"
                    }
                });
                let response = Response::builder()
                    .status(StatusCode::UNAUTHORIZED)
                    .header(http::header::CONTENT_TYPE, "application/json")
                    .body(ResBody::from(
                        serde_json::to_string(&body).unwrap_or_default(),
                    ))
                    .unwrap_or_default();
                Ok(response)
            }
        })
    }
}

// ── Auth configuration ──────────────────────────────────────────

/// Configuration for authentication.
///
/// # Defaults
///
/// | Field | Default |
/// |-------|---------|
/// | `bcrypt_cost` | `12` |
/// | `session_key` | `"user_id"` |
#[derive(Debug, Clone, serde::Deserialize)]
pub struct AuthConfig {
    /// Bcrypt cost factor for password hashing.
    #[serde(default = "default_bcrypt_cost")]
    pub bcrypt_cost: u32,

    /// Session key used to identify authenticated users.
    #[serde(default = "default_session_key")]
    pub session_key: String,
}

const fn default_bcrypt_cost() -> u32 {
    DEFAULT_BCRYPT_COST
}

fn default_session_key() -> String {
    "user_id".to_owned()
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            bcrypt_cost: default_bcrypt_cost(),
            session_key: default_session_key(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn hash_and_verify_password() {
        let hash = hash_password("test_password").await.unwrap();
        assert!(hash.starts_with("$2b$"));
        assert!(verify_password("test_password", &hash).await.unwrap());
        assert!(!verify_password("wrong_password", &hash).await.unwrap());
    }

    #[tokio::test]
    async fn verify_invalid_hash_returns_false() {
        let result = verify_password("test", "not-a-valid-hash").await;
        assert!(result.is_ok());
        assert!(!result.unwrap());
    }

    #[tokio::test]
    async fn verify_password_rejects_invalid_hash_format_safely() {
        // Test short hash
        let result = verify_password("test", "short").await;
        assert!(result.is_ok());
        assert!(!result.unwrap());

        // Test hash with correct length but not starting with $
        let bad_prefix = "a".repeat(60);
        let result = verify_password("test", &bad_prefix).await;
        assert!(result.is_ok());
        assert!(!result.unwrap());

        // Test hash with incorrect length but starting with $
        let bad_length = "$2b$12$short";
        let result = verify_password("test", bad_length).await;
        assert!(result.is_ok());
        assert!(!result.unwrap());
    }

    #[test]
    fn auth_config_defaults() {
        let config = AuthConfig::default();
        assert_eq!(config.bcrypt_cost, 12);
        assert_eq!(config.session_key, "user_id");
    }

    #[test]
    fn auth_rejection_is_401() {
        let rejection = AuthRejection;
        let response = rejection.into_response();
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn auth_rejection_display() {
        assert_eq!(AuthRejection.to_string(), "authentication required");
    }

    #[tokio::test]
    async fn auth_extractor_returns_401_when_no_user() {
        use crate::state::AppState;
        use axum::Router;
        use axum::body::Body;
        use axum::routing::get;
        use tower::ServiceExt;

        #[derive(Clone)]
        struct TestUser {
            name: String,
        }

        async fn handler(Auth(user): Auth<TestUser>) -> String {
            user.name
        }

        let state = AppState {
            extensions: std::sync::Arc::new(
                std::sync::Mutex::new(std::collections::HashMap::new()),
            ),
            #[cfg(feature = "db")]
            pool: None,
            profile: None,
            started_at: std::time::Instant::now(),
            health_detailed: false,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
        };

        let app = Router::new().route("/", get(handler)).with_state(state);

        let response = app
            .oneshot(
                http::Request::builder()
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn auth_extractor_returns_user_when_present() {
        use crate::state::AppState;
        use axum::Router;
        use axum::body::Body;
        use axum::routing::get;
        use tower::ServiceExt;

        #[derive(Clone)]
        struct TestUser {
            name: String,
        }

        async fn handler(Auth(user): Auth<TestUser>) -> String {
            user.name
        }

        let state = AppState {
            extensions: std::sync::Arc::new(
                std::sync::Mutex::new(std::collections::HashMap::new()),
            ),
            #[cfg(feature = "db")]
            pool: None,
            profile: None,
            started_at: std::time::Instant::now(),
            health_detailed: false,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
        };

        // Middleware that inserts a user into extensions
        let app = Router::new()
            .route("/", get(handler))
            .layer(axum::middleware::from_fn(
                |mut req: axum::extract::Request, next: axum::middleware::Next| async move {
                    req.extensions_mut().insert(TestUser {
                        name: "alice".into(),
                    });
                    next.run(req).await
                },
            ))
            .with_state(state);

        let response = app
            .oneshot(
                http::Request::builder()
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(std::str::from_utf8(&body).unwrap(), "alice");
    }

    #[tokio::test]
    async fn require_auth_rejects_unauthenticated() {
        use axum::Router;
        use axum::body::Body;
        use axum::routing::get;
        use tower::ServiceExt;

        use crate::session::{MemoryStore, SessionConfig, SessionLayer};
        use crate::state::AppState;

        let state = AppState {
            extensions: std::sync::Arc::new(
                std::sync::Mutex::new(std::collections::HashMap::new()),
            ),
            #[cfg(feature = "db")]
            pool: None,
            profile: None,
            started_at: std::time::Instant::now(),
            health_detailed: false,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
        };

        let app = Router::new()
            .route("/protected", get(|| async { "secret" }))
            .layer(RequireAuth::new("user_id"))
            .layer(SessionLayer::new(
                MemoryStore::new(),
                SessionConfig::default(),
            ))
            .with_state(state);

        let response = app
            .oneshot(
                http::Request::builder()
                    .uri("/protected")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    // ── __check_secured tests ────────────────────────────────

    #[tokio::test]
    async fn check_secured_rejects_unauthenticated() {
        let session =
            crate::session::Session::new_for_test(String::new(), std::collections::HashMap::new());
        let result = __check_secured(&session, &[]).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(err.to_string(), "authentication required");
    }

    #[tokio::test]
    async fn check_secured_allows_authenticated() {
        let data = std::collections::HashMap::from([("user_id".into(), "42".into())]);
        let session = crate::session::Session::new_for_test("sess".into(), data);
        let result = __check_secured(&session, &[]).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn check_secured_rejects_wrong_role() {
        let data = std::collections::HashMap::from([
            ("user_id".into(), "42".into()),
            ("role".into(), "viewer".into()),
        ]);
        let session = crate::session::Session::new_for_test("sess".into(), data);
        let result = __check_secured(&session, &["admin"]).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.status(), StatusCode::FORBIDDEN);
        assert_eq!(err.to_string(), "insufficient permissions");
    }

    #[tokio::test]
    async fn check_secured_allows_matching_role() {
        let data = std::collections::HashMap::from([
            ("user_id".into(), "42".into()),
            ("role".into(), "admin".into()),
        ]);
        let session = crate::session::Session::new_for_test("sess".into(), data);
        let result = __check_secured(&session, &["admin"]).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn check_secured_allows_any_of_multiple_roles() {
        let data = std::collections::HashMap::from([
            ("user_id".into(), "42".into()),
            ("role".into(), "editor".into()),
        ]);
        let session = crate::session::Session::new_for_test("sess".into(), data);
        let result = __check_secured(&session, &["admin", "editor"]).await;
        assert!(result.is_ok());
    }

    // ── #[secured] macro integration tests ──────────────────────

    #[tokio::test]
    async fn secured_macro_rejects_unauthenticated() {
        use axum::Router;
        use axum::body::Body;
        use axum::routing::get;
        use tower::ServiceExt;

        use crate::session::{MemoryStore, SessionConfig, SessionLayer};
        use crate::state::AppState;

        #[autumn_macros::secured]
        async fn protected_handler() -> crate::AutumnResult<&'static str> {
            Ok("secret")
        }

        let state = AppState {
            extensions: std::sync::Arc::new(
                std::sync::Mutex::new(std::collections::HashMap::new()),
            ),
            #[cfg(feature = "db")]
            pool: None,
            profile: None,
            started_at: std::time::Instant::now(),
            health_detailed: false,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
        };

        let app = Router::new()
            .route("/", get(protected_handler))
            .layer(SessionLayer::new(
                MemoryStore::new(),
                SessionConfig::default(),
            ))
            .with_state(state);

        let response = app
            .oneshot(
                http::Request::builder()
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn secured_macro_allows_authenticated() {
        use axum::Router;
        use axum::body::Body;
        use axum::routing::get;
        use http::header::COOKIE;
        use tower::ServiceExt;

        use crate::session::{MemoryStore, SessionConfig, SessionLayer, SessionStore};
        use crate::state::AppState;

        #[autumn_macros::secured]
        async fn protected_handler() -> crate::AutumnResult<&'static str> {
            Ok("secret")
        }

        let store = MemoryStore::new();
        store
            .save(
                "sess1",
                std::collections::HashMap::from([("user_id".into(), "42".into())]),
            )
            .await
            .unwrap();

        let state = AppState {
            extensions: std::sync::Arc::new(
                std::sync::Mutex::new(std::collections::HashMap::new()),
            ),
            #[cfg(feature = "db")]
            pool: None,
            profile: None,
            started_at: std::time::Instant::now(),
            health_detailed: false,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
        };

        let app = Router::new()
            .route("/", get(protected_handler))
            .layer(SessionLayer::new(store, SessionConfig::default()))
            .with_state(state);

        let response = app
            .oneshot(
                http::Request::builder()
                    .uri("/")
                    .header(COOKIE, "autumn.sid=sess1")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(std::str::from_utf8(&body).unwrap(), "secret");
    }

    #[tokio::test]
    async fn secured_macro_with_role_rejects_wrong_role() {
        use axum::Router;
        use axum::body::Body;
        use axum::routing::get;
        use http::header::COOKIE;
        use tower::ServiceExt;

        use crate::session::{MemoryStore, SessionConfig, SessionLayer, SessionStore};
        use crate::state::AppState;

        #[autumn_macros::secured("admin")]
        async fn admin_only() -> crate::AutumnResult<&'static str> {
            Ok("admin area")
        }

        let store = MemoryStore::new();
        store
            .save(
                "sess1",
                std::collections::HashMap::from([
                    ("user_id".into(), "42".into()),
                    ("role".into(), "viewer".into()),
                ]),
            )
            .await
            .unwrap();

        let state = AppState {
            extensions: std::sync::Arc::new(
                std::sync::Mutex::new(std::collections::HashMap::new()),
            ),
            #[cfg(feature = "db")]
            pool: None,
            profile: None,
            started_at: std::time::Instant::now(),
            health_detailed: false,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
        };

        let app = Router::new()
            .route("/", get(admin_only))
            .layer(SessionLayer::new(store, SessionConfig::default()))
            .with_state(state);

        let response = app
            .oneshot(
                http::Request::builder()
                    .uri("/")
                    .header(COOKIE, "autumn.sid=sess1")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn secured_macro_with_multiple_roles_allows_match() {
        use axum::Router;
        use axum::body::Body;
        use axum::routing::get;
        use http::header::COOKIE;
        use tower::ServiceExt;

        use crate::session::{MemoryStore, SessionConfig, SessionLayer, SessionStore};
        use crate::state::AppState;

        #[autumn_macros::secured("admin", "editor")]
        async fn content_handler() -> crate::AutumnResult<&'static str> {
            Ok("content")
        }

        let store = MemoryStore::new();
        store
            .save(
                "sess1",
                std::collections::HashMap::from([
                    ("user_id".into(), "42".into()),
                    ("role".into(), "editor".into()),
                ]),
            )
            .await
            .unwrap();

        let state = AppState {
            extensions: std::sync::Arc::new(
                std::sync::Mutex::new(std::collections::HashMap::new()),
            ),
            #[cfg(feature = "db")]
            pool: None,
            profile: None,
            started_at: std::time::Instant::now(),
            health_detailed: false,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
        };

        let app = Router::new()
            .route("/", get(content_handler))
            .layer(SessionLayer::new(store, SessionConfig::default()))
            .with_state(state);

        let response = app
            .oneshot(
                http::Request::builder()
                    .uri("/")
                    .header(COOKIE, "autumn.sid=sess1")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(std::str::from_utf8(&body).unwrap(), "content");
    }

    #[tokio::test]
    async fn require_auth_allows_authenticated() {
        use axum::Router;
        use axum::body::Body;
        use axum::routing::get;
        use http::header::COOKIE;
        use tower::ServiceExt;

        use crate::session::{MemoryStore, SessionConfig, SessionLayer, SessionStore};
        use crate::state::AppState;

        let store = MemoryStore::new();
        // Pre-populate a session with user_id
        let mut session_data = std::collections::HashMap::new();
        session_data.insert("user_id".into(), "42".into());
        store.save("valid-session", session_data).await.unwrap();

        let state = AppState {
            extensions: std::sync::Arc::new(
                std::sync::Mutex::new(std::collections::HashMap::new()),
            ),
            #[cfg(feature = "db")]
            pool: None,
            profile: None,
            started_at: std::time::Instant::now(),
            health_detailed: false,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
        };

        let app = Router::new()
            .route("/protected", get(|| async { "secret" }))
            .layer(RequireAuth::new("user_id"))
            .layer(SessionLayer::new(store, SessionConfig::default()))
            .with_state(state);

        let response = app
            .oneshot(
                http::Request::builder()
                    .uri("/protected")
                    .header(COOKIE, "autumn.sid=valid-session")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(std::str::from_utf8(&body).unwrap(), "secret");
    }

    #[tokio::test]
    async fn require_auth_poll_ready_propagates() {
        use std::task::{Context, Poll};
        use tower::{Layer, Service};

        #[derive(Clone)]
        struct MockService {
            ready: bool,
            poll_count: std::sync::Arc<std::sync::atomic::AtomicUsize>,
        }

        impl Service<axum::extract::Request> for MockService {
            type Response = axum::response::Response;
            type Error = std::convert::Infallible;
            type Future = std::future::Ready<Result<Self::Response, Self::Error>>;

            fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
                self.poll_count
                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                if self.ready {
                    Poll::Ready(Ok(()))
                } else {
                    Poll::Pending
                }
            }

            fn call(&mut self, _req: axum::extract::Request) -> Self::Future {
                std::future::ready(Ok(axum::response::Response::new(axum::body::Body::empty())))
            }
        }

        let layer = RequireAuth::new("user_id");
        let poll_count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let mock_service = MockService {
            ready: false,
            poll_count: poll_count.clone(),
        };
        let mut service = layer.layer(mock_service);

        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);

        // When inner is not ready, RequireAuthService should not be ready
        let poll = service.poll_ready(&mut cx);
        assert!(poll.is_pending());
        assert_eq!(poll_count.load(std::sync::atomic::Ordering::SeqCst), 1);

        // When inner is ready, RequireAuthService should be ready
        let mock_service_ready = MockService {
            ready: true,
            poll_count: poll_count.clone(),
        };
        let mut service_ready = layer.layer(mock_service_ready);
        let poll_ready = service_ready.poll_ready(&mut cx);
        assert!(poll_ready.is_ready());
        assert_eq!(poll_count.load(std::sync::atomic::Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn auth_rejection_into_response() {
        let rejection = AuthRejection;
        let response = rejection.into_response();
        assert_eq!(response.status(), axum::http::StatusCode::UNAUTHORIZED);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"]["status"], 401);
        assert_eq!(json["error"]["message"], "authentication required");
    }

    #[test]
    fn test_auth_config_defaults() {
        let config = AuthConfig::default();
        assert_eq!(config.bcrypt_cost, DEFAULT_BCRYPT_COST);
        assert_eq!(config.session_key, "user_id");
    }
}