//! The audit writer of the web layer. Every change of an account, a session or a sign-in goes //! through [`record`]. //! //! The entry is written after the change has committed. A failed write is logged and never fails //! the request: a person who has just signed in should not see an error because the log was busy. //! Nothing secret goes in `data`; callers pass counts, reasons and ids only. use im_core::model::AuditAction; use im_core::store::audit::NewAudit; use serde_json::Value; use topcoat::context::{Cx, app_context}; use crate::client_ip::client_addr; use crate::state::AppState; /// Who performed the action. #[derive(Clone, Copy)] pub enum Actor<'a> { /// A signed-in person, by their id. User(&'a str), /// Nobody is signed in: a failed sign-in, for example. Anonymous, } /// Appends one entry. `target` is the kind and id of what the action was about; `data` is JSON /// (`Value::Null` for none). pub async fn record( cx: &Cx, actor: Actor<'_>, action: AuditAction, target: Option<(&str, &str)>, data: Value, ) { let state = app_context::(cx); let ip = client_addr(cx).to_string(); let (actor_id, actor_kind) = match actor { Actor::User(id) => (Some(id), "user"), Actor::Anonymous => (None, "anonymous"), }; let data_text = (!data.is_null()).then(|| data.to_string()); let entry = NewAudit { actor_id, actor_kind, action: action.as_str(), target_kind: target.map(|(kind, _)| kind), target_id: target.map(|(_, id)| id), ip: Some(ip.as_str()), data: data_text.as_deref(), }; if let Err(error) = state.store.record_audit(&entry).await { tracing::error!( error = %error, action = action.as_str(), "audit entry was not written" ); } }