forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

audit.rs67 lines, 2.3 KiBHistoryRawDownload
1//! Writes to the security audit log. Recording never fails the request: a store error is logged
2//! and the action continues. Passwords and tokens never go into an entry.
3
4use forge_core::{AuditAction, AuditEntry, Store, User};
5use serde_json::Value;
6use topcoat::context::Cx;
7
8use crate::client_ip::client_ip;
9use crate::live::Topic;
10
11/// Who did it. `Anonymous` is an unauthenticated attempt, `Cli` is the admin command line.
12pub enum Actor<'a> {
13 User(&'a User),
14 Anonymous,
15 Cli,
16}
17
18/// What it was done to. Empty kind and id for actions with no object (such as a login).
19#[derive(Default)]
20pub struct Target<'a> {
21 pub kind: &'a str,
22 pub id: &'a str,
23 pub name: &'a str,
24}
25
26/// Appends one entry. `cx` supplies the client IP for web requests; the CLI passes `None` and
27/// gets an empty IP. `data` is an optional JSON object (`Value::Null` stores `{}`).
28pub async fn record(
29 store: &Store,
30 cx: Option<&Cx>,
31 actor: Actor<'_>,
32 action: AuditAction,
33 target: Target<'_>,
34 data: Value,
35) {
36 let mut entry = AuditEntry::new(action);
37 match actor {
38 Actor::User(user) => {
39 entry.actor_id = Some(user.id.clone());
40 entry.actor_name = user.username.clone();
41 }
42 Actor::Anonymous => {}
43 Actor::Cli => entry.actor_name = "cli".to_string(),
44 }
45 entry.target_kind = target.kind.to_string();
46 entry.target_id = target.id.to_string();
47 entry.target_name = target.name.to_string();
48 entry.ip = cx.map(|cx| client_ip(cx).to_string()).unwrap_or_default();
49 if !data.is_null() {
50 entry.data = data.to_string();
51 }
52 if let Err(err) = store.record_audit(&entry).await {
53 tracing::error!(action = action.as_str(), error = %err, "failed to record audit entry");
54 return;
55 }
56 // The entry is committed: the audit log and the account list follow it, and so do the
57 // accounts it names (the actor's last login, the target's facts and status).
58 let hub = crate::live::admin();
59 hub.bump(&Topic::AdminAudit);
60 hub.bump(&Topic::AdminUsers);
61 if let Some(actor) = &entry.actor_id {
62 hub.bump(&Topic::AdminUser(actor.clone()));
63 }
64 if target.kind == "user" && !target.id.is_empty() {
65 hub.bump(&Topic::AdminUser(target.id.to_string()));
66 }
67}