//! `/admin/audit`: the audit log, newest first, with filters and keyset paging. //! //! The filters are an action, an actor id, a target id, and a day range. The cursor of the next page is the //! position of the last entry (`at|id`), so entries written while an administrator pages do not shift the //! pages. The day range is read in UTC: `from` is the first nanosecond of its day, and `to` is the last //! nanosecond of its day, so both days are included in full. use im_core::model::AuditEntry; use im_core::store::audit::{AuditCursor, AuditFilter}; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::page; use topcoat::view::{View, component, view}; use crate::auth::require_admin; use crate::i18n::Lang; use crate::i18n::admin::{A, text}; use crate::pages::admin::{PAGE_SIZE, Tab, frame_info, tabs}; use crate::state::AppState; use crate::views::{ViewerInfo, shell}; /// The query: the four filters, and the cursor of the page. #[derive(Deserialize, Default)] struct AuditQuery { #[serde(default)] action: String, #[serde(default)] actor: String, #[serde(default)] target: String, /// A day, `YYYY-MM-DD`. #[serde(default)] from: String, /// A day, `YYYY-MM-DD`, included. #[serde(default)] to: String, /// `at|id` of the last entry of the previous page. #[serde(default)] after: String, } /// `GET /admin/audit`. #[page("/admin/audit")] async fn audit_page(cx: &Cx, Form(query): Form) -> Result { let viewer = require_admin(cx).await?; let state = app_context::(cx); let (lang, info) = frame_info(cx, &viewer); let filter = AuditFilter { action: non_empty(&query.action), actor_id: non_empty(&query.actor), target_id: non_empty(&query.target), from: day_stamp(&query.from, false), to: day_stamp(&query.to, true), }; let cursor = cursor_of(&query.after); let (entries, next) = state .store .list_audit(&filter, cursor.as_ref(), PAGE_SIZE) .await?; let base = filter_query(&query); let next_href = next.map(|next| { format!( "/admin/audit?{base}&after={}", encode(&format!("{}|{}", next.at, next.id)) ) }); Ok(audit_view(cx, lang, info, base, query, entries, next_href)) } /// Trimmed text, or `None` when it is empty. fn non_empty(text: &str) -> Option { let text = text.trim(); (!text.is_empty()).then(|| text.to_owned()) } /// The stamp of the first (or, with `end`, the last) nanosecond of a `YYYY-MM-DD` day. A day that is not /// well formed is ignored, so the filter is simply not applied. fn day_stamp(day: &str, end: bool) -> Option { let bytes = day.trim().as_bytes(); let well_formed = bytes.len() == 10 && bytes.iter().enumerate().all(|(index, byte)| match index { 4 | 7 => *byte == b'-', _ => byte.is_ascii_digit(), }); if !well_formed { return None; } let day = day.trim(); Some(if end { format!("{day}T23:59:59.999999999Z") } else { format!("{day}T00:00:00.000000000Z") }) } /// The cursor of the page, from `at|id`. A cursor that is not well formed starts the first page. fn cursor_of(after: &str) -> Option { let (at, id) = after.split_once('|')?; (!at.is_empty() && !id.is_empty()).then(|| AuditCursor { at: at.to_owned(), id: id.to_owned(), }) } /// The filters as a query string, without the cursor. fn filter_query(query: &AuditQuery) -> String { format!( "action={}&actor={}&target={}&from={}&to={}", encode(&query.action), encode(&query.actor), encode(&query.target), encode(&query.from), encode(&query.to), ) } /// Percent-encodes everything but the unreserved characters, so a filter value cannot add a parameter. fn encode(value: &str) -> String { let mut out = String::with_capacity(value.len()); for byte in value.bytes() { if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') { out.push(char::from(byte)); } else { out.push_str(&format!("%{byte:02X}")); } } out } /// The audit page: the filters, the entries, and the links to the newest and the next page. fn audit_view( cx: &Cx, lang: Lang, info: ViewerInfo, base: String, query: AuditQuery, entries: Vec, next_href: Option, ) -> impl View { let newest = format!("/admin/audit?{base}"); view! { cx => shell(title: text(lang, A::AuditTitle), lang: lang, viewer: Some(info), tabs(lang: lang, current: Tab::Audit)

(text(lang, A::AuditTitle))

(text(lang, A::AuditIntro))

(text(lang, A::AuditNewer))

if entries.is_empty() {

(text(lang, A::AuditNoEntries))

} else { for entry in entries { audit_row(entry: entry) }
(text(lang, A::AuditWhen)) (text(lang, A::AuditWho)) (text(lang, A::AuditAction)) (text(lang, A::AuditTarget)) (text(lang, A::AuditIp)) (text(lang, A::AuditDetails))
} if let Some(href) = next_href {

(text(lang, A::AuditOlder))

}
) } } /// One entry of the log. Its details are text from the store; the view escapes them. #[component] async fn audit_row(entry: AuditEntry) -> Result { let who = entry .actor_id .clone() .unwrap_or_else(|| entry.actor_kind.clone()); let target = match (&entry.target_kind, &entry.target_id) { (Some(kind), Some(id)) => format!("{kind}:{id}"), _ => String::new(), }; Ok(view! { (entry.at.clone()) (who) (entry.action.clone()) (target) (entry.ip.clone().unwrap_or_default()) (entry.data.clone().unwrap_or_default()) }) }