Skip to main content

allowthem_server/
bearer.rs

1use axum::extract::FromRequestParts;
2use axum::http::header::AUTHORIZATION;
3use axum::http::request::Parts;
4
5use allowthem_core::{AllowThem, User};
6
7use crate::error::AuthExtractError;
8
9/// Axum extractor that validates an API bearer token.
10///
11/// Reads the `Authorization: Bearer <token>` header, validates the token
12/// against the database, and returns the authenticated user.
13///
14/// Rejects with 401 if the header is absent, malformed, the token is unknown
15/// or expired, or the user is inactive.
16///
17/// This extractor requires `AllowThem: FromRef<S>` (not `Arc<dyn AuthClient>`)
18/// because API tokens are an embedded-mode feature not part of the auth trait.
19///
20/// Usage: `BearerAuthUser(user): BearerAuthUser` in handler arguments.
21pub struct BearerAuthUser(pub User);
22
23impl<S: Send + Sync> FromRequestParts<S> for BearerAuthUser {
24    type Rejection = AuthExtractError;
25
26    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
27        let ath = parts
28            .extensions
29            .get::<AllowThem>()
30            .cloned()
31            .ok_or(AuthExtractError::Unauthenticated)?;
32
33        let auth_header = parts
34            .headers
35            .get(AUTHORIZATION)
36            .and_then(|v| v.to_str().ok())
37            .ok_or(AuthExtractError::Unauthenticated)?;
38
39        let raw_token = auth_header
40            .strip_prefix("Bearer ")
41            .ok_or(AuthExtractError::Unauthenticated)?;
42
43        let (user_id, _token_info) = ath
44            .db()
45            .validate_api_token(raw_token)
46            .await
47            .map_err(AuthExtractError::Internal)?
48            .ok_or(AuthExtractError::Unauthenticated)?;
49
50        let user = ath.db().get_user(user_id).await.map_err(|e| match e {
51            allowthem_core::AuthError::NotFound => AuthExtractError::Unauthenticated,
52            other => AuthExtractError::Internal(other),
53        })?;
54
55        if !user.is_active {
56            return Err(AuthExtractError::Unauthenticated);
57        }
58
59        Ok(BearerAuthUser(user))
60    }
61}
62
63#[cfg(test)]
64mod tests {
65    use axum::Json;
66    use axum::Router;
67    use axum::http::{Request, StatusCode};
68    use axum::routing::get;
69    use chrono::{Duration, Utc};
70    use tower::ServiceExt;
71
72    use allowthem_core::{AllowThem, AllowThemBuilder, Email};
73
74    use super::*;
75
76    async fn test_setup() -> (AllowThem, String) {
77        let ath = AllowThemBuilder::new("sqlite::memory:")
78            .cookie_secure(false)
79            .build()
80            .await
81            .unwrap();
82
83        let email = Email::new("bearer@example.com".into()).unwrap();
84        let user = ath
85            .db()
86            .create_user(email, "password123", None, None)
87            .await
88            .unwrap();
89
90        let (raw, _) = ath
91            .db()
92            .create_api_token(user.id, "test-token", None, None)
93            .await
94            .unwrap();
95
96        (ath, raw)
97    }
98
99    fn test_app(ath: AllowThem) -> Router {
100        Router::new().route("/bearer", get(bearer_handler)).layer(
101            axum::middleware::from_fn_with_state(ath, crate::cors::inject_ath_into_extensions),
102        )
103    }
104
105    async fn bearer_handler(BearerAuthUser(user): BearerAuthUser) -> Json<serde_json::Value> {
106        Json(serde_json::json!({"email": user.email}))
107    }
108
109    async fn read_body(resp: axum::http::Response<axum::body::Body>) -> serde_json::Value {
110        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
111            .await
112            .unwrap();
113        serde_json::from_slice(&bytes).unwrap()
114    }
115
116    #[tokio::test]
117    async fn test_no_auth_header_returns_401() {
118        let (ath, _) = test_setup().await;
119        let app = test_app(ath);
120
121        let req = Request::builder()
122            .uri("/bearer")
123            .body(axum::body::Body::empty())
124            .unwrap();
125        let resp = app.oneshot(req).await.unwrap();
126
127        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
128    }
129
130    #[tokio::test]
131    async fn test_malformed_bearer_returns_401() {
132        let (ath, _) = test_setup().await;
133        let app = test_app(ath);
134
135        let req = Request::builder()
136            .uri("/bearer")
137            .header(AUTHORIZATION, "Token abc123")
138            .body(axum::body::Body::empty())
139            .unwrap();
140        let resp = app.oneshot(req).await.unwrap();
141
142        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
143    }
144
145    #[tokio::test]
146    async fn test_invalid_token_returns_401() {
147        let (ath, _) = test_setup().await;
148        let app = test_app(ath);
149
150        let req = Request::builder()
151            .uri("/bearer")
152            .header(AUTHORIZATION, "Bearer garbage-token-xyz")
153            .body(axum::body::Body::empty())
154            .unwrap();
155        let resp = app.oneshot(req).await.unwrap();
156
157        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
158    }
159
160    #[tokio::test]
161    async fn test_valid_bearer_returns_user() {
162        let (ath, raw_token) = test_setup().await;
163        let app = test_app(ath);
164
165        let req = Request::builder()
166            .uri("/bearer")
167            .header(AUTHORIZATION, format!("Bearer {raw_token}"))
168            .body(axum::body::Body::empty())
169            .unwrap();
170        let resp = app.oneshot(req).await.unwrap();
171
172        assert_eq!(resp.status(), StatusCode::OK);
173        let body = read_body(resp).await;
174        assert_eq!(body["email"], "bearer@example.com");
175    }
176
177    #[tokio::test]
178    async fn test_expired_token_returns_401() {
179        let ath = AllowThemBuilder::new("sqlite::memory:")
180            .cookie_secure(false)
181            .build()
182            .await
183            .unwrap();
184
185        let email = Email::new("expired-bearer@example.com".into()).unwrap();
186        let user = ath
187            .db()
188            .create_user(email, "password123", None, None)
189            .await
190            .unwrap();
191
192        let past = Utc::now() - Duration::hours(1);
193        let (raw, _) = ath
194            .db()
195            .create_api_token(user.id, "expired", Some(past), None)
196            .await
197            .unwrap();
198
199        let app = test_app(ath);
200
201        let req = Request::builder()
202            .uri("/bearer")
203            .header(AUTHORIZATION, format!("Bearer {raw}"))
204            .body(axum::body::Body::empty())
205            .unwrap();
206        let resp = app.oneshot(req).await.unwrap();
207
208        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
209    }
210
211    #[tokio::test]
212    async fn test_inactive_user_returns_401() {
213        let (ath, raw_token) = test_setup().await;
214
215        let email = Email::new("bearer@example.com".into()).unwrap();
216        let user = ath.db().get_user_by_email(&email).await.unwrap();
217        ath.db().update_user_active(user.id, false).await.unwrap();
218
219        let app = test_app(ath);
220
221        let req = Request::builder()
222            .uri("/bearer")
223            .header(AUTHORIZATION, format!("Bearer {raw_token}"))
224            .body(axum::body::Body::empty())
225            .unwrap();
226        let resp = app.oneshot(req).await.unwrap();
227
228        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
229        let body = read_body(resp).await;
230        assert_eq!(body["error"], "unauthenticated");
231    }
232}