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