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    request: crate::security_log::LoginRequest,
53    headers: axum::http::HeaderMap,
54    body: axum::body::Bytes,
55) -> Response {
56    let is_json = headers
57        .get(axum::http::header::CONTENT_TYPE)
58        .and_then(|v| v.to_str().ok())
59        .is_some_and(|v| v.starts_with("application/json"));
60
61    let parsed: Result<LoginForm, String> = if is_json {
62        serde_json::from_slice(&body).map_err(|e| e.to_string())
63    } else {
64        serde_urlencoded::from_bytes(&body).map_err(|e| e.to_string())
65    };
66    let Ok(form) = parsed else {
67        return crate::api::error::ApiError::bad_request(
68            "expected `identifier` and `password`, as JSON or form encoding",
69        )
70        .into_response();
71    };
72
73    login_inner(&tenant, &ctx, &request, &form).await
74}
75
76async fn login_inner(
77    tenant: &Tenant,
78    ctx: &rustango::extractors::TenantContext,
79    request: &crate::security_log::LoginRequest,
80    form: &LoginForm,
81) -> Response {
82    use crate::admin::MemberLoginError;
83    use crate::api::error::{ApiError, ErrorCode};
84    let outcome = crate::admin::authenticate_member(
85        tenant.pool(),
86        &tenant.org.slug,
87        request,
88        "api",
89        &form.identifier,
90        &form.password,
91    )
92    .await;
93    let user = match outcome {
94        Ok(user) => user,
95        // One message for "no such account" and "wrong password" — the
96        // difference is an account-enumeration oracle, and a client can
97        // do nothing useful with it either way.
98        Err(MemberLoginError::Invalid) => {
99            return ApiError::new(ErrorCode::Unauthenticated, "invalid credentials")
100                .into_response();
101        }
102        Err(MemberLoginError::Refused(refused)) => return refused_response(refused),
103    };
104
105    let uid = user.id.get().copied().unwrap_or_default();
106    let ttl = crate::admin::members::MEMBER_SESSION_TTL;
107    let token = member_auth::encode(
108        &ctx.session_secret,
109        &member_auth::MemberSessionPayload::new(
110            uid,
111            &tenant.org.slug,
112            ttl,
113            rustango::session::PasswordFingerprint::of(&ctx.session_secret, &user.password_hash),
114        ),
115    );
116
117    Json(serde_json::json!({
118        "token": token,
119        "token_type": "Bearer",
120        "expires_in": ttl,
121        "member": {
122            "id": uid,
123            "username": user.username,
124            "email": user.email,
125        },
126    }))
127    .into_response()
128}
129
130/// A login the throttle refused, in the API's error envelope, with the
131/// framework's `Retry-After`.
132fn refused_response(refused: rustango::login_throttle::LoginRefused) -> Response {
133    use crate::api::error::{ApiError, ErrorCode};
134    use rustango::login_throttle::LoginRefused;
135    let (error, retry_after) = match refused {
136        LoginRefused::Throttled { retry_after_secs } => (
137            ApiError::new(ErrorCode::RateLimited, "too many login attempts"),
138            retry_after_secs,
139        ),
140        LoginRefused::Busy => (
141            ApiError::new(ErrorCode::Unavailable, "login is busy, try again"),
142            1,
143        ),
144    };
145    let mut resp = error.into_response();
146    resp.headers_mut()
147        .insert(axum::http::header::RETRY_AFTER, retry_after.into());
148    resp
149}
150
151/// A member resolved from `Authorization: Bearer <token>`.
152///
153/// Never rejects — like [`member_auth::CurrentMember`] and
154/// `SessionUser`, an absent or invalid token simply means "anonymous",
155/// because these endpoints serve anonymous callers by design. A bad
156/// token must not turn a public page into a 401.
157#[derive(Debug, Clone)]
158pub struct BearerMember(pub Option<User>);
159
160impl<S: Send + Sync> FromRequestParts<S> for BearerMember {
161    type Rejection = Infallible;
162
163    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
164        let Some(token) = bearer_token(parts) else {
165            return Ok(Self(None));
166        };
167        let Some(ctx) = parts
168            .extensions
169            .get::<Arc<rustango::extractors::TenantContext>>()
170            .cloned()
171        else {
172            return Ok(Self(None));
173        };
174        use rustango::tenancy::OrgResolver as _;
175        let org = match ctx.resolver.resolve(parts, &ctx.pools.registry_pool()).await {
176            Ok(Some(o)) => o,
177            _ => return Ok(Self(None)),
178        };
179        // Same verification the cookie path runs: signature, expiry, and
180        // the tenant the token was minted for.
181        let Ok(payload) = member_auth::decode(&ctx.session_secret, &org.slug, &token) else {
182            return Ok(Self(None));
183        };
184        let Ok(pool) = ctx.pools.scoped_pool_dyn(&org).await else {
185            return Ok(Self(None));
186        };
187
188        use rustango::core::Column as _;
189        use rustango::sql::FetcherPool as _;
190        let user = User::objects()
191            .where_(User::id.eq(payload.uid))
192            .fetch(&pool)
193            .await
194            .unwrap_or_default()
195            .into_iter()
196            .next()
197            .filter(|u| u.active)
198            // A token minted before the user's last password change is
199            // dead, exactly as the cookie is. Rotating a password must
200            // log out every device, including SPA ones.
201            .filter(|u| match u.password_changed_at {
202                Some(changed) => payload.iat >= changed.timestamp(),
203                None => true,
204            });
205        Ok(Self(user))
206    }
207}
208
209/// Pull the token out of an `Authorization: Bearer …` header.
210fn bearer_token(parts: &Parts) -> Option<String> {
211    let raw = parts
212        .headers
213        .get(axum::http::header::AUTHORIZATION)?
214        .to_str()
215        .ok()?;
216    let (scheme, value) = raw.split_once(' ')?;
217    scheme
218        .eq_ignore_ascii_case("bearer")
219        .then(|| value.trim().to_owned())
220        .filter(|v| !v.is_empty())
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    fn parts_with(header: Option<&str>) -> Parts {
228        let mut b = axum::http::Request::builder().uri("/");
229        if let Some(h) = header {
230            b = b.header(axum::http::header::AUTHORIZATION, h);
231        }
232        b.body(()).unwrap().into_parts().0
233    }
234
235    #[test]
236    fn extracts_a_bearer_token() {
237        assert_eq!(
238            bearer_token(&parts_with(Some("Bearer abc.def"))),
239            Some("abc.def".to_owned()),
240        );
241    }
242
243    #[test]
244    fn the_scheme_is_case_insensitive() {
245        // RFC 9110 says the scheme is case-insensitive, and clients vary.
246        for h in ["bearer abc", "BEARER abc", "BeArEr abc"] {
247            assert_eq!(bearer_token(&parts_with(Some(h))), Some("abc".to_owned()));
248        }
249    }
250
251    #[test]
252    fn another_scheme_is_not_a_bearer_token() {
253        assert_eq!(bearer_token(&parts_with(Some("Basic abc"))), None);
254    }
255
256    #[test]
257    fn a_missing_or_empty_header_yields_nothing() {
258        assert_eq!(bearer_token(&parts_with(None)), None);
259        assert_eq!(bearer_token(&parts_with(Some("Bearer"))), None);
260        assert_eq!(bearer_token(&parts_with(Some("Bearer   "))), None);
261    }
262}