1use 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
52pub const EVENT_LOGIN: &str = "login";
54pub const EVENT_LOGIN_FAILED: &str = "login_failed";
57pub const EVENT_LOCKOUT: &str = "lockout";
59pub const EVENT_LOGOUT: &str = "logout";
61pub const EVENT_PASSWORD_RESET_REQUESTED: &str = "password_reset_requested";
63pub const EVENT_PASSWORD_RESET: &str = "password_reset";
65pub const EVENT_PERMISSIONS_CHANGED: &str = "permissions_changed";
68
69pub 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
80pub 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 #[rustango(max_length = 32, index)]
92 pub event: String,
93
94 #[rustango(max_length = 32)]
96 pub source: String,
97
98 pub user_id: Option<i64>,
100
101 #[rustango(max_length = 150, index)]
104 pub username: String,
105
106 #[rustango(max_length = 150, default = "''")]
108 pub actor: String,
109
110 #[rustango(max_length = 1000, default = "''")]
112 pub detail: String,
113
114 #[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#[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 #[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
174fn clip(s: &str, max: usize) -> String {
176 s.trim().chars().take(max).collect()
177}
178
179pub 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
206pub struct Access {
207 pub superuser: bool,
208 pub active: bool,
209 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#[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#[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#[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
275fn 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
284async 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
303pub 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#[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
339pub 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
348pub 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#[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
395fn 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
412pub 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
423pub async fn unlock(site: &TenantSlug, username: &str) {
426 rustango::account_lockout::shared().clear(&lock_key(site, username)).await;
427}
428
429fn 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
461pub 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 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
526fn signal_source(source: &'static str) -> &'static str {
528 match source {
529 "tenant_admin" => "admin",
530 other => other,
531 }
532}
533
534async 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 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 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}