Skip to main content

rustango_cms/api/
auth.rs

1//! `POST /api/v2/auth/login` — a member session a browser SPA can hold.
2//!
3//! Member auth was cookie-only: `rustango_member_session` is
4//! `HttpOnly; SameSite=Lax`, and Lax cookies are simply not sent on
5//! cross-site fetches. So a decoupled frontend on its own origin could
6//! not authenticate a member *at all* — CORS and `credentials:
7//! "include"` do not help, because the browser never attaches the
8//! cookie. Gated content was unreachable except from a same-origin page.
9//!
10//! The token here is deliberately **not a new credential format**: it is
11//! the exact same signed value the cookie carries, minted by
12//! `member_auth::encode` and verified by `member_auth::decode`. So it
13//! inherits the existing expiry, the tenant binding, and the rule that a
14//! password change invalidates outstanding sessions — and it cannot
15//! drift from the cookie path, because there is only one path.
16//!
17//! What changes is transport: the SPA holds the value and sends
18//! `Authorization: Bearer <token>` instead of relying on a cookie the
19//! browser refuses to send.
20
21use axum::extract::FromRequestParts;
22use axum::http::request::Parts;
23use axum::response::{IntoResponse, Response};
24use axum::Json;
25use rustango::extractors::Tenant;
26use rustango::tenancy::auth::User;
27use rustango::tenancy::member_auth;
28use serde::Deserialize;
29use std::convert::Infallible;
30use std::sync::Arc;
31
32/// Where credentials are posted.
33pub const LOGIN_PATH: &str = "/api/v2/auth/login";
34
35/// Credentials. Accepts JSON or form encoding, so a SPA and an HTML form
36/// can both post here.
37#[derive(Deserialize)]
38pub struct LoginForm {
39    /// Email or username — whatever the member signed up with.
40    pub identifier: String,
41    pub password: String,
42}
43
44/// `POST /api/v2/auth/login`
45///
46/// Accepts `application/json` or form encoding, decided by
47/// `Content-Type`, so a SPA and a plain HTML form can both post here.
48/// Two separate handlers would need two routes for one path.
49pub async fn login(
50    tenant: Tenant,
51    axum::Extension(ctx): axum::Extension<Arc<rustango::extractors::TenantContext>>,
52    headers: axum::http::HeaderMap,
53    body: axum::body::Bytes,
54) -> Response {
55    let is_json = headers
56        .get(axum::http::header::CONTENT_TYPE)
57        .and_then(|v| v.to_str().ok())
58        .is_some_and(|v| v.starts_with("application/json"));
59
60    let parsed: Result<LoginForm, String> = if is_json {
61        serde_json::from_slice(&body).map_err(|e| e.to_string())
62    } else {
63        serde_urlencoded::from_bytes(&body).map_err(|e| e.to_string())
64    };
65    let Ok(form) = parsed else {
66        return crate::api::error::ApiError::bad_request(
67            "expected `identifier` and `password`, as JSON or form encoding",
68        )
69        .into_response();
70    };
71
72    login_inner(&tenant, &ctx, &form).await
73}
74
75async fn login_inner(
76    tenant: &Tenant,
77    ctx: &rustango::extractors::TenantContext,
78    form: &LoginForm,
79) -> Response {
80    let Some(user) = crate::admin::members::authenticate_member(
81        tenant.pool(),
82        &form.identifier,
83        &form.password,
84    )
85    .await
86    else {
87        // One message for "no such account" and "wrong password" — the
88        // difference is an account-enumeration oracle, and a client can
89        // do nothing useful with it either way.
90        return crate::api::error::ApiError::new(
91            crate::api::error::ErrorCode::Unauthenticated,
92            "invalid credentials",
93        )
94        .into_response();
95    };
96
97    let uid = user.id.get().copied().unwrap_or_default();
98    let ttl = crate::admin::members::MEMBER_SESSION_TTL;
99    let token = member_auth::encode(
100        &ctx.session_secret,
101        &member_auth::MemberSessionPayload::new(
102            uid,
103            &tenant.org.slug,
104            ttl,
105            rustango::session::PasswordFingerprint::of(&ctx.session_secret, &user.password_hash),
106        ),
107    );
108
109    Json(serde_json::json!({
110        "token": token,
111        "token_type": "Bearer",
112        "expires_in": ttl,
113        "member": {
114            "id": uid,
115            "username": user.username,
116            "email": user.email,
117        },
118    }))
119    .into_response()
120}
121
122/// A member resolved from `Authorization: Bearer <token>`.
123///
124/// Never rejects — like [`member_auth::CurrentMember`] and
125/// `SessionUser`, an absent or invalid token simply means "anonymous",
126/// because these endpoints serve anonymous callers by design. A bad
127/// token must not turn a public page into a 401.
128#[derive(Debug, Clone)]
129pub struct BearerMember(pub Option<User>);
130
131impl<S: Send + Sync> FromRequestParts<S> for BearerMember {
132    type Rejection = Infallible;
133
134    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
135        let Some(token) = bearer_token(parts) else {
136            return Ok(Self(None));
137        };
138        let Some(ctx) = parts
139            .extensions
140            .get::<Arc<rustango::extractors::TenantContext>>()
141            .cloned()
142        else {
143            return Ok(Self(None));
144        };
145        use rustango::tenancy::OrgResolver as _;
146        let org = match ctx.resolver.resolve(parts, &ctx.pools.registry_pool()).await {
147            Ok(Some(o)) => o,
148            _ => return Ok(Self(None)),
149        };
150        // Same verification the cookie path runs: signature, expiry, and
151        // the tenant the token was minted for.
152        let Ok(payload) = member_auth::decode(&ctx.session_secret, &org.slug, &token) else {
153            return Ok(Self(None));
154        };
155        let Ok(pool) = ctx.pools.scoped_pool_dyn(&org).await else {
156            return Ok(Self(None));
157        };
158
159        use rustango::core::Column as _;
160        use rustango::sql::FetcherPool as _;
161        let user = User::objects()
162            .where_(User::id.eq(payload.uid))
163            .fetch(&pool)
164            .await
165            .unwrap_or_default()
166            .into_iter()
167            .next()
168            .filter(|u| u.active)
169            // A token minted before the user's last password change is
170            // dead, exactly as the cookie is. Rotating a password must
171            // log out every device, including SPA ones.
172            .filter(|u| match u.password_changed_at {
173                Some(changed) => payload.iat >= changed.timestamp(),
174                None => true,
175            });
176        Ok(Self(user))
177    }
178}
179
180/// Pull the token out of an `Authorization: Bearer …` header.
181fn bearer_token(parts: &Parts) -> Option<String> {
182    let raw = parts
183        .headers
184        .get(axum::http::header::AUTHORIZATION)?
185        .to_str()
186        .ok()?;
187    let (scheme, value) = raw.split_once(' ')?;
188    scheme
189        .eq_ignore_ascii_case("bearer")
190        .then(|| value.trim().to_owned())
191        .filter(|v| !v.is_empty())
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    fn parts_with(header: Option<&str>) -> Parts {
199        let mut b = axum::http::Request::builder().uri("/");
200        if let Some(h) = header {
201            b = b.header(axum::http::header::AUTHORIZATION, h);
202        }
203        b.body(()).unwrap().into_parts().0
204    }
205
206    #[test]
207    fn extracts_a_bearer_token() {
208        assert_eq!(
209            bearer_token(&parts_with(Some("Bearer abc.def"))),
210            Some("abc.def".to_owned()),
211        );
212    }
213
214    #[test]
215    fn the_scheme_is_case_insensitive() {
216        // RFC 9110 says the scheme is case-insensitive, and clients vary.
217        for h in ["bearer abc", "BEARER abc", "BeArEr abc"] {
218            assert_eq!(bearer_token(&parts_with(Some(h))), Some("abc".to_owned()));
219        }
220    }
221
222    #[test]
223    fn another_scheme_is_not_a_bearer_token() {
224        assert_eq!(bearer_token(&parts_with(Some("Basic abc"))), None);
225    }
226
227    #[test]
228    fn a_missing_or_empty_header_yields_nothing() {
229        assert_eq!(bearer_token(&parts_with(None)), None);
230        assert_eq!(bearer_token(&parts_with(Some("Bearer"))), None);
231        assert_eq!(bearer_token(&parts_with(Some("Bearer   "))), None);
232    }
233}