Skip to main content

rustango_cms/
security_log.rs

1//! Sign-in security log and account lockout (#433).
2//!
3//! Every password sign-in, lockout, sign-out, password reset and change
4//! to who may do what (user flags, role memberships, role permissions)
5//! lands a row in `cms_security_event`, per tenant, which superusers read
6//! at `/cms-admin/security-log`.
7//!
8//! Two kinds of login feed it:
9//!
10//! * **Logins the CMS owns** — the member form (`/members/login`), the
11//!   headless API login, `/cms-admin/logout`, the password-reset
12//!   screens and the user and role screens — record their rows directly
13//!   with [`record`].
14//! * **Logins the framework owns** — the tenant admin `POST /login` and
15//!   its JWT login — are recorded from the framework's auth signals,
16//!   connected by [`install`]. The signals carry no tenant, so the
17//!   receiver takes it from [`rustango::tenant_log`], which the
18//!   framework's request log fills (on unless `[logging] access_log =
19//!   false`). Without it these events are not stored.
20//!
21//! ## Lockout
22//!
23//! Every password login goes through the framework's shared
24//! [`rustango::login_throttle`] gate in the tenant scope, so the admin
25//! form, the member form and the API login share one per-account lock
26//! (keyed by the submitted name, so an unknown name locks exactly like a
27//! real one and the lock is no account-enumeration oracle), plus per-IP
28//! and per-tenant limits. The lock is time-bounded: an attacker can hold
29//! an account locked only for `RCMS_LOGIN_LOCKOUT_SECONDS` after their
30//! last burst, never for good.
31//!
32//! The policy defaults to the framework's (5 failures in an hour lock
33//! the account for 15 minutes, or `[auth] lockout_*`). Set any of
34//! `RCMS_LOGIN_LOCKOUT_ATTEMPTS`, `RCMS_LOGIN_LOCKOUT_SECONDS`,
35//! `RCMS_LOGIN_LOCKOUT_WINDOW_SECONDS` to override it.
36//!
37//! Attempts refused while an account is locked are not logged one by
38//! one — that would let an anonymous client grow the table without any
39//! limit — only the failure that locked it is.
40
41use std::sync::Arc;
42use std::time::Duration;
43
44use chrono::{DateTime, Utc};
45use rustango::login_throttle::ClientIp;
46use rustango::signals::auth::AuthRequestMeta;
47use rustango::sql::Auto;
48use rustango::tenancy::TenantSlug;
49use rustango::Model;
50use serde::{Deserialize, Serialize};
51
52/// A password sign-in succeeded.
53pub const EVENT_LOGIN: &str = "login";
54/// A password sign-in was refused (unknown name, wrong password,
55/// disabled account).
56pub const EVENT_LOGIN_FAILED: &str = "login_failed";
57/// A failure locked the account.
58pub const EVENT_LOCKOUT: &str = "lockout";
59/// A session was ended.
60pub const EVENT_LOGOUT: &str = "logout";
61/// A password-reset link was issued.
62pub const EVENT_PASSWORD_RESET_REQUESTED: &str = "password_reset_requested";
63/// A password was changed through a reset link.
64pub const EVENT_PASSWORD_RESET: &str = "password_reset";
65/// A user's superuser flag, active flag or roles, or a role's
66/// permissions, were changed.
67pub const EVENT_PERMISSIONS_CHANGED: &str = "permissions_changed";
68
69/// Every event, in the order the viewer offers them as filters.
70pub const EVENTS: &[&str] = &[
71    EVENT_LOGIN,
72    EVENT_LOGIN_FAILED,
73    EVENT_LOCKOUT,
74    EVENT_LOGOUT,
75    EVENT_PASSWORD_RESET_REQUESTED,
76    EVENT_PASSWORD_RESET,
77    EVENT_PERMISSIONS_CHANGED,
78];
79
80/// Rows older than this many days are pruned unless
81/// `RCMS_SECURITY_LOG_RETENTION_DAYS` says otherwise.
82pub const DEFAULT_RETENTION_DAYS: i64 = 90;
83
84#[derive(Model, Debug, Clone, Serialize, Deserialize)]
85#[rustango(table = "cms_security_event", app = "cms", display = "event")]
86pub struct SecurityEvent {
87    #[rustango(primary_key)]
88    pub id: Auto<i64>,
89
90    /// One of the `EVENT_*` constants.
91    #[rustango(max_length = 32, index)]
92    pub event: String,
93
94    /// Which sign-in surface: `admin`, `member`, `api`, `jwt`, …
95    #[rustango(max_length = 32)]
96    pub source: String,
97
98    /// The account, when one was identified.
99    pub user_id: Option<i64>,
100
101    /// The name as submitted (or the account's username). For a role
102    /// change, empty.
103    #[rustango(max_length = 150, index)]
104    pub username: String,
105
106    /// Who made a permission change; empty for sign-in events.
107    #[rustango(max_length = 150, default = "''")]
108    pub actor: String,
109
110    /// What a permission change changed, in words.
111    #[rustango(max_length = 1000, default = "''")]
112    pub detail: String,
113
114    /// Why a sign-in failed: `invalid_credentials` or `inactive`.
115    #[rustango(max_length = 32, default = "''")]
116    pub reason: String,
117
118    #[rustango(max_length = 64, default = "''")]
119    pub ip_address: String,
120
121    #[rustango(max_length = 255, default = "''")]
122    pub user_agent: String,
123
124    #[rustango(auto_now_add, index)]
125    pub created_at: Auto<DateTime<Utc>>,
126}
127
128/// One event to store. Build with [`Entry::new`] and the setters.
129#[derive(Debug, Clone, Default)]
130pub struct Entry {
131    pub event: &'static str,
132    pub source: &'static str,
133    pub user_id: Option<i64>,
134    pub username: String,
135    pub reason: &'static str,
136    pub actor: String,
137    pub detail: String,
138    pub request: AuthRequestMeta,
139}
140
141impl Entry {
142    #[must_use]
143    pub fn new(event: &'static str, source: &'static str, request: &AuthRequestMeta) -> Self {
144        Self {
145            event,
146            source,
147            request: request.clone(),
148            ..Self::default()
149        }
150    }
151
152    #[must_use]
153    pub fn user(mut self, user_id: Option<i64>, username: &str) -> Self {
154        self.user_id = user_id;
155        self.username = username.to_owned();
156        self
157    }
158
159    #[must_use]
160    pub fn reason(mut self, reason: &'static str) -> Self {
161        self.reason = reason;
162        self
163    }
164
165    /// Who made a permission change, and what it changed.
166    #[must_use]
167    pub fn change(mut self, actor: &str, detail: impl Into<String>) -> Self {
168        self.actor = actor.to_owned();
169        self.detail = detail.into();
170        self
171    }
172}
173
174/// `s` cut to at most `max` characters.
175fn clip(s: &str, max: usize) -> String {
176    s.trim().chars().take(max).collect()
177}
178
179/// Store `entry` in `tenant_slug`'s log. Best-effort: a failed write is
180/// logged, never returned, so a broken log cannot break signing in.
181pub async fn record(pool: &rustango::sql::Pool, tenant_slug: &str, entry: Entry) {
182    let mut row = SecurityEvent {
183        id: Auto::Unset,
184        event: entry.event.to_owned(),
185        source: entry.source.to_owned(),
186        user_id: entry.user_id,
187        username: clip(&entry.username, 150),
188        reason: entry.reason.to_owned(),
189        actor: clip(&entry.actor, 150),
190        detail: clip(&entry.detail, 1000),
191        ip_address: clip(entry.request.ip_address.as_deref().unwrap_or(""), 64),
192        user_agent: clip(entry.request.user_agent.as_deref().unwrap_or(""), 255),
193        created_at: Auto::Unset,
194    };
195    if let Err(e) = row.insert(pool).await {
196        tracing::warn!(target: "rustango_cms::security_log", error = %e, event = entry.event, "security event not stored");
197        return;
198    }
199    prune_if_due(pool, tenant_slug).await;
200}
201
202// ------------------------------------------------------------------ permission changes
203
204/// What a user may do: the flags and roles a permission change compares.
205#[derive(Debug, Clone, Default, PartialEq, Eq)]
206pub struct Access {
207    pub superuser: bool,
208    pub active: bool,
209    /// Role names, in any order.
210    pub roles: Vec<String>,
211}
212
213fn on_off(b: bool) -> &'static str {
214    if b { "on" } else { "off" }
215}
216
217fn role_list(roles: &[String]) -> String {
218    let mut sorted = roles.to_vec();
219    sorted.sort();
220    if sorted.is_empty() {
221        "none".to_owned()
222    } else {
223        sorted.join(", ")
224    }
225}
226
227/// `before → after` in words (`superuser: off → on; roles: none →
228/// Editor`), or `None` when nothing that grants access changed.
229#[must_use]
230pub fn describe_user_change(before: &Access, after: &Access) -> Option<String> {
231    let mut parts = Vec::new();
232    if before.superuser != after.superuser {
233        parts.push(format!("superuser: {} → {}", on_off(before.superuser), on_off(after.superuser)));
234    }
235    if before.active != after.active {
236        parts.push(format!("active: {} → {}", on_off(before.active), on_off(after.active)));
237    }
238    let (old_roles, new_roles) = (role_list(&before.roles), role_list(&after.roles));
239    if old_roles != new_roles {
240        parts.push(format!("roles: {old_roles} → {new_roles}"));
241    }
242    (!parts.is_empty()).then(|| parts.join("; "))
243}
244
245/// A new user's access in words.
246#[must_use]
247pub fn describe_new_user(access: &Access) -> String {
248    format!(
249        "created; superuser: {}; active: {}; roles: {}",
250        on_off(access.superuser),
251        on_off(access.active),
252        role_list(&access.roles),
253    )
254}
255
256/// The codenames a role gained and lost (`role “Editor”: + cms_page.publish;
257/// − cms_page.delete`), or `None` when its set is unchanged.
258#[must_use]
259pub fn describe_role_change(name: &str, before: &[String], after: &[String]) -> Option<String> {
260    use std::collections::BTreeSet;
261    let before: BTreeSet<&str> = before.iter().map(String::as_str).collect();
262    let after: BTreeSet<&str> = after.iter().map(String::as_str).collect();
263    let added: Vec<&str> = after.difference(&before).copied().collect();
264    let removed: Vec<&str> = before.difference(&after).copied().collect();
265    let mut parts = Vec::new();
266    if !added.is_empty() {
267        parts.push(format!("+ {}", added.join(", ")));
268    }
269    if !removed.is_empty() {
270        parts.push(format!("− {}", removed.join(", ")));
271    }
272    (!parts.is_empty()).then(|| format!("role “{name}”: {}", parts.join("; ")))
273}
274
275// ------------------------------------------------------------------ retention
276
277fn retention_days() -> i64 {
278    crate::config::var("SECURITY_LOG_RETENTION_DAYS")
279        .and_then(|v| v.trim().parse::<i64>().ok())
280        .filter(|d| *d > 0)
281        .unwrap_or(DEFAULT_RETENTION_DAYS)
282}
283
284/// Delete rows past the retention window, at most once an hour per
285/// tenant, so the log of a site under attack stays bounded.
286async fn prune_if_due(pool: &rustango::sql::Pool, tenant_slug: &str) {
287    use std::collections::HashMap;
288    use std::sync::Mutex;
289    static LAST: Mutex<Option<HashMap<String, std::time::Instant>>> = Mutex::new(None);
290    {
291        let mut g = LAST.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
292        let map = g.get_or_insert_with(HashMap::new);
293        if map.get(tenant_slug).is_some_and(|t| t.elapsed() < Duration::from_secs(3600)) {
294            return;
295        }
296        map.insert(tenant_slug.to_owned(), std::time::Instant::now());
297    }
298    if let Err(e) = prune(pool, retention_days()).await {
299        tracing::warn!(target: "rustango_cms::security_log", error = %e, "security log prune failed");
300    }
301}
302
303/// Delete rows older than `days`. Returns how many went.
304///
305/// # Errors
306/// Driver / query failures.
307pub async fn prune(pool: &rustango::sql::Pool, days: i64) -> Result<u64, rustango::sql::ExecError> {
308    use rustango::core::Column as _;
309    let cutoff = Utc::now() - chrono::Duration::days(days);
310    let query = SecurityEvent::objects()
311        .where_(SecurityEvent::created_at.lt(cutoff))
312        .compile_delete()?;
313    rustango::sql::delete_pool(pool, &query).await
314}
315
316// ------------------------------------------------------------------ reading
317
318/// What the viewer filters by. Empty strings mean "any".
319#[derive(Debug, Clone, Default)]
320pub struct Filter {
321    pub event: String,
322    pub username: String,
323}
324
325fn filtered(filter: &Filter) -> rustango::query::QuerySet<SecurityEvent> {
326    use rustango::core::Column as _;
327    let mut qs = SecurityEvent::objects();
328    let event = filter.event.trim();
329    if EVENTS.contains(&event) {
330        qs = qs.where_(SecurityEvent::event.eq(event.to_owned()));
331    }
332    let username = filter.username.trim();
333    if !username.is_empty() {
334        qs = qs.where_(SecurityEvent::username.eq(username.to_owned()));
335    }
336    qs
337}
338
339/// How many rows match `filter`.
340///
341/// # Errors
342/// Driver / query failures.
343pub async fn count(pool: &rustango::sql::Pool, filter: &Filter) -> Result<i64, rustango::sql::ExecError> {
344    use rustango::sql::CounterPool as _;
345    filtered(filter).count(pool).await
346}
347
348/// One page of the rows matching `filter`, newest first.
349///
350/// # Errors
351/// Driver / query failures.
352pub async fn list(
353    pool: &rustango::sql::Pool,
354    filter: &Filter,
355    limit: i64,
356    offset: i64,
357) -> Result<Vec<SecurityEvent>, rustango::sql::ExecError> {
358    use rustango::sql::FetcherPool as _;
359    filtered(filter)
360        .order_by(&[("created_at", true), ("id", true)])
361        .limit(limit)
362        .offset(offset)
363        .fetch(pool)
364        .await
365}
366
367// ------------------------------------------------------------------ requests
368
369/// What a login handler needs from the request: the client address the
370/// throttle limits by, and the details a log row keeps.
371#[derive(Debug, Clone, Default)]
372pub struct LoginRequest {
373    pub ip: ClientIp,
374    pub meta: AuthRequestMeta,
375}
376
377impl<S: Send + Sync> axum::extract::FromRequestParts<S> for LoginRequest {
378    type Rejection = std::convert::Infallible;
379
380    async fn from_request_parts(
381        parts: &mut axum::http::request::Parts,
382        _: &S,
383    ) -> Result<Self, Self::Rejection> {
384        Ok(Self {
385            ip: ClientIp::from_parts(&parts.extensions, &parts.headers),
386            meta: rustango::signals::auth::meta_from_parts(
387                &parts.extensions,
388                &parts.headers,
389                Some(parts.uri.path()),
390            ),
391        })
392    }
393}
394
395// ------------------------------------------------------------------ lockout
396
397/// The lock key the framework's throttle uses for `username` in this
398/// site: `login:tenant:#org:<id>:<slug>:<sha256 of the trimmed, lowercased
399/// name>`. The framework keeps it private; `tests/security_log_sqlite.rs`
400/// fails if the two drift.
401fn lock_key(site: &TenantSlug, username: &str) -> String {
402    use sha2::{Digest as _, Sha256};
403    use std::fmt::Write as _;
404    let digest = Sha256::digest(username.trim().to_lowercase().as_bytes());
405    let mut key = format!("login:tenant:{}:", site.namespace());
406    for b in digest {
407        let _ = write!(key, "{b:02x}");
408    }
409    key
410}
411
412/// `true` when any of `names` is locked out of `site` right now.
413pub async fn is_locked(site: &TenantSlug, names: &[&str]) -> bool {
414    let lockout = rustango::account_lockout::shared();
415    for name in names {
416        if lockout.is_locked(&lock_key(site, name)).await {
417            return true;
418        }
419    }
420    false
421}
422
423/// Clear the lock and the failure count of `username` in `site`, as a
424/// successful sign-in would.
425pub async fn unlock(site: &TenantSlug, username: &str) {
426    rustango::account_lockout::shared().clear(&lock_key(site, username)).await;
427}
428
429/// The lockout policy from `RCMS_LOGIN_LOCKOUT_*`, or `None` when none
430/// is set (the framework default or `[auth] lockout_*` then applies).
431fn lockout_from_env() -> Option<rustango::account_lockout::Lockout> {
432    let num = |name: &str| {
433        crate::config::var(name).and_then(|v| match v.trim().parse::<u64>() {
434            Ok(n) if n > 0 => Some(n),
435            _ => {
436                tracing::warn!(target: "rustango_cms::security_log", setting = name, value = %v, "ignored: not a positive whole number");
437                None
438            }
439        })
440    };
441    let attempts = num("LOGIN_LOCKOUT_ATTEMPTS");
442    let seconds = num("LOGIN_LOCKOUT_SECONDS");
443    let window = num("LOGIN_LOCKOUT_WINDOW_SECONDS");
444    if attempts.is_none() && seconds.is_none() && window.is_none() {
445        return None;
446    }
447    let mut lockout =
448        rustango::account_lockout::Lockout::new(Arc::new(rustango::cache::InMemoryCache::new()));
449    if let Some(n) = attempts {
450        lockout = lockout.max_attempts(u32::try_from(n).unwrap_or(u32::MAX));
451    }
452    if let Some(s) = seconds {
453        lockout = lockout.lockout_duration(Duration::from_secs(s));
454    }
455    if let Some(s) = window {
456        lockout = lockout.counter_ttl(Duration::from_secs(s));
457    }
458    Some(lockout)
459}
460
461// ------------------------------------------------------------------ framework logins
462
463/// Apply the `RCMS_LOGIN_LOCKOUT_*` policy and start recording the
464/// framework's own logins. Idempotent; [`crate::ensure_seeded`] calls it
465/// at boot.
466pub fn install() {
467    static ONCE: std::sync::Once = std::sync::Once::new();
468    ONCE.call_once(|| {
469        if let Some(lockout) = lockout_from_env() {
470            if !rustango::account_lockout::configure_shared(lockout) {
471                tracing::warn!(
472                    target: "rustango_cms::security_log",
473                    "RCMS_LOGIN_LOCKOUT_* ignored: the application already installed a lockout policy"
474                );
475            }
476        }
477        connect_receivers();
478    });
479}
480
481fn connect_receivers() {
482    use rustango::signals::auth::{
483        connect_user_logged_in, connect_user_logged_out, connect_user_login_failed,
484        AuthFailureReason,
485    };
486    connect_user_logged_in(|ctx| async move {
487        let Some((site, pool)) = request_tenant().await else { return };
488        let entry = Entry::new(EVENT_LOGIN, signal_source(ctx.source), &ctx.request)
489            .user(Some(ctx.user_id), &ctx.username);
490        record(&pool, &site.slug, entry).await;
491    });
492    connect_user_login_failed(|ctx| async move {
493        let Some((site, pool)) = request_tenant().await else { return };
494        let username = ctx.attempted_username.unwrap_or_default();
495        let reason = match ctx.reason {
496            AuthFailureReason::Inactive => "inactive",
497            _ => "invalid_credentials",
498        };
499        let source = signal_source(ctx.source);
500        record(
501            &pool,
502            &site.slug,
503            Entry::new(EVENT_LOGIN_FAILED, source, &ctx.request)
504                .user(None, &username)
505                .reason(reason),
506        )
507        .await;
508        // The framework counts the failure before it signals, so a lock
509        // seen here is the one this failure set.
510        if is_locked(&site, &[&username]).await {
511            let entry = Entry::new(EVENT_LOCKOUT, source, &ctx.request).user(None, &username);
512            record(&pool, &site.slug, entry).await;
513        }
514    });
515    connect_user_logged_out(|ctx| async move {
516        if ctx.user_id.is_none() {
517            return;
518        }
519        let Some((site, pool)) = request_tenant().await else { return };
520        let entry = Entry::new(EVENT_LOGOUT, signal_source(ctx.source), &ctx.request)
521            .user(ctx.user_id, ctx.username.as_deref().unwrap_or(""));
522        record(&pool, &site.slug, entry).await;
523    });
524}
525
526/// The framework's surface tag, in this log's vocabulary.
527fn signal_source(source: &'static str) -> &'static str {
528    match source {
529        "tenant_admin" => "admin",
530        other => other,
531    }
532}
533
534/// The tenant the current request resolved to, and its pool. `None`
535/// outside a tenant request (operator console, bare admin) or when the
536/// request log that carries the tenant is off.
537async fn request_tenant() -> Option<(TenantSlug, rustango::sql::Pool)> {
538    let label = rustango::tenant_log::current()?;
539    let pool = crate::task_queue::resolve_pool(&label.slug).await?;
540    Some((TenantSlug::new(label.id?, label.slug), pool))
541}
542
543#[cfg(test)]
544mod tests {
545    use super::*;
546
547    #[test]
548    fn clip_counts_characters_not_bytes() {
549        assert_eq!(clip("  żółw  ", 3), "żół");
550        assert_eq!(clip("abc", 10), "abc");
551    }
552
553    fn access(superuser: bool, active: bool, roles: &[&str]) -> Access {
554        Access {
555            superuser,
556            active,
557            roles: roles.iter().map(|r| (*r).to_owned()).collect(),
558        }
559    }
560
561    #[test]
562    fn user_changes_name_only_what_changed() {
563        let before = access(false, true, &["Viewer"]);
564        assert_eq!(describe_user_change(&before, &before), None);
565        // Role order is not a change.
566        let reordered = access(false, true, &["Viewer"]);
567        assert_eq!(describe_user_change(&before, &reordered), None);
568        let after = access(true, true, &["Viewer", "Editor"]);
569        assert_eq!(
570            describe_user_change(&before, &after).as_deref(),
571            Some("superuser: off → on; roles: Viewer → Editor, Viewer"),
572        );
573        let after = access(false, false, &[]);
574        assert_eq!(
575            describe_user_change(&before, &after).as_deref(),
576            Some("active: on → off; roles: Viewer → none"),
577        );
578        assert_eq!(
579            describe_new_user(&access(false, true, &[])),
580            "created; superuser: off; active: on; roles: none",
581        );
582    }
583
584    #[test]
585    fn role_changes_list_gained_and_lost_codenames() {
586        let s = |v: &[&str]| v.iter().map(|c| (*c).to_owned()).collect::<Vec<_>>();
587        assert_eq!(describe_role_change("Editor", &s(&["a"]), &s(&["a"])), None);
588        assert_eq!(
589            describe_role_change("Editor", &s(&["a", "b"]), &s(&["a", "c"])).as_deref(),
590            Some("role “Editor”: + c; − b"),
591        );
592    }
593
594    #[test]
595    fn lock_keys_ignore_case_and_padding() {
596        let acme = TenantSlug::new(1, "acme");
597        assert_eq!(lock_key(&acme, " Alice "), lock_key(&acme, "alice"));
598        assert_ne!(lock_key(&acme, "alice"), lock_key(&TenantSlug::new(2, "other"), "alice"));
599        // Bound to the org id: a new site reusing the slug starts clean.
600        assert_ne!(lock_key(&acme, "alice"), lock_key(&TenantSlug::new(9, "acme"), "alice"));
601        assert!(lock_key(&acme, "alice").starts_with("login:tenant:#org:1:acme:"));
602    }
603}