From af20f046145364841383deff52de32dd36986cf6 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 13:47:39 +0100 Subject: [PATCH 1/2] fix(auth): events stay readable when a newer release recorded an actor this one doesn't know A stored actor of a type this release does not know, or a known type naming a value it does not know such as a new job, read as unknown with its JSON instead of failing the whole events read. A known actor that does not decode is still an error, and writes stay typed. Closes #676 --- apps/auth-service/src/account/tests.rs | 10 +-- apps/auth-service/src/admin/service/events.rs | 8 +- apps/auth-service/src/admin/tests/accounts.rs | 8 +- .../src/admin/tests/announcements.rs | 2 +- .../src/admin/tests/deliveries.rs | 2 +- apps/auth-service/src/admin/tests/messages.rs | 2 +- apps/auth-service/src/alerts/tests.rs | 2 +- apps/auth-service/src/audit/tests.rs | 6 +- apps/auth-service/src/cli/account.rs | 10 +-- apps/auth-service/src/cli/tests.rs | 8 +- .../src/clients/tests/deletion.rs | 6 +- .../src/clients/tests/registry.rs | 2 +- apps/auth-service/src/deletion/tests.rs | 86 +++++++++++++++++-- apps/auth-service/src/emails/tests.rs | 2 +- apps/auth-service/src/history/mod.rs | 21 +++-- apps/auth-service/src/history/tests.rs | 10 ++- apps/auth-service/src/keys/tests.rs | 6 +- apps/auth-service/src/notifications/tests.rs | 14 +-- .../src/oidc/tests/app_removal.rs | 2 +- apps/auth-service/src/sessions/tests.rs | 6 +- apps/auth-service/src/web/admin/tests/mod.rs | 2 +- ...c46d6f7b8e1c8163cbf5f12c214099398b02.json} | 6 +- ...66d5a3f2400ee36630e7bfe61f075724f09e.json} | 6 +- ...d18489a433abf243569b0646c6632b994404.json} | 6 +- crates/database/src/lib.rs | 2 +- .../database/src/repositories/events/mod.rs | 54 ++++++++++-- .../database/src/repositories/events/tests.rs | 68 ++++++++++++++- crates/database/src/repositories/mod.rs | 34 +++++--- crates/ui/src/settings/timeline.rs | 21 +++-- docs/dev/architecture/database.md | 16 +++- 30 files changed, 323 insertions(+), 105 deletions(-) rename crates/database/.sqlx/{query-272ffe8342df643dbd8f71220ba5e30a88fefca2ee6a5b30063554881094433e.json => query-56a009ea93354f9751267dee1f96c46d6f7b8e1c8163cbf5f12c214099398b02.json} (68%) rename crates/database/.sqlx/{query-bbd34bb4b9c0b313f31775d31d7158d943c00a90f5ca9cebad8b231cc41ce44e.json => query-a0794ef8a5630571d2fa84bbd94a66d5a3f2400ee36630e7bfe61f075724f09e.json} (70%) rename crates/database/.sqlx/{query-91e8ca711565c9e8d85627a1a20c62d5b5ec2d1913e51e811e1e6291d06253fb.json => query-a7249cae558f351ab2b3447fad7dd18489a433abf243569b0646c6632b994404.json} (59%) diff --git a/apps/auth-service/src/account/tests.rs b/apps/auth-service/src/account/tests.rs index df5314f47..66ffe6d65 100644 --- a/apps/auth-service/src/account/tests.rs +++ b/apps/auth-service/src/account/tests.rs @@ -187,7 +187,7 @@ async fn administrators_change_another_account_on_its_behalf() { .iter() .find(|stored| stored.event.known() == Some(&expected)) .unwrap_or_else(|| panic!("{expected:?} recorded")); - assert_eq!(stored.actor, actor, "{expected:?}"); + assert_eq!(stored.actor.known(), Some(&actor), "{expected:?}"); assert_eq!(stored.reason.as_deref(), Some(REASON), "{expected:?}"); } @@ -281,7 +281,7 @@ async fn owners_and_administrators_change_the_display_name() { Some(DomainEvent::DisplayNameChanged { old, new }) => Some(( old.clone(), new.clone(), - stored.actor.clone(), + stored.actor.known().cloned().expect("known actor"), stored.reason.as_deref(), )), _ => None, @@ -430,11 +430,11 @@ async fn administrators_reads_are_recorded_as_views() { }; assert_ne!(other.actor, view.actor); assert_eq!( - view.actor, - Actor::Admin { + view.actor.known(), + Some(&Actor::Admin { user_id: fixture.admin.user_id, session_id: fixture.admin.session_id, - } + }) ); assert_eq!(view.subject, Some(target.user_id)); } diff --git a/apps/auth-service/src/admin/service/events.rs b/apps/auth-service/src/admin/service/events.rs index a2d27e025..68e0d76ad 100644 --- a/apps/auth-service/src/admin/service/events.rs +++ b/apps/auth-service/src/admin/service/events.rs @@ -46,8 +46,10 @@ impl AdminService { Personal::Value(origin) => (origin, false), Personal::Erased => (RequestOrigin::default(), true), }; - let administrator = match &stored.actor { - Actor::Admin { user_id, .. } => administrators.get(user_id).cloned().flatten(), + let administrator = match stored.actor.known() { + Some(Actor::Admin { user_id, .. }) => { + administrators.get(user_id).cloned().flatten() + } _ => None, }; Ok(Event { @@ -76,7 +78,7 @@ impl AdminService { ) -> Result>, AdminError> { let mut handles = HashMap::new(); for event in events { - if let Actor::Admin { user_id, .. } = event.actor + if let Some(&Actor::Admin { user_id, .. }) = event.actor.known() && !handles.contains_key(&user_id) { let user = self.database.users().find_by_id(user_id).await?; diff --git a/apps/auth-service/src/admin/tests/accounts.rs b/apps/auth-service/src/admin/tests/accounts.rs index 37c5be089..7ddffbdb2 100644 --- a/apps/auth-service/src/admin/tests/accounts.rs +++ b/apps/auth-service/src/admin/tests/accounts.rs @@ -193,7 +193,13 @@ async fn events_a_newer_release_wrote_are_listed() { harness .database .events() - .insert_written_elsewhere(user.user_id, "from_a_newer_release", 1, &data) + .insert_written_elsewhere( + user.user_id, + "from_a_newer_release", + 1, + &data, + &json!({"type": "anonymous"}), + ) .await .expect("event"); let filter = EventSearch { diff --git a/apps/auth-service/src/admin/tests/announcements.rs b/apps/auth-service/src/admin/tests/announcements.rs index 68fb33560..c88e08bf2 100644 --- a/apps/auth-service/src/admin/tests/announcements.rs +++ b/apps/auth-service/src/admin/tests/announcements.rs @@ -142,7 +142,7 @@ async fn announcements_change_until_a_confirmed_administrator_sends_them() { }) }) .expect("recorded"); - assert_eq!(recorded.actor, administrator.reading().actor); + assert_eq!(recorded.actor.known(), Some(&administrator.reading().actor)); // Nobody writes a reason for it: its text says why. assert_eq!(recorded.reason.as_deref(), Some("See message contents")); assert_refused( diff --git a/apps/auth-service/src/admin/tests/deliveries.rs b/apps/auth-service/src/admin/tests/deliveries.rs index 8d2824dac..9b276bfdb 100644 --- a/apps/auth-service/src/admin/tests/deliveries.rs +++ b/apps/auth-service/src/admin/tests/deliveries.rs @@ -113,6 +113,6 @@ async fn delivery_changes_check_and_record_their_administrator() { ) }) .unwrap_or_else(|| panic!("{kind} recorded")); - assert_eq!(recorded.actor, admin.reading().actor, "{kind}"); + assert_eq!(recorded.actor.known(), Some(&admin.reading().actor)); } } diff --git a/apps/auth-service/src/admin/tests/messages.rs b/apps/auth-service/src/admin/tests/messages.rs index bc507ffd8..bd1440824 100644 --- a/apps/auth-service/src/admin/tests/messages.rs +++ b/apps/auth-service/src/admin/tests/messages.rs @@ -92,7 +92,7 @@ async fn messages_reach_the_inbox_and_the_primary_address_until_purged() { let events = harness.database.events().list(&filter, 10).await; let [sent] = events.expect("events").try_into().expect("one event"); assert_eq!(sent.event.known(), Some(&DomainEvent::MessageSent {})); - assert_eq!(sent.actor, admin.reading().actor); + assert_eq!(sent.actor.known(), Some(&admin.reading().actor)); // Nobody writes a reason for it: its text says why. assert_eq!(sent.reason.as_deref(), Some("See message contents")); diff --git a/apps/auth-service/src/alerts/tests.rs b/apps/auth-service/src/alerts/tests.rs index a272a005a..b09627ecb 100644 --- a/apps/auth-service/src/alerts/tests.rs +++ b/apps/auth-service/src/alerts/tests.rs @@ -219,7 +219,7 @@ async fn updates_acknowledge_an_alert_until_its_condition_changes() { .await .expect("events") .remove(0); - assert!(matches!(recorded.actor, Actor::Admin { .. })); + assert!(matches!(recorded.actor.known(), Some(Actor::Admin { .. }))); assert_eq!( recorded.event, RecordedEvent::Known(DomainEvent::AlertUpdated { diff --git a/apps/auth-service/src/audit/tests.rs b/apps/auth-service/src/audit/tests.rs index fe5a466e4..178a0c996 100644 --- a/apps/auth-service/src/audit/tests.rs +++ b/apps/auth-service/src/audit/tests.rs @@ -649,10 +649,10 @@ async fn the_verifier_verifies_when_no_verification_is_recent() { .expect("newest") .expect("recorded"); assert_eq!( - newest.actor, - Actor::System { + newest.actor.known(), + Some(&Actor::System { job: JobName::AuditVerification - } + }) ); assert_eq!(verifier.pass(&mut lock).await.expect("pass"), None); lock.release().await.expect("release"); diff --git a/apps/auth-service/src/cli/account.rs b/apps/auth-service/src/cli/account.rs index fef2c0532..6e444426e 100644 --- a/apps/auth-service/src/cli/account.rs +++ b/apps/auth-service/src/cli/account.rs @@ -21,6 +21,7 @@ use clap::{Args, Subcommand}; use sourceorigin_common::{ ClientId, EmailId, EventId, NotificationId, PasskeyId, Provider, SessionId, UserId, admin::KnownDevice, + events::HistoryActor, notifications::NotificationPreference, protocol::api::{Identity, Passkey}, }; @@ -593,7 +594,7 @@ report!(HistoryPage, self, out, { Cell::new(item.id), item.occurred_at.into(), Cell::new(item.entry.kind()), - Cell::new(item.actor), + item.actor.map(HistoryActor::as_str).into(), item.reason.as_deref().into(), ] }), @@ -652,10 +653,9 @@ report!(NotificationView, self, out, { fields.push(("Offers", Cell::new(action.label()))); } if let Some(entry) = &self.history { - fields.push(( - "History entry", - Cell::new(format_args!("{} (by {})", entry.id, entry.actor)), - )); + // An actor a newer release recorded is not named. + let by = (entry.actor).map_or_else(String::new, |actor| format!(" (by {actor})")); + fields.push(("History entry", Cell::new(format_args!("{}{by}", entry.id)))); } out.fields(&fields)?; out.blank()?; diff --git a/apps/auth-service/src/cli/tests.rs b/apps/auth-service/src/cli/tests.rs index be2ff4571..b3fa45711 100644 --- a/apps/auth-service/src/cli/tests.rs +++ b/apps/auth-service/src/cli/tests.rs @@ -529,7 +529,9 @@ async fn user_disable_runs_the_admin_operation() { matches!(event, DomainEvent::AccountDisabled { .. }) }) .await; - assert!(matches!(&disabled.actor, Actor::Cli { os_user, .. } if os_user == "test")); + assert!( + matches!(disabled.actor.known(), Some(Actor::Cli { os_user, .. }) if os_user == "test") + ); recorded(&database, browser.user_id, |event| { matches!(event, DomainEvent::SessionRevoked { session_id, .. } if *session_id == browser.session_id) }) @@ -560,7 +562,7 @@ async fn account_commands_run_the_shared_operation() { matches!(event, DomainEvent::SessionRevoked { session_id, .. } if *session_id == browser.session_id) }) .await; - assert!(matches!(&revoked.actor, Actor::Cli { os_user, .. } if os_user == "test")); + assert!(matches!(revoked.actor.known(), Some(Actor::Cli { os_user, .. }) if os_user == "test")); assert_eq!(revoked.reason.as_deref(), Some("Lost phone")); } @@ -609,6 +611,6 @@ async fn account_apps_remove_withdraws_the_consent() { matches!(event, DomainEvent::ConsentRevoked { client_id } if *client_id == client.id) }) .await; - assert!(matches!(&removed.actor, Actor::Cli { os_user, .. } if os_user == "test")); + assert!(matches!(removed.actor.known(), Some(Actor::Cli { os_user, .. }) if os_user == "test")); assert_eq!(removed.reason.as_deref(), Some("Impersonating app")); } diff --git a/apps/auth-service/src/clients/tests/deletion.rs b/apps/auth-service/src/clients/tests/deletion.rs index d957d282e..dd1a6f6a6 100644 --- a/apps/auth-service/src/clients/tests/deletion.rs +++ b/apps/auth-service/src/clients/tests/deletion.rs @@ -112,15 +112,15 @@ async fn deleted_clients_stay_deleted() { .await .expect("history"); assert_eq!( - (history[0].event.known(), &history[0].actor), + (history[0].event.known(), history[0].actor.known()), ( Some(&DomainEvent::ClientDeleted { client_id: client_id.clone() }), - &Actor::User { + Some(&Actor::User { user_id: alice.user_id, session_id: Some(alice.session_id), - } + }) ) ); diff --git a/apps/auth-service/src/clients/tests/registry.rs b/apps/auth-service/src/clients/tests/registry.rs index 554c0a583..49a49dbdb 100644 --- a/apps/auth-service/src/clients/tests/registry.rs +++ b/apps/auth-service/src/clients/tests/registry.rs @@ -107,7 +107,7 @@ async fn changes_apply_to_the_next_request_on_every_replica() { assert!( history .iter() - .all(|event| event.actor == operator().reading().actor) + .all(|event| event.actor.known() == Some(&operator().reading().actor)) ); let client_id = client.id.clone(); assert_eq!( diff --git a/apps/auth-service/src/deletion/tests.rs b/apps/auth-service/src/deletion/tests.rs index 241ba5d81..22923b68b 100644 --- a/apps/auth-service/src/deletion/tests.rs +++ b/apps/auth-service/src/deletion/tests.rs @@ -4,6 +4,7 @@ use super::*; use crate::{ AdminError, AdminService, + account::Viewer, jobs::AccountPurge, security::SessionError, tests::{ @@ -15,6 +16,7 @@ use axum::http::header; use serde_json::json; use sourceorigin_common::{ AnnouncementId, AuthenticationMethod, PictureId, Provider, RecoveryId, TokenId, + admin::EventSearch, clients::{ClientKind, ClientOwner}, events::{Actor, JobName, Platform, RequestOrigin, SignInFailure, UserAgentFamily}, notifications::{EmailCategory, Notification, NotificationPreference}, @@ -55,7 +57,10 @@ impl Fixture { .await .expect("history") .into_iter() - .map(|stored| (stored.event.known().cloned().expect("known"), stored.actor)) + .map(|stored| { + let actor = stored.actor.known().cloned().expect("known actor"); + (stored.event.known().cloned().expect("known"), actor) + }) .collect() } @@ -377,6 +382,16 @@ fn holds(value: &serde_json::Value, path: &[&str]) -> bool { } } +/// The document `export` streams. +async fn download(export: AccountExport) -> String { + let mut body = Vec::new(); + let mut chunks = export.stream(); + while let Some(chunk) = chunks.next().await { + body.extend_from_slice(&chunk.expect("chunk")); + } + String::from_utf8(body).expect("UTF-8") +} + /// `browser`'s user, acting from it. const fn user(browser: &Browser) -> Actor { Actor::User { @@ -420,12 +435,7 @@ async fn exports_hold_every_category_and_no_secret() { )); drop(second); // Its file name and the sections' shapes are checked in the export's own tests. - let mut body = Vec::new(); - let mut chunks = export.stream(); - while let Some(chunk) = chunks.next().await { - body.extend_from_slice(&chunk.expect("chunk")); - } - let text = String::from_utf8(body).expect("UTF-8"); + let text = download(export).await; let export: serde_json::Value = serde_json::from_str(&text).expect("JSON"); assert_eq!( export["profile"]["handle"], @@ -489,6 +499,68 @@ async fn exports_hold_every_category_and_no_secret() { ); } +/// Events whose actor a newer release recorded, of a type this one does not know +/// or a known type naming a job it does not know, fail none of the pages that +/// read them. The dashboard lists them with the actor as stored, which it shows as +/// nobody recorded and the CLI as JSON. The owner's history and export name no +/// actor. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn actors_a_newer_release_wrote_are_read() { + let fixture = Fixture::new().await; + let browser = Browser::new_account(&fixture.database).await; + let actors = [ + json!({"type": "from_a_newer_release"}), + json!({"type": "system", "job": "from_a_newer_release"}), + ]; + for actor in &actors { + fixture + .database + .events() + .insert_written_elsewhere( + browser.user_id, + "passkey_renamed", + DomainEvent::FIRST_VERSION, + &json!({"passkey_id": PasskeyId::new()}), + actor, + ) + .await + .expect("event"); + } + let search = EventSearch { + user: Some(browser.user_id), + kind: Some("passkey_renamed".into()), + ..EventSearch::default() + }; + let page = (fixture.admin.events(&operator(), search)) + .await + .expect("events"); + let listed: Vec<_> = page.events.iter().map(|event| &event.actor).collect(); + assert_eq!(listed, [&actors[1], &actors[0]]); + + let owner = browser.owner(&fixture.database).await; + let history = (fixture.account.history(&Viewer::from(&owner), None)) + .await + .expect("history"); + let history = serde_json::to_value(history.entries).expect("history"); + let export = fixture.account.export(&owner).await.expect("export"); + let export: serde_json::Value = serde_json::from_str(&download(export).await).expect("JSON"); + for (surface, entries, kind) in [ + ("history", &history, "passkey.renamed"), + ("export", &export["events"], "passkey_renamed"), + ] { + let renamed: Vec<_> = (entries.as_array().expect("entries").iter()) + .filter(|entry| entry["kind"] == kind) + .map(|entry| &entry["actor"]) + .collect(); + assert_eq!( + renamed, + [&json!(null), &json!(null)], + "{surface}: {entries}" + ); + } +} + /// Deleting needs the account's handle and a recent passkey confirmation. It signs /// every browser out, revokes every grant and leaves an account that can no longer /// sign in. diff --git a/apps/auth-service/src/emails/tests.rs b/apps/auth-service/src/emails/tests.rs index 66db1e7d8..0fd1c3c2d 100644 --- a/apps/auth-service/src/emails/tests.rs +++ b/apps/auth-service/src/emails/tests.rs @@ -370,7 +370,7 @@ async fn verification_checks_the_signed_in_account() { Some(&DomainEvent::EmailVerified { email_id: second }) ); assert!( - matches!(verified.actor, Actor::User { user_id, .. } if user_id == owner.user_id), + matches!(verified.actor.known(), Some(&Actor::User { user_id, .. }) if user_id == owner.user_id), "{:?}", verified.actor ); diff --git a/apps/auth-service/src/history/mod.rs b/apps/auth-service/src/history/mod.rs index 52664a11c..1fa1cd09b 100644 --- a/apps/auth-service/src/history/mod.rs +++ b/apps/auth-service/src/history/mod.rs @@ -70,8 +70,8 @@ pub(crate) struct HistoryItem { /// What happened: its `kind` and details. #[serde(flatten)] pub(crate) entry: E, - /// Who did it. - pub(crate) actor: HistoryActor, + /// Who did it; `None` for an actor a newer release recorded. + pub(crate) actor: Option, /// Why, as the administrator or operator who did it wrote it, while kept. pub(crate) reason: Option, /// The application involved, if any. @@ -107,7 +107,7 @@ impl HistoryItem { /// `stored`, saying what happened with `entry`. `clients` maps client IDs to /// their names. An administrator's or operator's change shows no IP address /// or device: they are the administrator's own, which only the admin views - /// show. + /// show. Neither does an actor a newer release recorded, which may be one. pub(crate) fn with( stored: &StoredEvent, clients: &BTreeMap, @@ -115,14 +115,16 @@ impl HistoryItem { ) -> Self { let client = (stored.event.known()) .and_then(DomainEvent::client_id) - .or(stored.actor.client_id()) + .or(stored.actor.known().and_then(Actor::client_id)) .map(|id| ClientView { name: clients.get(id).cloned(), id: id.clone(), }); - let actor = HistoryActor::from(&stored.actor); + let actor = stored.actor.known().map(HistoryActor::from); let (origin, erased) = match (actor, &stored.origin) { - (HistoryActor::Admin | HistoryActor::Operator, _) => (RequestOrigin::default(), false), + (Some(HistoryActor::Admin | HistoryActor::Operator) | None, _) => { + (RequestOrigin::default(), false) + } (_, Personal::Value(origin)) => (*origin, false), (_, Personal::Erased) => (RequestOrigin::default(), true), }; @@ -144,7 +146,7 @@ impl HistoryItem { /// Whether the account may report it as not theirs: what its own sessions did, /// of the kinds [`HistoryEntry::reportable`] allows. pub(crate) const fn reportable(&self) -> bool { - matches!(self.actor, HistoryActor::Account) && self.entry.reportable() + matches!(self.actor, Some(HistoryActor::Account)) && self.entry.reportable() } /// The entry `stored` shows its subject, or `None` if it shows none, as for an @@ -304,7 +306,10 @@ impl AccountService { let mut tx = self.database.begin().await?; owner.lock(&mut tx).await?; let (stored, entry) = Self::entry(tx.events(), owner.user(), event_id).await?; - let caused = matches!(stored.actor, Actor::User { user_id, .. } if user_id == owner.user()); + let caused = matches!( + stored.actor.known(), + Some(&Actor::User { user_id, .. }) if user_id == owner.user() + ); if !caused || !entry.reportable() { return Err(HistoryError::NotReportable.into()); } diff --git a/apps/auth-service/src/history/tests.rs b/apps/auth-service/src/history/tests.rs index a3152bd12..64ac89902 100644 --- a/apps/auth-service/src/history/tests.rs +++ b/apps/auth-service/src/history/tests.rs @@ -228,7 +228,13 @@ async fn events_a_newer_release_wrote_are_hidden() { let unknown = harness .database .events() - .insert_written_elsewhere(alice.user_id, "from_a_newer_release", 1, &json!({})) + .insert_written_elsewhere( + alice.user_id, + "from_a_newer_release", + 1, + &json!({}), + &json!({"type": "anonymous"}), + ) .await .expect("event"); let page = harness.page(&alice, None).await; @@ -355,7 +361,7 @@ async fn reporting_ends_other_sessions_and_every_grant() { .into_iter() .map(|stored| { ( - stored.actor, + stored.actor.known().cloned().expect("a known actor"), stored.event.known().cloned().expect("a known event"), ) }) diff --git a/apps/auth-service/src/keys/tests.rs b/apps/auth-service/src/keys/tests.rs index 53086719e..4343f6366 100644 --- a/apps/auth-service/src/keys/tests.rs +++ b/apps/auth-service/src/keys/tests.rs @@ -67,10 +67,10 @@ async fn changes(tx: &mut DatabaseTransaction<'_>, key: &KeyId) -> Vec { - Some((preference.email, stored.actor)) - } + Some(DomainEvent::NotificationPreferenceChanged(preference)) => Some(( + preference.email, + stored.actor.known().cloned().expect("known actor"), + )), _ => None, }) .collect() @@ -353,9 +354,10 @@ async fn the_sign_out_link_works_once_within_seven_days() { .expect("history") .into_iter() .filter_map(|stored| match stored.event.known() { - Some(DomainEvent::SessionRevoked { reason, .. }) => { - Some((reason.clone(), stored.actor)) - } + Some(DomainEvent::SessionRevoked { reason, .. }) => Some(( + reason.clone(), + stored.actor.known().cloned().expect("known actor"), + )), _ => None, }) .collect(); diff --git a/apps/auth-service/src/oidc/tests/app_removal.rs b/apps/auth-service/src/oidc/tests/app_removal.rs index 633aaca47..eb40ec153 100644 --- a/apps/auth-service/src/oidc/tests/app_removal.rs +++ b/apps/auth-service/src/oidc/tests/app_removal.rs @@ -42,7 +42,7 @@ async fn an_administrator_removes_an_app_with_a_reason() { user_id: admin.user_id, session_id: admin.session_id, }; - assert_eq!(stored.actor, actor); + assert_eq!(stored.actor.known(), Some(&actor)); assert_eq!(stored.reason.as_deref(), Some(reason)); } diff --git a/apps/auth-service/src/sessions/tests.rs b/apps/auth-service/src/sessions/tests.rs index e55284abe..dfae33fb0 100644 --- a/apps/auth-service/src/sessions/tests.rs +++ b/apps/auth-service/src/sessions/tests.rs @@ -139,11 +139,11 @@ async fn signing_out_one_session_ends_only_that_one() { .expect("history") .remove(0); assert_eq!( - latest.actor, - Actor::User { + latest.actor.known(), + Some(&Actor::User { user_id: laptop.user_id, session_id: Some(laptop.session_id), - } + }) ); assert_eq!( latest.event.known(), diff --git a/apps/auth-service/src/web/admin/tests/mod.rs b/apps/auth-service/src/web/admin/tests/mod.rs index 46c043790..6bff61d12 100644 --- a/apps/auth-service/src/web/admin/tests/mod.rs +++ b/apps/auth-service/src/web/admin/tests/mod.rs @@ -246,6 +246,6 @@ impl Harness { events .into_iter() .find(|stored| stored.event.known().is_some_and(&found)) - .map(|stored| stored.actor) + .and_then(|stored| stored.actor.known().cloned()) } } diff --git a/crates/database/.sqlx/query-272ffe8342df643dbd8f71220ba5e30a88fefca2ee6a5b30063554881094433e.json b/crates/database/.sqlx/query-56a009ea93354f9751267dee1f96c46d6f7b8e1c8163cbf5f12c214099398b02.json similarity index 68% rename from crates/database/.sqlx/query-272ffe8342df643dbd8f71220ba5e30a88fefca2ee6a5b30063554881094433e.json rename to crates/database/.sqlx/query-56a009ea93354f9751267dee1f96c46d6f7b8e1c8163cbf5f12c214099398b02.json index ecd74ca0c..21483f316 100644 --- a/crates/database/.sqlx/query-272ffe8342df643dbd8f71220ba5e30a88fefca2ee6a5b30063554881094433e.json +++ b/crates/database/.sqlx/query-56a009ea93354f9751267dee1f96c46d6f7b8e1c8163cbf5f12c214099398b02.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT\n e.id AS \"id: EventId\", e.occurred_at, e.kind, e.version, e.payload,\n e.actor AS \"actor: Json\",\n e.subject_user_id AS \"subject_user_id: UserId\",\n e.trace_id AS \"trace_id: TraceId\",\n p.event_id IS NOT NULL AS \"personal!\", p.client_ip AS \"client_ip?: IpAddr\",\n p.user_agent_family AS \"browser?: Browser\",\n p.platform AS \"platform?: Platform\",\n p.details AS \"details?\", p.reason AS \"reason?\"\n FROM domain_events e\n LEFT JOIN event_personal_data p ON p.event_id = e.id\n WHERE e.kind = 'audit_chain_verified'\n AND ($1 OR e.payload ->> 'keys' IS DISTINCT FROM 'given')\n ORDER BY e.occurred_at DESC\n LIMIT 1", + "query": "SELECT\n e.id AS \"id: EventId\", e.occurred_at, e.kind, e.version, e.payload,\n e.actor,\n e.subject_user_id AS \"subject_user_id: UserId\",\n e.trace_id AS \"trace_id: TraceId\",\n p.event_id IS NOT NULL AS \"personal!\", p.client_ip AS \"client_ip?: IpAddr\",\n p.user_agent_family AS \"browser?: Browser\",\n p.platform AS \"platform?: Platform\",\n p.details AS \"details?\", p.reason AS \"reason?\"\n FROM domain_events e\n LEFT JOIN event_personal_data p ON p.event_id = e.id\n WHERE e.kind = 'audit_chain_verified'\n AND ($1 OR e.payload ->> 'keys' IS DISTINCT FROM 'given')\n ORDER BY e.occurred_at DESC\n LIMIT 1", "describe": { "columns": [ { @@ -30,7 +30,7 @@ }, { "ordinal": 5, - "name": "actor: Json", + "name": "actor", "type_info": "Jsonb" }, { @@ -96,5 +96,5 @@ true ] }, - "hash": "272ffe8342df643dbd8f71220ba5e30a88fefca2ee6a5b30063554881094433e" + "hash": "56a009ea93354f9751267dee1f96c46d6f7b8e1c8163cbf5f12c214099398b02" } diff --git a/crates/database/.sqlx/query-bbd34bb4b9c0b313f31775d31d7158d943c00a90f5ca9cebad8b231cc41ce44e.json b/crates/database/.sqlx/query-a0794ef8a5630571d2fa84bbd94a66d5a3f2400ee36630e7bfe61f075724f09e.json similarity index 70% rename from crates/database/.sqlx/query-bbd34bb4b9c0b313f31775d31d7158d943c00a90f5ca9cebad8b231cc41ce44e.json rename to crates/database/.sqlx/query-a0794ef8a5630571d2fa84bbd94a66d5a3f2400ee36630e7bfe61f075724f09e.json index 34b5043e1..9ffdb87e7 100644 --- a/crates/database/.sqlx/query-bbd34bb4b9c0b313f31775d31d7158d943c00a90f5ca9cebad8b231cc41ce44e.json +++ b/crates/database/.sqlx/query-a0794ef8a5630571d2fa84bbd94a66d5a3f2400ee36630e7bfe61f075724f09e.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT\n e.id AS \"id: EventId\", e.occurred_at, e.kind, e.version, e.payload,\n e.actor AS \"actor: Json\",\n e.subject_user_id AS \"subject_user_id: UserId\",\n e.trace_id AS \"trace_id: TraceId\",\n p.event_id IS NOT NULL AS \"personal!\", p.client_ip AS \"client_ip?: IpAddr\",\n p.user_agent_family AS \"browser?: Browser\",\n p.platform AS \"platform?: Platform\",\n p.details AS \"details?\", p.reason AS \"reason?\"\n FROM domain_events e\n LEFT JOIN event_personal_data p ON p.event_id = e.id\n WHERE e.client_id = $1\n ORDER BY e.txid DESC, e.sequence DESC\n LIMIT $2", + "query": "SELECT\n e.id AS \"id: EventId\", e.occurred_at, e.kind, e.version, e.payload,\n e.actor,\n e.subject_user_id AS \"subject_user_id: UserId\",\n e.trace_id AS \"trace_id: TraceId\",\n p.event_id IS NOT NULL AS \"personal!\", p.client_ip AS \"client_ip?: IpAddr\",\n p.user_agent_family AS \"browser?: Browser\",\n p.platform AS \"platform?: Platform\",\n p.details AS \"details?\", p.reason AS \"reason?\"\n FROM domain_events e\n LEFT JOIN event_personal_data p ON p.event_id = e.id\n WHERE e.client_id = $1\n ORDER BY e.txid DESC, e.sequence DESC\n LIMIT $2", "describe": { "columns": [ { @@ -30,7 +30,7 @@ }, { "ordinal": 5, - "name": "actor: Json", + "name": "actor", "type_info": "Jsonb" }, { @@ -97,5 +97,5 @@ true ] }, - "hash": "bbd34bb4b9c0b313f31775d31d7158d943c00a90f5ca9cebad8b231cc41ce44e" + "hash": "a0794ef8a5630571d2fa84bbd94a66d5a3f2400ee36630e7bfe61f075724f09e" } diff --git a/crates/database/.sqlx/query-91e8ca711565c9e8d85627a1a20c62d5b5ec2d1913e51e811e1e6291d06253fb.json b/crates/database/.sqlx/query-a7249cae558f351ab2b3447fad7dd18489a433abf243569b0646c6632b994404.json similarity index 59% rename from crates/database/.sqlx/query-91e8ca711565c9e8d85627a1a20c62d5b5ec2d1913e51e811e1e6291d06253fb.json rename to crates/database/.sqlx/query-a7249cae558f351ab2b3447fad7dd18489a433abf243569b0646c6632b994404.json index ee97e33ac..9dccbbea3 100644 --- a/crates/database/.sqlx/query-91e8ca711565c9e8d85627a1a20c62d5b5ec2d1913e51e811e1e6291d06253fb.json +++ b/crates/database/.sqlx/query-a7249cae558f351ab2b3447fad7dd18489a433abf243569b0646c6632b994404.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT\n e.id AS \"id: EventId\", e.occurred_at, e.kind, e.version, e.payload,\n e.actor AS \"actor: Json\",\n e.subject_user_id AS \"subject_user_id: UserId\",\n e.trace_id AS \"trace_id: TraceId\",\n p.event_id IS NOT NULL AS \"personal!\", p.client_ip AS \"client_ip?: IpAddr\",\n p.user_agent_family AS \"browser?: Browser\",\n p.platform AS \"platform?: Platform\",\n p.details AS \"details?\", p.reason AS \"reason?\"\n FROM domain_events e\n LEFT JOIN event_personal_data p ON p.event_id = e.id\n WHERE ($1::uuid IS NULL OR e.subject_user_id = $1)\n AND ($2::text IS NULL OR e.kind = $2)\n AND (\n $3::uuid IS NULL\n OR (e.txid, e.sequence) < (\n SELECT txid, sequence FROM domain_events\n WHERE id = $3\n AND ($1::uuid IS NULL OR subject_user_id = $1)\n )\n )\n AND ($5::uuid IS NULL OR e.id = $5)\n AND ($7::text IS NULL OR e.kind <> $7)\n ORDER BY e.txid DESC, e.sequence DESC\n LIMIT $4 OFFSET $6", + "query": "SELECT\n e.id AS \"id: EventId\", e.occurred_at, e.kind, e.version, e.payload,\n e.actor,\n e.subject_user_id AS \"subject_user_id: UserId\",\n e.trace_id AS \"trace_id: TraceId\",\n p.event_id IS NOT NULL AS \"personal!\", p.client_ip AS \"client_ip?: IpAddr\",\n p.user_agent_family AS \"browser?: Browser\",\n p.platform AS \"platform?: Platform\",\n p.details AS \"details?\", p.reason AS \"reason?\"\n FROM domain_events e\n LEFT JOIN event_personal_data p ON p.event_id = e.id\n WHERE ($1::uuid IS NULL OR e.subject_user_id = $1)\n AND ($2::text IS NULL OR e.kind = $2)\n AND (\n $3::uuid IS NULL\n OR (e.txid, e.sequence) < (\n SELECT txid, sequence FROM domain_events\n WHERE id = $3\n AND ($1::uuid IS NULL OR subject_user_id = $1)\n )\n )\n AND ($5::uuid IS NULL OR e.id = $5)\n AND ($7::text IS NULL OR e.kind <> $7)\n ORDER BY e.txid DESC, e.sequence DESC\n LIMIT $4 OFFSET $6", "describe": { "columns": [ { @@ -30,7 +30,7 @@ }, { "ordinal": 5, - "name": "actor: Json", + "name": "actor", "type_info": "Jsonb" }, { @@ -102,5 +102,5 @@ true ] }, - "hash": "91e8ca711565c9e8d85627a1a20c62d5b5ec2d1913e51e811e1e6291d06253fb" + "hash": "a7249cae558f351ab2b3447fad7dd18489a433abf243569b0646c6632b994404" } diff --git a/crates/database/src/lib.rs b/crates/database/src/lib.rs index ecdc3e01f..bb430a09f 100644 --- a/crates/database/src/lib.rs +++ b/crates/database/src/lib.rs @@ -47,7 +47,7 @@ pub use repositories::{ LogoutRecipient, NewDelivery, PendingAddress, PendingRecovery, }, emails::{InsertUnverifiedEmail, InsertVerifiedEmail, PendingVerification, StoredEmail}, - events::{EventCursor, EventFilter, RecordedEvent, StoredEvent, Verifications}, + events::{EventCursor, EventFilter, RecordedActor, RecordedEvent, StoredEvent, Verifications}, exports::{AnnouncementRecord, IdentityRecord, NotificationRecord, SessionRecord}, federation::{ ConsumedFederationTransaction, InsertExternalIdentity, InsertFederationTransaction, diff --git a/crates/database/src/repositories/events/mod.rs b/crates/database/src/repositories/events/mod.rs index 0169a2cdb..6672900e6 100644 --- a/crates/database/src/repositories/events/mod.rs +++ b/crates/database/src/repositories/events/mod.rs @@ -64,7 +64,7 @@ pub struct StoredEvent { /// When it was recorded. pub occurred_at: DateTime, /// Who caused it. - pub actor: Actor, + pub actor: RecordedActor, /// The account it concerns, if any. The account may no longer exist. pub subject: Option, /// The trace of the request or job that recorded it, to find in telemetry. @@ -113,6 +113,36 @@ impl RecordedEvent { } } +/// Who a stored event says caused it. Like [`RecordedEvent`], a release reads +/// actors newer releases recorded: a type it does not know, or a known type +/// naming a value it does not know, such as a new [`JobName`] of an +/// [`Actor::System`]. Those read as [`Self::Unknown`] instead of failing, and each +/// reader decides what to do with them. Only reads produce one: `record` takes an +/// [`EventContext`], whose actor is an [`Actor`]. +/// +/// Serializes as stored. +/// +/// [`JobName`]: sourceorigin_common::events::JobName +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(untagged)] +pub enum RecordedActor { + /// An actor this release knows. + Known(Actor), + /// An actor a newer release recorded, as stored. + Unknown(Value), +} + +impl RecordedActor { + /// The actor, if this release knows it. + #[must_use] + pub const fn known(&self) -> Option<&Actor> { + match self { + Self::Known(actor) => Some(actor), + Self::Unknown(_) => None, + } + } +} + /// A checked `sqlx::query_as!` returning [`EventRow`]s, whose columns are written /// only here: every event column, joined with the event's personal data, from /// `domain_events e` and `event_personal_data p`. `$rest` filters and orders, @@ -123,7 +153,7 @@ macro_rules! select_events { EventRow, r#"SELECT e.id AS "id: EventId", e.occurred_at, e.kind, e.version, e.payload, - e.actor AS "actor: Json", + e.actor, e.subject_user_id AS "subject_user_id: UserId", e.trace_id AS "trace_id: TraceId", p.event_id IS NOT NULL AS "personal!", p.client_ip AS "client_ip?: IpAddr", @@ -150,8 +180,8 @@ struct EventRow { version: i16, /// The variant's data, with `"$erased"` where personal values were. payload: Value, - /// Who caused it. - actor: Json, + /// Who caused it, as [`RecordedActor`] decodes it. + actor: Value, /// The account it concerns. subject_user_id: Option, /// The trace that recorded it. @@ -175,7 +205,8 @@ impl TryFrom for StoredEvent { /// Restores the event's personal values, if they are still stored, and decodes /// it. A kind or version this release does not know reads as - /// [`RecordedEvent::Unknown`]; a known one whose payload does not decode fails. + /// [`RecordedEvent::Unknown`], and an actor as [`RecordedActor::Unknown`]; a + /// known one that does not decode fails. fn try_from(row: EventRow) -> Result { let invalid = |column: &str, source: serde_json::Error| DatabaseError::InvalidStoredData { column: column.into(), @@ -210,10 +241,14 @@ impl TryFrom for StoredEvent { data: payload, }, }; + let actor = match KindProbe::known_flat(row.actor.clone()) { + Some(actor) => RecordedActor::Known(actor.map_err(|source| invalid("actor", source))?), + None => RecordedActor::Unknown(row.actor), + }; Ok(Self { id: row.id, occurred_at: row.occurred_at, - actor: row.actor.0, + actor, subject: row.subject_user_id, trace_id: row.trace_id, event, @@ -562,8 +597,8 @@ impl EventRepository<'_> { } /// Writes an event about `subject` as another release would, with any `kind`, - /// `version` and `payload` and no personal data, for tests of what this - /// release reads back. + /// `version`, `payload` and `actor` and no personal data, for tests of what + /// this release reads back. /// /// # Errors /// @@ -575,6 +610,7 @@ impl EventRepository<'_> { kind: &str, version: i16, payload: &Value, + actor: &Value, ) -> Result { let id = EventId::new(); run!( @@ -587,7 +623,7 @@ impl EventRepository<'_> { kind, version, payload, - Json(&Actor::Anonymous) as _, + actor, subject.as_uuid(), ) )?; diff --git a/crates/database/src/repositories/events/tests.rs b/crates/database/src/repositories/events/tests.rs index 8ee495e9b..cbdbdadbc 100644 --- a/crates/database/src/repositories/events/tests.rs +++ b/crates/database/src/repositories/events/tests.rs @@ -83,7 +83,7 @@ async fn personal_data_is_stored_apart_and_erases() { record(&pool, user, linked()).await; let [stored] = <[StoredEvent; 1]>::try_from(history().await).expect("one event"); assert_eq!(stored.event, RecordedEvent::Known(linked())); - assert_eq!(stored.actor, context(user).actor); + assert_eq!(stored.actor.known(), Some(&context(user).actor)); assert_eq!(stored.origin, Personal::Value(context(user).origin)); assert_eq!(stored.reason, context(user).reason); let (event_row, personal_row): (String, String) = sqlx::query_as( @@ -195,6 +195,7 @@ async fn related_origins_are_personal_but_older_events_still_read() { "related_origin_approved", DomainEvent::FIRST_VERSION, &serde_json::json!({"client_id": client_id, "origin": origin}), + &serde_json::json!({"type": "anonymous"}), ) .await .expect("sealed event"); @@ -250,12 +251,13 @@ async fn events_a_newer_release_wrote_read_as_unknown() { let user = UserRepository::from_pool(&pool).insert_named("event").await; let mut events = EventRepository::from_pool(&pool); let data = serde_json::json!({"client_id": "deleted"}); + let anonymous = serde_json::json!({"type": "anonymous"}); for (kind, version) in [ ("from_a_newer_release", DomainEvent::FIRST_VERSION), ("passkey_added", DomainEvent::FIRST_VERSION + 1), ] { events - .insert_written_elsewhere(user, kind, version, &data) + .insert_written_elsewhere(user, kind, version, &data, &anonymous) .await .expect("event"); } @@ -281,7 +283,13 @@ async fn events_a_newer_release_wrote_read_as_unknown() { // Rolled back, so that consumers of every event never read it. let mut tx = DatabaseTransaction::new(pool.begin().await.expect("transaction")); tx.events() - .insert_written_elsewhere(user, "passkey_added", DomainEvent::FIRST_VERSION, &data) + .insert_written_elsewhere( + user, + "passkey_added", + DomainEvent::FIRST_VERSION, + &data, + &anonymous, + ) .await .expect("malformed event"); assert!(matches!( @@ -291,6 +299,60 @@ async fn events_a_newer_release_wrote_read_as_unknown() { tx.rollback().await.expect("rollback"); } +/// Actors a newer release recorded, of a type this one does not know or a known +/// type naming a job it does not know, read as unknown with their JSON. A known +/// type that does not decode still fails. +#[tokio::test] +#[ignore = "requires a disposable TEST_DATABASE_URL"] +async fn actors_a_newer_release_wrote_read_as_unknown() { + let pool = Database::test_pool().await; + let user = UserRepository::from_pool(&pool).insert_named("event").await; + let mut events = EventRepository::from_pool(&pool); + let actors = [ + serde_json::json!({"type": "from_a_newer_release"}), + serde_json::json!({"type": "system", "job": "from_a_newer_release"}), + ]; + for actor in &actors { + events + .insert_written_elsewhere( + user, + "account_exported", + DomainEvent::FIRST_VERSION, + &serde_json::json!({}), + actor, + ) + .await + .expect("event"); + } + let read: Vec<_> = events + .history_for_user(user, 10) + .await + .expect("history") + .into_iter() + .map(|stored| stored.actor) + .collect(); + let [older, newer] = actors.map(RecordedActor::Unknown); + assert_eq!(read, [newer, older]); + + // Rolled back, so that consumers of every event never read it. + let mut tx = DatabaseTransaction::new(pool.begin().await.expect("transaction")); + tx.events() + .insert_written_elsewhere( + user, + "account_exported", + DomainEvent::FIRST_VERSION, + &serde_json::json!({}), + &serde_json::json!({"type": "user"}), + ) + .await + .expect("malformed actor"); + assert!(matches!( + tx.events().history_for_user(user, 10).await, + Err(DatabaseError::InvalidStoredData { .. }) + )); + tx.rollback().await.expect("rollback"); +} + /// An alert update's note is its event's reason, so it is read while the event's /// personal data is kept, and reads as none once that is erased. #[tokio::test] diff --git a/crates/database/src/repositories/mod.rs b/crates/database/src/repositories/mod.rs index 0ec2f19cc..6d9f48ba9 100644 --- a/crates/database/src/repositories/mod.rs +++ b/crates/database/src/repositories/mod.rs @@ -136,14 +136,15 @@ repositories! { exports: ExportRepository; } -/// How decoding `{"kind": …}` alone as a stored, `kind`-tagged enum fails, which -/// tells whether this release knows the kind: a [`DomainEvent`], an [`Alert`] or a -/// [`Notification`] a newer release wrote reads as unknown, not as corrupt. Only -/// serde's derive knows the variant names, and it reports an unknown one through -/// [`serde::de::Error::unknown_variant`]. +/// How decoding some of a stored value's strings alone fails, which tells whether +/// this release knows the variants they name: a [`DomainEvent`], an [`Alert`], a +/// [`Notification`] or an [`Actor`] a newer release wrote reads as unknown, not as +/// corrupt. Only serde's derive knows the variant names, and it reports an unknown +/// one through [`serde::de::Error::unknown_variant`]. /// /// [`Alert`]: sourceorigin_common::alerts::Alert /// [`Notification`]: sourceorigin_common::notifications::Notification +/// [`Actor`]: sourceorigin_common::events::Actor #[derive(Debug, thiserror::Error)] enum KindProbe { /// The kind is no variant of this release's enum. @@ -167,11 +168,11 @@ impl serde::de::Error for KindProbe { } impl KindProbe { - /// Whether `kind` is the serde tag of a variant of this release's `T`. - fn knows(kind: &str) -> bool { - let tag = - serde::de::value::MapDeserializer::<_, Self>::new(std::iter::once(("kind", kind))); - !matches!(T::deserialize(tag), Err(Self::Unknown)) + /// Whether this release's `T` knows every variant `fields` name, each a + /// field of a stored `T` and its string value, such as its serde tag. + fn knows<'a, T: DeserializeOwned>(fields: impl Iterator) -> bool { + let fields = serde::de::value::MapDeserializer::<_, Self>::new(fields); + !matches!(T::deserialize(fields), Err(Self::Unknown)) } /// Decodes `tagged`, a stored `{"kind": …}` `T`, or returns `None` if this @@ -180,10 +181,21 @@ impl KindProbe { let known = tagged .get("kind") .and_then(Value::as_str) - .is_some_and(Self::knows::); + .is_some_and(|kind| Self::knows::(std::iter::once(("kind", kind)))); known.then(|| serde_json::from_value(tagged)) } + /// Decodes `flat`, a stored `T` whose fields are its tag and values beside + /// it, as an [`Actor`](sourceorigin_common::events::Actor)'s are, or returns + /// `None` if one of its strings names a variant this release does not know: + /// its tag, or a value such as the job of an `Actor::System`. + fn known_flat(flat: Value) -> Option> { + let strings = (flat.as_object().into_iter().flatten()) + .filter_map(|(field, value)| Some((field.as_str(), value.as_str()?))); + let known = Self::knows::(strings); + known.then(|| serde_json::from_value(flat)) + } + /// Decodes `tagged`, a `T` stored at payload `version`, if this release writes /// its kind in that version, which `version_of` tells; any other reads as /// `None`, as a newer release wrote it. A known kind at the first version, which diff --git a/crates/ui/src/settings/timeline.rs b/crates/ui/src/settings/timeline.rs index 8ea6b08b1..fad8cd25b 100644 --- a/crates/ui/src/settings/timeline.rs +++ b/crates/ui/src/settings/timeline.rs @@ -61,8 +61,8 @@ pub struct HistoryRow<'a> { pub occurred_at: DateTime, /// What happened. pub entry: &'a HistoryEntry, - /// Who did it. - pub actor: HistoryActor, + /// Who did it; `None` for an actor this release does not know. + pub actor: Option, /// Whether the account may report it as not theirs, as the service decides. pub reportable: bool, /// Why, as the administrator or operator who did it wrote it. @@ -280,7 +280,10 @@ impl HistoryRow<'_> { | HistoryEntry::RecoveryStarted | HistoryEntry::Recovered { .. } | HistoryEntry::DeletionScheduled { .. } - ) || matches!(self.actor, HistoryActor::Admin | HistoryActor::Operator) + ) || matches!( + self.actor, + Some(HistoryActor::Admin | HistoryActor::Operator) + ) } /// From where and through which application, after its time. @@ -301,11 +304,11 @@ impl HistoryRow<'_> { /// Who did it, if not the account itself, and why, if they said. pub(crate) fn by(&self) -> Option { let actor = match self.actor { - HistoryActor::Admin => "By a SourceOrigin administrator", - HistoryActor::Operator => "By a SourceOrigin operator", - HistoryActor::Client => "By an app", - HistoryActor::System => "Automatically by SourceOrigin", - HistoryActor::Account | HistoryActor::Anonymous => return None, + Some(HistoryActor::Admin) => "By a SourceOrigin administrator", + Some(HistoryActor::Operator) => "By a SourceOrigin operator", + Some(HistoryActor::Client) => "By an app", + Some(HistoryActor::System) => "Automatically by SourceOrigin", + Some(HistoryActor::Account | HistoryActor::Anonymous) | None => return None, }; Some(match self.reason { Some(reason) => format!("{actor}: “{reason}”"), @@ -600,7 +603,7 @@ mod tests { id: EventId::new(), occurred_at: Utc::now(), entry: &scheduled, - actor: HistoryActor::Account, + actor: Some(HistoryActor::Account), reportable: false, reason: None, client: None, diff --git a/docs/dev/architecture/database.md b/docs/dev/architecture/database.md index 7c46038b7..9d3f4d46c 100644 --- a/docs/dev/architecture/database.md +++ b/docs/dev/architecture/database.md @@ -405,9 +405,19 @@ unknown. Adding a field is not one, since older releases ignore fields they do n know, but the field must be an `Option` or `#[serde(default)]`, so that the new release still reads the rows already stored. -Closed vocabularies stored in other columns, such as `AccountStatus` and the -`JobName` of an `Actor::System`, have no such tolerance: a release fails to decode -a value it does not know. Add the value in one release that never writes it, and +An event's actor is read by the same rule. Reads return `StoredEvent.actor` as a +`RecordedActor`: `Known(Actor)`, or `Unknown(Value)` with the stored JSON when +this release does not know the actor's `type` or a value beside it, such as the +`JobName` of an `Actor::System`. The admin events API lists it as stored, which +the dashboard shows as nobody recorded and the CLI as its JSON. The security +history and the account export show its entries with no actor, IP address or +device, since it may be an administrator. `record` takes an `Actor`, so a +release never writes an unknown one, and an actor of a known type that does not +decode, such as a `user` with no `user_id`, is still +`DatabaseError::InvalidStoredData`. + +Closed vocabularies stored in other columns, such as `AccountStatus`, have no +such tolerance: a release fails to decode a value it does not know. Add the value in one release that never writes it, and start writing it in a later one, so the release a deploy or rollback runs beside always reads it. From 9487789c5dfd8bf78602397167256c828dc97892 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 14:55:23 +0100 Subject: [PATCH 2/2] fix(auth): history and export hide an unknown actor's origin, tested with one recorded Review follow-ups: the test gives the unknown actors' events a recorded IP address and device and checks the history and export show neither, through an optional origin on insert_written_elsewhere that shares record's personal-data insert. known_flat borrows the stored actor instead of cloning it on every read. The database docs name alert_updates.author as still strict (#701), and the history fields say an unknown actor's origin is hidden. --- apps/auth-service/src/admin/tests/accounts.rs | 1 + apps/auth-service/src/deletion/tests.rs | 26 ++++++++------ apps/auth-service/src/history/mod.rs | 6 ++-- apps/auth-service/src/history/tests.rs | 1 + .../database/src/repositories/events/mod.rs | 35 ++++++++++++++----- .../database/src/repositories/events/tests.rs | 6 +++- crates/database/src/repositories/mod.rs | 5 ++- docs/dev/architecture/database.md | 10 +++--- 8 files changed, 61 insertions(+), 29 deletions(-) diff --git a/apps/auth-service/src/admin/tests/accounts.rs b/apps/auth-service/src/admin/tests/accounts.rs index 7ddffbdb2..e9e7623a3 100644 --- a/apps/auth-service/src/admin/tests/accounts.rs +++ b/apps/auth-service/src/admin/tests/accounts.rs @@ -199,6 +199,7 @@ async fn events_a_newer_release_wrote_are_listed() { 1, &data, &json!({"type": "anonymous"}), + None, ) .await .expect("event"); diff --git a/apps/auth-service/src/deletion/tests.rs b/apps/auth-service/src/deletion/tests.rs index 22923b68b..3433f1d8b 100644 --- a/apps/auth-service/src/deletion/tests.rs +++ b/apps/auth-service/src/deletion/tests.rs @@ -503,7 +503,7 @@ async fn exports_hold_every_category_and_no_secret() { /// or a known type naming a job it does not know, fail none of the pages that /// read them. The dashboard lists them with the actor as stored, which it shows as /// nobody recorded and the CLI as JSON. The owner's history and export name no -/// actor. +/// actor, and show no IP address or device, as the actor may be an administrator. #[tokio::test] #[ignore = "requires TEST_DATABASE_URL"] async fn actors_a_newer_release_wrote_are_read() { @@ -513,20 +513,29 @@ async fn actors_a_newer_release_wrote_are_read() { json!({"type": "from_a_newer_release"}), json!({"type": "system", "job": "from_a_newer_release"}), ]; + let origin = RequestOrigin { + client_ip: Some([192, 0, 2, 7].into()), + user_agent_family: Some(UserAgentFamily { + browser: sourceorigin_common::events::Browser::Firefox, + platform: Platform::Linux, + }), + }; + // Personal data is only recorded in its event's transaction. + let mut tx = fixture.database.begin().await.expect("transaction"); for actor in &actors { - fixture - .database - .events() + tx.events() .insert_written_elsewhere( browser.user_id, "passkey_renamed", DomainEvent::FIRST_VERSION, &json!({"passkey_id": PasskeyId::new()}), actor, + Some(&origin), ) .await .expect("event"); } + tx.commit().await.expect("commit"); let search = EventSearch { user: Some(browser.user_id), kind: Some("passkey_renamed".into()), @@ -551,13 +560,10 @@ async fn actors_a_newer_release_wrote_are_read() { ] { let renamed: Vec<_> = (entries.as_array().expect("entries").iter()) .filter(|entry| entry["kind"] == kind) - .map(|entry| &entry["actor"]) + .map(|entry| (&entry["actor"], &entry["ip"], &entry["device"])) .collect(); - assert_eq!( - renamed, - [&json!(null), &json!(null)], - "{surface}: {entries}" - ); + let unnamed = (&json!(null), &json!(null), &json!(null)); + assert_eq!(renamed, [unnamed, unnamed], "{surface}: {entries}"); } } diff --git a/apps/auth-service/src/history/mod.rs b/apps/auth-service/src/history/mod.rs index 1fa1cd09b..f076b8b04 100644 --- a/apps/auth-service/src/history/mod.rs +++ b/apps/auth-service/src/history/mod.rs @@ -77,11 +77,11 @@ pub(crate) struct HistoryItem { /// The application involved, if any. pub(crate) client: Option, /// The request's IP address, while kept; never an administrator's or - /// operator's. + /// operator's, nor an actor's a newer release recorded. pub(crate) ip: Option, /// The request's browser and platform, while kept; never an administrator's - /// or operator's. Entries recorded before platforms were have `other` for - /// theirs. + /// or operator's, nor an actor's a newer release recorded. Entries recorded + /// before platforms were have `other` for theirs. pub(crate) device: Option, /// Whether retention or a purge deleted the IP address and device. pub(crate) erased: bool, diff --git a/apps/auth-service/src/history/tests.rs b/apps/auth-service/src/history/tests.rs index 64ac89902..2477607a0 100644 --- a/apps/auth-service/src/history/tests.rs +++ b/apps/auth-service/src/history/tests.rs @@ -234,6 +234,7 @@ async fn events_a_newer_release_wrote_are_hidden() { 1, &json!({}), &json!({"type": "anonymous"}), + None, ) .await .expect("event"); diff --git a/crates/database/src/repositories/events/mod.rs b/crates/database/src/repositories/events/mod.rs index 6672900e6..035195388 100644 --- a/crates/database/src/repositories/events/mod.rs +++ b/crates/database/src/repositories/events/mod.rs @@ -241,7 +241,7 @@ impl TryFrom for StoredEvent { data: payload, }, }; - let actor = match KindProbe::known_flat(row.actor.clone()) { + let actor = match KindProbe::known_flat(&row.actor) { Some(actor) => RecordedActor::Known(actor.map_err(|source| invalid("actor", source))?), None => RecordedActor::Unknown(row.actor), }; @@ -346,7 +346,6 @@ impl EventRepository<'_> { serde_json::from_value(serde_json::to_value(event).map_err(serialization)?) .map_err(serialization)?; let details = PersonalDetails::extract(&mut data); - let family = context.origin.user_agent_family; let id = EventId::new(); run!( self, @@ -373,6 +372,21 @@ impl EventRepository<'_> { Telemetry::current_trace_id().map(String::from), ) )?; + self.insert_personal(id, &context.origin, &details, context.reason.as_deref()) + .await?; + Ok(id) + } + + /// Writes the personal data of the event `id`: where its request came from, + /// its payload's personal values and its reason. + async fn insert_personal( + &mut self, + id: EventId, + origin: &RequestOrigin, + details: &PersonalDetails, + reason: Option<&str>, + ) -> Result<(), DatabaseError> { + let family = origin.user_agent_family; run!( self, execute, @@ -381,14 +395,14 @@ impl EventRepository<'_> { event_id, client_ip, user_agent_family, platform, details, reason ) VALUES ($1, $2, $3, $4, $5, $6)", id.as_uuid(), - context.origin.client_ip as _, + origin.client_ip as _, family.map(|family| family.browser.as_str()), family.map(|family| family.platform.as_str()), - Json(&details) as _, - context.reason.as_deref(), + Json(details) as _, + reason, ) )?; - Ok(id) + Ok(()) } /// Lists the events concerning an account, newest first, for its security history. @@ -597,8 +611,9 @@ impl EventRepository<'_> { } /// Writes an event about `subject` as another release would, with any `kind`, - /// `version`, `payload` and `actor` and no personal data, for tests of what - /// this release reads back. + /// `version`, `payload` and `actor`, for tests of what this release reads + /// back. It keeps `origin` as its personal data, or none without one; personal + /// data is only recorded with its event, so pass `origin` in a transaction. /// /// # Errors /// @@ -611,6 +626,7 @@ impl EventRepository<'_> { version: i16, payload: &Value, actor: &Value, + origin: Option<&RequestOrigin>, ) -> Result { let id = EventId::new(); run!( @@ -627,6 +643,9 @@ impl EventRepository<'_> { subject.as_uuid(), ) )?; + if let Some(origin) = origin { + (self.insert_personal(id, origin, &PersonalDetails::default(), None)).await?; + } Ok(id) } } diff --git a/crates/database/src/repositories/events/tests.rs b/crates/database/src/repositories/events/tests.rs index cbdbdadbc..8729e43cd 100644 --- a/crates/database/src/repositories/events/tests.rs +++ b/crates/database/src/repositories/events/tests.rs @@ -196,6 +196,7 @@ async fn related_origins_are_personal_but_older_events_still_read() { DomainEvent::FIRST_VERSION, &serde_json::json!({"client_id": client_id, "origin": origin}), &serde_json::json!({"type": "anonymous"}), + None, ) .await .expect("sealed event"); @@ -257,7 +258,7 @@ async fn events_a_newer_release_wrote_read_as_unknown() { ("passkey_added", DomainEvent::FIRST_VERSION + 1), ] { events - .insert_written_elsewhere(user, kind, version, &data, &anonymous) + .insert_written_elsewhere(user, kind, version, &data, &anonymous, None) .await .expect("event"); } @@ -289,6 +290,7 @@ async fn events_a_newer_release_wrote_read_as_unknown() { DomainEvent::FIRST_VERSION, &data, &anonymous, + None, ) .await .expect("malformed event"); @@ -320,6 +322,7 @@ async fn actors_a_newer_release_wrote_read_as_unknown() { DomainEvent::FIRST_VERSION, &serde_json::json!({}), actor, + None, ) .await .expect("event"); @@ -343,6 +346,7 @@ async fn actors_a_newer_release_wrote_read_as_unknown() { DomainEvent::FIRST_VERSION, &serde_json::json!({}), &serde_json::json!({"type": "user"}), + None, ) .await .expect("malformed actor"); diff --git a/crates/database/src/repositories/mod.rs b/crates/database/src/repositories/mod.rs index 6d9f48ba9..fb452b449 100644 --- a/crates/database/src/repositories/mod.rs +++ b/crates/database/src/repositories/mod.rs @@ -189,11 +189,10 @@ impl KindProbe { /// it, as an [`Actor`](sourceorigin_common::events::Actor)'s are, or returns /// `None` if one of its strings names a variant this release does not know: /// its tag, or a value such as the job of an `Actor::System`. - fn known_flat(flat: Value) -> Option> { + fn known_flat(flat: &Value) -> Option> { let strings = (flat.as_object().into_iter().flatten()) .filter_map(|(field, value)| Some((field.as_str(), value.as_str()?))); - let known = Self::knows::(strings); - known.then(|| serde_json::from_value(flat)) + Self::knows::(strings).then(|| T::deserialize(flat)) } /// Decodes `tagged`, a `T` stored at payload `version`, if this release writes diff --git a/docs/dev/architecture/database.md b/docs/dev/architecture/database.md index 9d3f4d46c..fe7bac2ba 100644 --- a/docs/dev/architecture/database.md +++ b/docs/dev/architecture/database.md @@ -416,10 +416,12 @@ release never writes an unknown one, and an actor of a known type that does not decode, such as a `user` with no `user_id`, is still `DatabaseError::InvalidStoredData`. -Closed vocabularies stored in other columns, such as `AccountStatus`, have no -such tolerance: a release fails to decode a value it does not know. Add the value in one release that never writes it, and -start writing it in a later one, so the release a deploy or rollback runs beside -always reads it. +Closed vocabularies stored in other columns, such as `AccountStatus` and the +actor in `alert_updates.author`, have no such tolerance: a release fails to +decode a value it does not know +([#701](https://github.com/sourceorigin-dev/sourceorigin/issues/701)). Add the +value in one release that never writes it, and start writing it in a later one, +so the release a deploy or rollback runs beside always reads it. ### Personal data