Skip to content

Commit 4ea75df

Browse files
authored
feat(admin): event views show which administrator made each change, and why (#442)
Builds on #438 (#258), now merged. An administrator couldn't read why a change was made, or which administrator made it. The dashboard's events said "by an administrator", and `audit list` printed only the account's ID. A recovery's justification was stored with the event, but no view showed it. Now the dashboard and `audit list` show who made each change and why, with where the request came from. Closes #260. Part of #379. ## How - **The shared view.** `sourceorigin_common::admin::Event` gains: - `administrator`: the acting administrator's current handle, looked up once per administrator on each page; - `reason`, `ip` and `device`; - `erased`, set once retention or a purge deleted them. `AdminService::events` fills them, so the dashboard, `audit list` and its `--output json` read the same data. - **Dashboard.** An event caused by an administrator reads "by @alice: “Lost every passkey”", with the handle linking their account. The device ("Chrome on Linux", as the owner's history words it) and IP address follow, or "personal data erased". The Events page, an account's recent events and the overview share this renderer. Known kinds were already described in words. An `AccountDisabled` event recorded before #258 still shows the reason from its own field. - **`audit list`.** It prints `admin @alice` and a REASON column. `--output json` adds the origin. - **Docs.** `surfaces.md` and `administration.md` say what event views show. ## Proof - `recoveries_are_started_and_undone_from_the_dashboard`: an administrator starts a recovery. The recovery's row on the account page links `@handle` and quotes the reason. The service's view carries the handle, the reason and the IP address. - `audit_list_names_the_administrator_and_their_reason`: `audit list`'s line names `admin @alice` and ends with the reason. - On a preview, an administrator disabled and re-enabled an account, each with a reason. The dashboard showed "by @ev-admin-…: “Appeal accepted” · device Chrome on Linux · IP …", and `audit list` printed `admin @ev-admin-…` with each reason. - Dashboard, CLI and admin tests pass, and so do clippy and `just docs`. Reviewed by GPT 6.1 Sol. It found no correctness or privacy issues: administrators could already read IP addresses and devices in an account's security history. Its two findings are fixed: - The test matched the sidebar's handle and never checked `audit list`. - A purged administrator's handle was looked up once per event. > [!NOTE] > Written by Claude Opus 5.5 in Claude Code and reviewed by GPT 6.1 Sol (via T3 Code) 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Admin event views - Extended the shared admin `Event` model with an optional administrator handle, reason, request IP, device, and an erasure flag. - Updated event retrieval to include stored reason and request origin. It resolves each administrator’s current handle once per page. If the account no longer exists, the handle is omitted. - Updated the dashboard event list to show the administrator’s handle, the recorded reason, and available device and IP details. If personal data was erased, it displays that status instead of request details. - Updated `audit list` to include a `REASON` column. It shows `erased` when the reason has been erased and includes administrator handles when available. JSON output uses the expanded shared event view. ## Reasons for administrative changes - Made a `Reason` required for administrative mutations across accounts, sessions, invitations, administrator access, clients, keys, handles, deliveries, audit pruning, and related operations. - Updated dashboard forms and CLI commands to collect and pass reasons to the service layer. Alert updates now require a note that serves as the reason. - Recorded change reasons in events. Reasons for account changes also appear in the affected owner’s security history. Announcements use the fixed reason “See message contents.” - Separated read-event context from change-event context. Reads use `Operator::reading()` without a reason; changes use `Operator::context(reason)`. ## Tests and documentation - Updated service, CLI, dashboard, and browser tests for required reasons and the expanded event views. Added checks for administrator identity and reasons in recovery and audit-list output. - Updated administration guides, CLI references, runbooks, and operational examples to include required reason arguments and describe event-view details. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 1019072 commit 4ea75df

10 files changed

Lines changed: 199 additions & 33 deletions

File tree

‎apps/auth-service/src/admin/service/events.rs‎

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,12 @@ use crate::{
88
audit::{AuditChain, AuditPage, AuditVerification},
99
};
1010
use sourceorigin_common::{
11-
DeliveryId,
11+
DeliveryId, Handle, Personal, UserId,
1212
admin::{Event, EventPage, EventSearch, Paging},
13-
events::DomainEvent,
13+
events::{Actor, DomainEvent, RequestOrigin},
1414
};
15-
use sourceorigin_repository::{DeliveryStatus, DeliverySummary, EventFilter};
15+
use sourceorigin_repository::{DeliveryStatus, DeliverySummary, EventFilter, StoredEvent};
16+
use std::collections::HashMap;
1617

1718
/// Events per page.
1819
const EVENT_PAGE_SIZE: u16 = 50;
@@ -37,22 +38,54 @@ impl AdminService {
3738
let paging = Paging::new(search.page, total, u32::from(EVENT_PAGE_SIZE));
3839
filter.offset = u32::try_from(paging.offset()).unwrap_or(u32::MAX);
3940
let stored = events.list(&filter, u32::from(EVENT_PAGE_SIZE)).await?;
41+
let administrators = self.administrators_of(&stored).await?;
4042
let events = stored
4143
.into_iter()
4244
.map(|stored| {
45+
let (origin, erased) = match stored.origin {
46+
Personal::Value(origin) => (origin, false),
47+
Personal::Erased => (RequestOrigin::default(), true),
48+
};
49+
let administrator = match &stored.actor {
50+
Actor::Admin { user_id, .. } => administrators.get(user_id).cloned().flatten(),
51+
_ => None,
52+
};
4353
Ok(Event {
4454
id: stored.id,
4555
occurred_at: stored.occurred_at,
4656
actor: serde_json::to_value(stored.actor)?,
57+
administrator,
4758
subject: stored.subject,
4859
trace_id: stored.trace_id,
4960
event: serde_json::to_value(stored.event)?,
61+
reason: stored.reason,
62+
ip: origin.client_ip,
63+
device: origin.user_agent_family,
64+
erased,
5065
})
5166
})
5267
.collect::<Result<_, serde_json::Error>>()?;
5368
Ok(EventPage { events, paging })
5469
}
5570

71+
/// The current handles of the administrators who caused `events`, by account,
72+
/// each looked up once. An account purged since has none.
73+
async fn administrators_of(
74+
&self,
75+
events: &[StoredEvent],
76+
) -> Result<HashMap<UserId, Option<Handle>>, AdminError> {
77+
let mut handles = HashMap::new();
78+
for event in events {
79+
if let Actor::Admin { user_id, .. } = event.actor
80+
&& !handles.contains_key(&user_id)
81+
{
82+
let user = self.database.users().find_by_id(user_id).await?;
83+
handles.insert(user_id, user.map(|user| user.handle));
84+
}
85+
}
86+
Ok(handles)
87+
}
88+
5689
/// Recomputes the audit chain and checks every checkpoint against `keys`, and
5790
/// records what it found, which the dashboard's audit page shows. A broken
5891
/// chain is a result, naming where it breaks.

‎apps/auth-service/src/cli/audit.rs‎

Lines changed: 35 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,15 @@ use crate::{
88
};
99
use clap::{Args, Subcommand};
1010
use sourceorigin_common::{
11-
admin::{EventPage, EventSearch},
11+
admin::{Event, EventPage, EventSearch},
1212
events::Actor,
1313
};
1414
use std::path::PathBuf;
1515

1616
/// Paging through, verifying and pruning the audit history.
1717
#[derive(Subcommand)]
1818
pub(super) enum AuditCommand {
19-
/// Page through recorded events, newest first.
19+
/// Page through recorded events, newest first, with who caused each and why.
2020
List(ListEvents),
2121
/// Recompute the chain and check every checkpoint against it, and record what
2222
/// it found, which the dashboard's Audit tab shows. Exits non-zero, naming the
@@ -175,36 +175,51 @@ impl ListEvents {
175175
)
176176
}
177177

178-
/// Prints one event per line, and how to continue if there may be more.
178+
/// Prints one event per line, with who caused it and why, and how to continue
179+
/// if there may be more. `--output json` adds where its request came from.
179180
fn print_page(page: &EventPage) {
180-
println!("ID\tOCCURRED\tACTOR\tSUBJECT\tKIND");
181+
println!("ID\tOCCURRED\tACTOR\tSUBJECT\tKIND\tREASON");
181182
for event in &page.events {
182-
println!(
183-
"{}\t{}\t{}\t{}\t{}",
184-
event.id,
185-
event.occurred_at.to_rfc3339(),
186-
Self::actor(&event.actor),
187-
event
188-
.subject
189-
.map_or_else(|| "-".to_owned(), |id| id.to_string()),
190-
event.event["kind"].as_str().unwrap_or("-"),
191-
);
183+
println!("{}", Self::line(event));
192184
}
193185
Output::paging(page.paging, "events");
194186
}
195187

196-
/// Names who acted in a few words, or as the stored JSON when this release
197-
/// does not know the kind of actor.
198-
fn actor(actor: &serde_json::Value) -> String {
199-
match serde_json::from_value(actor.clone()) {
188+
/// `event` as one tab-separated line. A reason has no tab or line break.
189+
pub(super) fn line(event: &Event) -> String {
190+
let reason = match (&event.reason, event.erased) {
191+
(Some(reason), _) => reason.as_str(),
192+
(None, true) => "erased",
193+
(None, false) => "-",
194+
};
195+
format!(
196+
"{}\t{}\t{}\t{}\t{}\t{reason}",
197+
event.id,
198+
event.occurred_at.to_rfc3339(),
199+
Self::actor(event),
200+
event
201+
.subject
202+
.map_or_else(|| "-".to_owned(), |id| id.to_string()),
203+
event.event["kind"].as_str().unwrap_or("-"),
204+
)
205+
}
206+
207+
/// Names who caused `event` in a few words, an administrator by their handle
208+
/// while their account exists, or as the stored JSON when this release does
209+
/// not know the kind of actor.
210+
fn actor(event: &Event) -> String {
211+
match serde_json::from_value(event.actor.clone()) {
200212
Ok(Actor::User { user_id, .. }) => format!("user {user_id}"),
201-
Ok(Actor::Admin { user_id, .. }) => format!("admin {user_id}"),
213+
Ok(Actor::Admin { user_id, .. }) => match &event.administrator {
214+
Some(handle) => format!("admin @{handle}"),
215+
None => format!("admin {user_id}"),
216+
},
202217
Ok(Actor::Cli { os_user, host }) => format!("cli {os_user}@{host}"),
203218
Ok(Actor::Client { client_id }) => format!("client {client_id}"),
204219
Ok(Actor::System { job }) => format!("job {job:?}"),
205220
Ok(Actor::Anonymous) => "anonymous".to_owned(),
206221
Ok(Actor::Unrecorded) => "unrecorded".to_owned(),
207-
Err(_) => actor.to_string(),
222+
Err(_) => event.actor.to_string(),
208223
}
209224
}
210225
}

‎apps/auth-service/src/cli/tests.rs‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ use crate::{
99
tests::{Browser, Replicas, operator},
1010
};
1111
use sourceorigin_common::{
12-
AccountStatus, Handle, UserId,
12+
AccountStatus, EventId, Handle, SessionId, UserId,
13+
admin::Event,
1314
clients::ClientKind,
1415
config::ConfigurationError,
1516
events::{Actor, DomainEvent},
@@ -457,6 +458,35 @@ impl Administration {
457458
}
458459
}
459460

461+
/// `audit list` names an administrator by their handle, and prints why they
462+
/// acted.
463+
#[test]
464+
fn audit_list_names_the_administrator_and_their_reason() {
465+
let actor = Actor::Admin {
466+
user_id: UserId::new(),
467+
session_id: SessionId::new(),
468+
};
469+
let event = Event {
470+
id: EventId::new(),
471+
occurred_at: chrono::Utc::now(),
472+
actor: serde_json::to_value(actor).expect("actor"),
473+
administrator: Some(Handle::parse("alice").expect("handle")),
474+
subject: None,
475+
trace_id: None,
476+
event: serde_json::json!({"kind": "recovery_started"}),
477+
reason: Some("Lost every passkey".into()),
478+
ip: None,
479+
device: None,
480+
erased: false,
481+
};
482+
let line = audit::ListEvents::line(&event);
483+
assert!(line.contains("\tadmin @alice\t"), "{line}");
484+
assert!(
485+
line.ends_with("\trecovery_started\tLost every passkey"),
486+
"{line}"
487+
);
488+
}
489+
460490
/// The first event of `kind` in `user`'s history, newest first, which must exist.
461491
async fn recorded(
462492
database: &Database,

‎apps/auth-service/src/web/admin/tests.rs‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ use axum::{
2424
use chrono::{DateTime, Utc};
2525
use sourceorigin_common::{
2626
AccountStatus, AuthenticationMethod, Handle, PictureId, UserId,
27+
admin::EventSearch,
2728
events::{Actor, DomainEvent},
2829
notifications::Notification,
2930
};
@@ -966,7 +967,8 @@ async fn the_admin_listener_keeps_to_its_host_forms_and_session() {
966967

967968
/// Recovering an account mails its primary verified address a link, which the
968969
/// recovery pages then list, and undoing it cancels the unused link; both go on
969-
/// to the account's page. Until then, the account's sign-in methods say no
970+
/// to the account's page, whose events say which administrator started it and
971+
/// why, as `audit list` does. Until then, the account's sign-in methods say no
970972
/// passkey can be removed. An account whose link would not be mailed is left
971973
/// alone, saying why.
972974
#[tokio::test]
@@ -992,6 +994,38 @@ async fn recoveries_are_started_and_undone_from_the_dashboard() {
992994
assert_eq!(redirect(&post(&recover).await), account);
993995
let page = html(harness.visit(&dashboard, &recover).await).await;
994996
assert!(page.contains("Link sent, not used"), "{page}");
997+
let handle = harness
998+
.database
999+
.users()
1000+
.find_by_id(admin.user_id)
1001+
.await
1002+
.expect("lookup")
1003+
.expect("administrator")
1004+
.handle;
1005+
let page = html(harness.visit(&dashboard, &account).await).await;
1006+
// The recovery's row links its administrator by handle, then says why.
1007+
let who_and_why = format!(
1008+
r#"<a href="/users/{}">@{handle}</a>: “<span class="fact">Lost every passkey</span>”"#,
1009+
admin.user_id
1010+
);
1011+
assert!(page.contains(&who_and_why), "{who_and_why}: {page}");
1012+
let started = AdminService::new(harness.database.clone(), true)
1013+
.events(
1014+
&operator(),
1015+
EventSearch {
1016+
user: Some(owner.user_id),
1017+
kind: Some("recovery_started".into()),
1018+
..EventSearch::default()
1019+
},
1020+
)
1021+
.await
1022+
.expect("events");
1023+
let [started] = started.events.as_slice() else {
1024+
panic!("one recovery started: {started:?}");
1025+
};
1026+
assert_eq!(started.administrator, Some(handle));
1027+
assert_eq!(started.reason.as_deref(), Some("Lost every passkey"));
1028+
assert!(!started.erased && started.ip.is_some(), "{started:?}");
9951029
let sign_in = format!("/users/{}/sign-in", owner.user_id);
9961030
let page = html(harness.visit(&dashboard, &sign_in).await).await;
9971031
assert!(

‎crates/common/src/admin.rs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,13 @@ use crate::{
1010
AccountStatus, AnnouncementId, AuthenticationMethod, ClientId, DeliveryId, EventId, Handle,
1111
PictureId, SessionId, TokenId, TraceId, UserId,
1212
clients::RelatedOrigin,
13+
events::UserAgentFamily,
1314
form::Checkbox,
1415
protocol::{jwt::KeyId, oauth::ClientAuthMethod},
1516
};
1617
use chrono::{DateTime, Utc};
1718
use serde::{Deserialize, Serialize};
19+
use std::net::IpAddr;
1820
use url::Url;
1921

2022
/// An account, as search results and its detail page show it.
@@ -378,6 +380,10 @@ pub struct Event {
378380
pub occurred_at: DateTime<Utc>,
379381
/// Who caused it, e.g. `{"type": "admin", "user_id": …, "session_id": …}`.
380382
pub actor: serde_json::Value,
383+
/// The current handle of the administrator who caused it, when one did and
384+
/// their account still exists.
385+
#[serde(default, skip_serializing_if = "Option::is_none")]
386+
pub administrator: Option<Handle>,
381387
/// The account it concerns, if any.
382388
pub subject: Option<UserId>,
383389
/// The trace of the request or job that recorded it, to look up in telemetry
@@ -390,6 +396,20 @@ pub struct Event {
390396
/// or payload version the serving release does not know, written by a newer
391397
/// one, also carries its `version`.
392398
pub event: serde_json::Value,
399+
/// Why the administrator or operator who caused it did, as they wrote it,
400+
/// while kept.
401+
#[serde(default, skip_serializing_if = "Option::is_none")]
402+
pub reason: Option<String>,
403+
/// The request's IP address, while kept.
404+
#[serde(default, skip_serializing_if = "Option::is_none")]
405+
pub ip: Option<IpAddr>,
406+
/// The request's browser and platform, while kept.
407+
#[serde(default, skip_serializing_if = "Option::is_none")]
408+
pub device: Option<UserAgentFamily>,
409+
/// Whether retention or a purge deleted its personal data: the IP address,
410+
/// device and reason.
411+
#[serde(default)]
412+
pub erased: bool,
393413
}
394414

395415
/// An origin approved for a client's pages to sign users in with passkeys, which

‎crates/ui/src/admin/events.rs‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
44
use super::moment;
55
use crate::layout::{Pager, page_head, pager};
6+
use crate::settings::device_name;
67
use serde_json::Value;
78
use sourceorigin_common::{
89
AlertId, AuthenticationMethod, Personal, Provider,
@@ -88,11 +89,18 @@ impl EventRow<'_> {
8889
}
8990

9091
/// Who caused it, in a few words, and whether that is an administrator's or
91-
/// operator's doing.
92+
/// operator's doing. An administrator is named by their handle while their
93+
/// account exists.
9294
fn actor(&self) -> (String, bool) {
9395
match serde_json::from_value(self.event.actor.clone()) {
9496
Ok(Actor::User { .. }) => ("the account".to_owned(), false),
95-
Ok(Actor::Admin { .. }) => ("an administrator".to_owned(), true),
97+
Ok(Actor::Admin { .. }) => (
98+
self.event.administrator.as_ref().map_or_else(
99+
|| "an administrator".to_owned(),
100+
|handle| format!("@{handle}"),
101+
),
102+
true,
103+
),
96104
Ok(Actor::Cli { os_user, host }) => (format!("the terminal, {os_user}@{host}"), true),
97105
Ok(Actor::Client { client_id }) => (format!("the app {client_id}"), false),
98106
Ok(Actor::System { job }) => (format!("the {} job", Self::job(job)), false),
@@ -109,6 +117,20 @@ impl EventRow<'_> {
109117
.unwrap_or_else(|| format!("{job:?}").to_lowercase())
110118
}
111119

120+
/// Where its request came from, as the owner's history says it, or that
121+
/// retention or a purge erased it with the reason.
122+
fn request(&self) -> Vec<(&'static str, String)> {
123+
if self.event.erased {
124+
return vec![("personal data", "erased".to_owned())];
125+
}
126+
let device = self
127+
.event
128+
.device
129+
.map(|device| ("device", device_name(device)));
130+
let ip = self.event.ip.map(|ip| ("IP", ip.to_string()));
131+
device.into_iter().chain(ip).collect()
132+
}
133+
112134
/// Its stored JSON, pretty-printed.
113135
fn raw(&self) -> String {
114136
serde_json::to_string_pretty(&self.event.event).unwrap_or_default()
@@ -274,9 +296,12 @@ impl EventRow<'_> {
274296
DomainEvent::InvitationRevoked { invitation_id } => {
275297
Description::new("Invitation revoked").with("invitation", invitation_id)
276298
}
277-
DomainEvent::AccountDisabled { reason } => {
299+
// Its reason shows beside its administrator, as every change's does;
300+
// only one recorded before changes carried theirs keeps it here.
301+
DomainEvent::AccountDisabled { reason } if self.event.reason.is_none() => {
278302
Description::new("Account disabled").personal("reason", &reason)
279303
}
304+
DomainEvent::AccountDisabled { .. } => Description::new("Account disabled"),
280305
DomainEvent::AccountEnabled {} => Description::new("Account enabled again"),
281306
DomainEvent::AccountViewed {} => Description::new("Account details viewed"),
282307
DomainEvent::AdministratorGranted {} => {
@@ -551,6 +576,7 @@ pub async fn event_rows<'a>(rows: &'a [EventRow<'a>]) -> Result<impl View> {
551576
<ul class="events">
552577
for row in rows {
553578
let described = row.describe();
579+
let request = row.request();
554580
let (actor, _) = row.actor();
555581
<li>
556582
moment(at: row.event.occurred_at)
@@ -563,11 +589,14 @@ pub async fn event_rows<'a>(rows: &'a [EventRow<'a>]) -> Result<impl View> {
563589
Some(href) => <a href=(href.as_str())>(actor.as_str())</a>,
564590
None => (actor.as_str()),
565591
}
592+
if let Some(reason) = &row.event.reason {
593+
": “" <span class="fact">(reason.as_str())</span> "”"
594+
}
566595
// The account it concerns, unless that is who caused it.
567596
if let Some(account) = row.account.as_ref().filter(|account| row.actor.as_ref() != Some(account)) {
568597
" · " <a href=(account.as_str())>"account"</a>
569598
}
570-
for (name, value) in &described.facts {
599+
for (name, value) in described.facts.iter().chain(&request) {
571600
" · " (*name) " " <span class="fact">(value.as_str())</span>
572601
}
573602
</small>

0 commit comments

Comments
 (0)