rustango-cms 0.3.0

A page-tree content management system for Rust, built on rustango
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
//! Public **members area** authentication (#members).
//!
//! A member is an end-user of the public site — a `rustango_users` row
//! distinguished from an admin only by the cookie that authenticates it
//! (`rustango_member_session` vs the admin `rustango_tenant_session`).
//! Members sign in through **any** method — email/password (this
//! module), or SSO / social (the framework's [`member_sso_router`],
//! mounted by the host at `/members/auth`). Every method mints the same
//! member session via [`member_auth::mint_cookie`], so the page-gating
//! guard ([`crate::view_restriction_guard`]) treats them uniformly.
//!
//! These routes live in [`super::public_router`] (unauthenticated, but
//! merged into the host `api` router so their POSTs are CSRF-protected
//! like every other admin form) and render through the shared admin
//! Tera with [`super::handlers::render_with_csrf`].
//!
//! [`member_sso_router`]: rustango::tenancy::member_auth::member_sso_router
//! [`member_auth::mint_cookie`]: rustango::tenancy::member_auth::mint_cookie

use std::collections::HashMap;
use std::sync::Arc;

use axum::extract::{Form, Query, State};
use axum::http::{header, HeaderMap, HeaderValue};
use axum::response::{IntoResponse, Redirect, Response};
use axum::Extension;
use tera::Context;

use rustango::extractors::{Tenant, TenantContext, TenantRejection};
use rustango::login_throttle::{self, LoginRefused, LoginScope};
use rustango::tenancy::auth::User;
use rustango::tenancy::member_auth::{self, CurrentMember};

use super::handlers::{add_branding_urls, render_with_csrf};
use crate::security_log::{self, LoginRequest};
use super::{AdminError, AdminState};

/// Member session lifetime — 7 days, matching the framework's
/// [`rustango::tenancy::member_auth::MemberAuthConfig`] default.
pub(crate) const MEMBER_SESSION_TTL: i64 = 7 * 24 * 60 * 60;

/// SSO buttons on the member login list the tenant's enabled providers
/// pointing at the member callback base (where the host mounts
/// [`member_sso_router`](rustango::tenancy::member_auth::member_sso_router)).
const MEMBER_SSO_BASE: &str = "/members/auth";

// ===================================================================
// Login (email/username + password)
// ===================================================================

#[derive(serde::Deserialize)]
pub(crate) struct MemberLoginForm {
    #[serde(default)]
    pub identifier: String,
    #[serde(default)]
    pub password: String,
    #[serde(default)]
    pub next: String,
}

/// GET `/members/login` — render the member sign-in page (password form
/// + one button per enabled SSO/social provider). An already-signed-in
/// member is bounced straight to the landing / `?next` destination.
pub(crate) async fn member_login_form(
    State(state): State<AdminState>,
    headers: HeaderMap,
    member: CurrentMember,
    tenant: Tenant,
    Query(q): Query<HashMap<String, String>>,
) -> Result<Response, AdminError> {
    let next = sanitize_next(q.get("next").map(String::as_str).unwrap_or("/"));
    if member.0.is_some() {
        return Ok(Redirect::to(&next).into_response());
    }
    let mut ctx = Context::new();
    ctx.insert("action", "/members/login");
    ctx.insert("signup_url", "/members/signup");
    ctx.insert("next", &next);
    if let Some(err) = q.get("error") {
        ctx.insert("error", err);
    }
    if let Some(err) = q.get("sso_error") {
        ctx.insert("sso_error", err);
    }
    let sso_providers =
        rustango::admin::sso_provider::list_enabled(tenant.pool(), MEMBER_SSO_BASE).await;
    ctx.insert("sso_enabled", &!sso_providers.is_empty());
    ctx.insert("sso_providers", &sso_providers);
    add_branding_urls(&mut ctx, &tenant).await;
    render_with_csrf(&state, &headers, "rcms_admin/member_login.html", &mut ctx)
}

/// POST `/members/login` — verify credentials against `rustango_users`
/// (by username OR email) and mint the member session cookie. Failures
/// bounce back to the form with a generic error (never leaking whether
/// the account exists).
pub(crate) async fn member_login_submit(
    Extension(ctx): Extension<Arc<TenantContext>>,
    tenant: Tenant,
    request: LoginRequest,
    Form(form): Form<MemberLoginForm>,
) -> Response {
    let next = sanitize_next(&form.next);
    let outcome = authenticate_member(
        tenant.pool(),
        &tenant.org.slug,
        &request,
        "member",
        &form.identifier,
        &form.password,
    )
    .await;
    match outcome {
        Ok(user) => {
            let cookie = member_auth::mint_cookie(
                &ctx.session_secret,
                &user,
                &tenant.org.slug,
                MEMBER_SESSION_TTL,
            );
            redirect_with_cookie(&next, &cookie)
        }
        Err(e) => {
            let reason = match e {
                MemberLoginError::Invalid => "invalid_credentials",
                MemberLoginError::Refused(_) => "throttled",
            };
            Redirect::to(&format!(
                "/members/login?error={reason}&next={}",
                crate::view_restriction_guard::url_encode_path(&next)
            ))
            .into_response()
        }
    }
}

