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::Model;
49use serde::{Deserialize, Serialize};
50
51pub const EVENT_LOGIN: &str = "login";
53pub const EVENT_LOGIN_FAILED: &str = "login_failed";
56pub const EVENT_LOCKOUT: &str = "lockout";
58pub const EVENT_LOGOUT: &str = "logout";
60pub const EVENT_PASSWORD_RESET_REQUESTED: &str = "password_reset_requested";
62pub const EVENT_PASSWORD_RESET: &str = "password_reset";
64pub const EVENT_PERMISSIONS_CHANGED: &str = "permissions_changed";
67
68pub 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
79pub 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 #[rustango(max_length = 32, index)]
91 pub event: String,
92
93 #[rustango(max_length = 32)]
95 pub source: String,
96
97 pub user_id: Option<i64>,
99
100 #[rustango(max_length = 150, index)]
103 pub username: String,
104
105 #[rustango(max_length = 150, default = "''")]
107 pub actor: String,
108
109 #[rustango(max_length = 1000, default = "''")]
111 pub detail: String,
112
113 #[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#[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 #[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
173fn clip(s: &str, max: usize) -> String {
175 s.trim().chars().take(max).collect()
176}
177
178pub 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
205pub struct Access {
206 pub superuser: bool,
207 pub active: bool,
208 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#[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#[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#[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
274fn 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
283async 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
302pub 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#[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
338pub 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
347pub 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#[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
394fn 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
411pub 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
422pub async fn unlock(tenant_slug: &str, username: &str) {
425 rustango::account_lockout::shared().clear(&lock_key(tenant_slug, username)).await;
426}
427
428fn 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
460pub 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 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
525fn signal_source(source: &'static str) -> &'static str {
527 match source {
528 "tenant_admin" => "admin",
529 other => other,
530 }
531}
532
533async 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 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}