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