// ===================================================================
// Signup (self-service email/password registration)
// ===================================================================

#[derive(serde::Deserialize)]
pub(crate) struct MemberSignupForm {
    #[serde(default)]
    pub email: String,
    #[serde(default)]
    pub password: String,
    #[serde(default)]
    pub password_confirm: String,
    #[serde(default)]
    pub display_name: String,
    #[serde(default)]
    pub next: String,
}

/// GET `/members/signup` — render the self-service registration form.
pub(crate) async fn member_signup_form(
    State(state): State<AdminState>,
    headers: HeaderMap,
    member: CurrentMember,
    tenant: Tenant,
    Query(q): Query<HashMap<String, String>>,
) -> Result<Response, AdminError> {
    let next = sanitize_next(q.get("next").map(String::as_str).unwrap_or("/"));
    if member.0.is_some() {
        return Ok(Redirect::to(&next).into_response());
    }
    let mut ctx = Context::new();
    ctx.insert("action", "/members/signup");
    ctx.insert("login_url", "/members/login");
    ctx.insert("next", &next);
    if let Some(err) = q.get("error") {
        ctx.insert("error", err);
    }
    add_branding_urls(&mut ctx, &tenant).await;
    render_with_csrf(&state, &headers, "rcms_admin/member_signup.html", &mut ctx)
}

/// POST `/members/signup` — validate, create a new member
/// (`is_superuser = false`, no tier — an admin assigns roles later),
/// and sign them straight in with a member cookie.
pub(crate) async fn member_signup_submit(
    Extension(ctx): Extension<Arc<TenantContext>>,
    tenant: Tenant,
    Form(form): Form<MemberSignupForm>,
) -> Response {
    let next = sanitize_next(&form.next);
    let email = form.email.trim().to_ascii_lowercase();

    let bounce = |reason: &str| {
        Redirect::to(&format!(
            "/members/signup?error={reason}&next={}",
            crate::view_restriction_guard::url_encode_path(&next)
        ))
        .into_response()
    };

    if email.is_empty() || !email.contains('@') {
        return bounce("invalid_email");
    }
    if form.password.len() < 8 {
        return bounce("weak_password");
    }
    if form.password != form.password_confirm {
        return bounce("password_mismatch");
    }
    match email_taken(tenant.pool(), &email).await {
        Ok(true) => return bounce("email_taken"),
        Ok(false) => {}
        Err(_) => return bounce("server_error"),
    }

    let display_name = if form.display_name.trim().is_empty() {
        email.split('@').next().unwrap_or(&email).to_owned()
    } else {
        form.display_name.trim().to_owned()
    };

    match create_member(tenant.pool(), &email, &form.password, &display_name).await {
        Ok(user) => {
            let cookie = member_auth::mint_cookie(
                &ctx.session_secret,
                &user,
                &tenant.org.slug,
                MEMBER_SESSION_TTL,
            );
            redirect_with_cookie(&next, &cookie)
        }
        Err(e) => {
            tracing::error!(target: "rustango_cms::members", error = %e, "member signup failed");
            bounce("server_error")
        }
    }
}

/// POST `/members/logout` — expire the member session and return to
/// the site root.
pub(crate) async fn member_logout(
    member: CurrentMember,
    tenant: Result<Tenant, TenantRejection>,
    request: LoginRequest,
) -> Response {
    if let (Some(user), Ok(tenant)) = (member.0, tenant) {
        let entry = security_log::Entry::new(security_log::EVENT_LOGOUT, "member", &request.meta)
            .user(user.id.get().copied(), &user.username);
        security_log::record(tenant.pool(), &tenant.org.slug, entry).await;
    }
    redirect_with_cookie("/", &member_auth::clear_cookie())
}

// ===================================================================
// Helpers
// ===================================================================

/// Why a member sign-in was refused.
#[derive(Debug)]
pub enum MemberLoginError {
    /// Too many attempts at this account or from this address, or the
    /// password-hashing queue is full. The password was not checked.
    Refused(LoginRefused),
    /// Unknown name, wrong password, or a disabled account — one answer
    /// for all three, so the response tells nothing about the account.
    Invalid,
}

/// Sign a member in by username OR (lowercased) email + password, in
/// `tenant_slug` (the tenant `pool` belongs to).
///
/// The attempt goes through the framework's login gate in the tenant
/// scope, so the account shares one lock with the admin `/login`, and is
/// written to the [`security_log`] as `source`. Runs a dummy verify on
/// the unknown-account branch so response timing doesn't reveal whether
/// the identifier exists.
///
/// # Errors
/// [`MemberLoginError`].
pub async fn authenticate_member(
    pool: &rustango::sql::Pool,
    tenant_slug: &str,
    request: &LoginRequest,
    source: &'static str,
    identifier: &str,
    password: &str,
) -> Result<User, MemberLoginError> {
    let ident = identifier.trim();
    if ident.is_empty() || password.is_empty() {
        return Err(MemberLoginError::Invalid);
    }
    let scope = LoginScope::Tenant(tenant_slug.to_owned());
    let mut attempt = login_throttle::shared()
        .begin(&scope, &request.ip, ident)
        .await
        .map_err(MemberLoginError::Refused)?;
    let found = find_member(pool, ident).await;
    if let Some(user) = &found {
        attempt.resolve(&user.username).await.map_err(MemberLoginError::Refused)?;
    }
    // Verify before checking `active` (#770): returning at once for a
    // disabled account made its response measurably faster than an active
    // one's or an unknown one's (which pays `verify_dummy`), so timing told
    // an attacker the account exists but is disabled.
    let password_ok = match &found {
        Some(user) => {
            matches!(crate::passwords::verify(password, &user.password_hash).await, Ok(true))
        }
        None => {
            crate::passwords::verify_dummy(password).await;
            false
        }
    };
    let active = found.as_ref().is_some_and(|u| u.active);
    let user_id = found.as_ref().and_then(|u| u.id.get().copied());
    let username = found.as_ref().map_or(ident, |u| u.username.as_str());
    if password_ok && active {
        attempt.succeeded().await;
        let entry = security_log::Entry::new(security_log::EVENT_LOGIN, source, &request.meta)
            .user(user_id, username);
        security_log::record(pool, tenant_slug, entry).await;
        return found.ok_or(MemberLoginError::Invalid);
    }
    attempt.failed().await;
    let reason = if password_ok { "inactive" } else { "invalid_credentials" };
    let entry = security_log::Entry::new(security_log::EVENT_LOGIN_FAILED, source, &request.meta)
        .user(user_id, username)
        .reason(reason);
    security_log::record(pool, tenant_slug, entry).await;
    // The gate refuses a locked account before it gets here, so a lock
    // seen now is the one this failure set.
    if security_log::is_locked(tenant_slug, &[ident, username]).await {
        let entry = security_log::Entry::new(security_log::EVENT_LOCKOUT, source, &request.meta)
            .user(user_id, username);
        security_log::record(pool, tenant_slug, entry).await;
    }
    Err(MemberLoginError::Invalid)
}

/// The `rustango_users` row named `ident` (username first, then the
/// lowercased email).
async fn find_member(pool: &rustango::sql::Pool, ident: &str) -> Option<User> {
    use rustango::core::Column as _;
    use rustango::sql::FetcherPool as _;
    let by_name: Vec<User> = User::objects()
        .where_(User::username.eq(ident.to_owned()))
        .limit(1)
        .fetch(pool)
        .await
        .unwrap_or_default();
    if let Some(user) = by_name.into_iter().next() {
        return Some(user);
    }
    User::objects()
        .filter("email", ident.to_ascii_lowercase())
        .limit(1)
        .fetch(pool)
        .await
        .unwrap_or_default()
        .into_iter()
        .next()
}

/// True when a `rustango_users` row already carries this (lowercased)
/// email.
async fn email_taken(pool: &rustango::sql::Pool, email: &str) -> Result<bool, AdminError> {
    use rustango::sql::FetcherPool as _;
    let rows: Vec<User> = User::objects()
        .filter("email", email.to_owned())
        .limit(1)
        .fetch(pool)
        .await?;
    Ok(!rows.is_empty())
}

/// Insert a new member row (username = email; unusable-until-set tiers
/// are granted later by an admin). Returns the new user id.
async fn create_member(
    pool: &rustango::sql::Pool,
    email: &str,
    password: &str,
    display_name: &str,
) -> Result<User, AdminError> {
    use rustango::sql::Auto;
    let mut user = User {
        id: Auto::Unset,
        username: email.to_owned(),
        password_hash: crate::passwords::hash(password).await
            .map_err(|e| AdminError::Validation(format!("password hashing failed: {e}")))?,
        email: Some(email.to_owned()),
        is_superuser: false,
        active: true,
        created_at: chrono::Utc::now(),
        data: serde_json::json!({ "display_name": display_name }),
        password_changed_at: None,
        sessions_revoked_at: None,
    };
    user.insert_pool(pool).await?;
    if user.id.get().is_none() {
        return Err(AdminError::Validation("member insert returned no id".to_owned()));
    }
    Ok(user)
}

/// Reject open-redirect-shaped `next` values: only a single-slash,
/// same-origin path is honored, everything else falls back to `/`.
fn sanitize_next(next: &str) -> String {
    rustango::auth_decorators::safe_next(next).unwrap_or_else(|| "/".to_owned())
}

/// A 303 redirect that also stamps a `Set-Cookie` header.
fn redirect_with_cookie(location: &str, set_cookie: &str) -> Response {
    let mut resp = Redirect::to(location).into_response();
    if let Ok(v) = HeaderValue::from_str(set_cookie) {
        resp.headers_mut().append(header::SET_COOKIE, v);
    }
    resp
}

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

    #[test]
    fn next_stays_on_site() {
        assert_eq!(sanitize_next("/members/area?x=1"), "/members/area?x=1");
        for hostile in ["https://evil.test", "//evil.test", "/\\evil.test", "/%5Cevil.test", "/%2F/evil.test", "/\t/evil.test"] {
            assert_eq!(sanitize_next(hostile), "/", "{hostile:?}");
        }
    }
}