diff --git a/README.md b/README.md index fc3b004ea..86fb502df 100644 --- a/README.md +++ b/README.md @@ -258,6 +258,7 @@ just auth user restore alice --reason "Changed their mind" just auth session revoke # one session, as `user show` lists it just auth session revoke-all alice # every session of the account just auth audit list --user alice --kind session_revoked +just auth audit list --user alice --views # with administrators' views of the account just auth audit verify # recompute the tamper-evident chain just auth account alice passkeys list # the account's settings, as its owner sees them just auth account alice name set "Alice B" --reason "Asked by email" @@ -285,8 +286,8 @@ just auth account alice apps remove --reason "Impersonating app" sessions, connected apps and the security history, with the owner's own operations. It never adds a way to sign in or an address. Every change needs `--reason`, which the owner sees in - their history; reads are recorded as views, which only the audit shows, not the - owner. See + their history; reads are recorded as views, once an hour per operator, which + only the audit shows, not the owner. See [surfaces.md](docs/architecture/surfaces.md#changing-an-account-on-its-owners-behalf) for what is shared. - `user recover` is for an owner who lost every passkey. It signs the account diff --git a/apps/auth-service/src/account/subject.rs b/apps/auth-service/src/account/subject.rs index 579e40122..3feeda2f5 100644 --- a/apps/auth-service/src/account/subject.rs +++ b/apps/auth-service/src/account/subject.rs @@ -11,11 +11,10 @@ use axum::{ }; use piquel_common::{ SessionId, UserId, - events::{DomainEvent, EventContext, RevocationReason}, + events::{EventContext, RevocationReason}, }; use piquel_repository::{Database, DatabaseTransaction, SessionScope, StoredSession}; use std::ops::Deref; -use tokio::sync::OnceCell; /// The signed-in owner of an account, acting through their browser session. Its /// fields are private and only the extractors and [`Self::resolve`] build one, @@ -83,10 +82,8 @@ pub(crate) struct ConfirmedSubject(Subject); enum Reading { /// The account's own user, signed in with this session. Owner(SessionId), - /// An administrator or operator, and their view of the account once - /// recorded: once per [`Viewer`], so a page reading several settings records - /// one view. - Operator(Operator, OnceCell<()>), + /// An administrator or operator. + Operator(Operator), } impl Owner { @@ -307,7 +304,7 @@ impl Viewer { pub(crate) const fn operator(user: UserId, operator: Operator) -> Self { Self { user, - by: Reading::Operator(operator, OnceCell::const_new()), + by: Reading::Operator(operator), } } @@ -327,27 +324,16 @@ impl Viewer { /// Authorizes a read before it reads. An administrator must still hold their /// rights and session, signed in with a passkey, as every admin read requires /// ([`Operator::authorize_read`]), and an administrator's or operator's - /// first read through this viewer is recorded as a view, as `user show` is, - /// since settings hold personal data. The extractor already checked an - /// owner's session, and an owner's reads of their own are not recorded. + /// read is recorded as a view, as `user show` is, since settings hold personal + /// data: once an hour ([`Operator::record_view`]), so a page reading several + /// settings records one. The extractor already checked an owner's session, + /// and an owner's reads of their own are not recorded. pub(crate) async fn authorize(&self, database: &Database) -> Result<(), AccountError> { - if let Reading::Operator(operator, viewed) = &self.by { + if let Reading::Operator(operator) = &self.by { operator.authorize_read(database).await?; - // Reads at once wait for the first to record; a failed record leaves - // the next read to try again. - viewed - .get_or_try_init(|| async { - let mut tx = database.begin().await?; - tx.record( - &operator.context(), - Some(self.user), - DomainEvent::AccountViewed {}, - ) - .await?; - tx.commit().await?; - Ok::<_, AccountError>(()) - }) - .await?; + let mut tx = database.begin().await?; + operator.record_view(&mut tx, self.user).await?; + tx.commit().await?; } Ok(()) } diff --git a/apps/auth-service/src/account/tests.rs b/apps/auth-service/src/account/tests.rs index 00226c634..dbfba15ce 100644 --- a/apps/auth-service/src/account/tests.rs +++ b/apps/auth-service/src/account/tests.rs @@ -356,8 +356,9 @@ async fn every_settings_read_checks_its_administrator() { } /// An administrator's read shows every session, none of them theirs, and is -/// recorded as a view of the account, by them: one per viewer, so a page reading -/// several settings records one view. +/// recorded as a view of the account, by them: once an hour, so a page reading +/// several settings, and its reload, record one view. Another administrator's +/// reads record their own. #[tokio::test] #[ignore = "requires TEST_DATABASE_URL"] async fn administrators_reads_are_recorded_as_views() { @@ -373,6 +374,11 @@ async fn administrators_reads_are_recorded_as_views() { [(target.session_id, false)] ); fixture.service.passkeys(&viewer).await.expect("passkeys"); + let reload = Viewer::operator(target.user_id, fixture.operator(Duration::zero())); + fixture.service.passkeys(&reload).await.expect("reload"); + let other = fixture.harness.admin().await; + let other = Viewer::operator(target.user_id, operator(other, Utc::now())); + fixture.service.passkeys(&other).await.expect("other admin"); let history = fixture .harness .database @@ -384,9 +390,10 @@ async fn administrators_reads_are_recorded_as_views() { .iter() .filter(|stored| stored.event.known() == Some(&DomainEvent::AccountViewed {})) .collect(); - let [view] = views.as_slice() else { - panic!("one view for two reads: {views:?}"); + let [other, view] = views.as_slice() else { + panic!("one view per administrator: {views:?}"); }; + assert_ne!(other.actor, view.actor); assert_eq!( view.actor, Actor::Admin { diff --git a/apps/auth-service/src/admin/operator.rs b/apps/auth-service/src/admin/operator.rs index 3ac06c7e6..cb6490ffc 100644 --- a/apps/auth-service/src/admin/operator.rs +++ b/apps/auth-service/src/admin/operator.rs @@ -7,11 +7,11 @@ use chrono::{DateTime, Duration, Utc}; use piquel_common::{ SessionId, UserId, config::{ConfigurationError, Variable}, - events::{Actor, EventContext, RequestOrigin}, + events::{Actor, DomainEvent, EventContext, RequestOrigin}, protocol::{claims::Acr, step_up::StepUpRequirement}, }; use piquel_repository::{ - Database, DatabaseTransaction, SessionAuthentication, StoredSession, StoredUser, + Database, DatabaseError, DatabaseTransaction, SessionAuthentication, StoredSession, StoredUser, }; /// The operating system user running a command, recorded on the events it causes. @@ -30,6 +30,10 @@ const PASSKEY: StepUpRequirement = StepUpRequirement { }; /// A passkey confirmation recent enough for a mutation. const RECENT_PASSKEY: StepUpRequirement = StepUpRequirement::passkey_within(CONFIRMATION_MAX_AGE); +/// How long one recorded view of an account covers the same viewer's later reads +/// of it, so an investigation reloading the account's pages records one view an +/// hour, not one per page. +const VIEW_WINDOW: Duration = Duration::hours(1); /// Who runs an administrative operation: an administrator through the admin /// dashboard, or an operator at the command line. @@ -97,6 +101,28 @@ impl Operator { } } + /// Records in `tx` that this operator viewed `user_id`'s account, which holds + /// personal data, unless they already did, in this same session, within + /// [`VIEW_WINDOW`]. Two reads at once may both record; a page's reads run one + /// after another. + pub(crate) async fn record_view( + &self, + tx: &mut DatabaseTransaction<'_>, + user_id: UserId, + ) -> Result<(), DatabaseError> { + let context = self.context(); + let event = DomainEvent::AccountViewed {}; + let since = Utc::now() - VIEW_WINDOW; + if !tx + .events() + .caused_since(&context.actor, user_id, event.kind(), since) + .await? + { + tx.record(&context, Some(user_id), event).await?; + } + Ok(()) + } + /// Whether the operator's passkey confirmation will still meet a mutation's /// requirement `ahead` from now, so that a form shown now can still be /// submitted. The terminal needs none. diff --git a/apps/auth-service/src/admin/service/accounts.rs b/apps/auth-service/src/admin/service/accounts.rs index 79294c528..90c25830d 100644 --- a/apps/auth-service/src/admin/service/accounts.rs +++ b/apps/auth-service/src/admin/service/accounts.rs @@ -122,12 +122,7 @@ impl AdminService { }, user: user.into(), }; - tx.record( - &operator.context(), - Some(user_id), - DomainEvent::AccountViewed {}, - ) - .await?; + operator.record_view(&mut tx, user_id).await?; tx.commit().await?; Ok(detail) } diff --git a/apps/auth-service/src/admin/service/events.rs b/apps/auth-service/src/admin/service/events.rs index 9ac4644ef..b9efda6ed 100644 --- a/apps/auth-service/src/admin/service/events.rs +++ b/apps/auth-service/src/admin/service/events.rs @@ -25,8 +25,10 @@ impl AdminService { search: EventSearch, ) -> Result { operator.authorize_read(&self.database).await?; + let viewed = DomainEvent::AccountViewed {}.kind(); let mut filter = EventFilter { subject: search.user, + except_kind: (!search.views && search.kind.is_none()).then(|| viewed.to_owned()), kind: search.kind, ..EventFilter::default() }; diff --git a/apps/auth-service/src/admin/service/recovery.rs b/apps/auth-service/src/admin/service/recovery.rs index 5cf58d4bf..5082df7e9 100644 --- a/apps/auth-service/src/admin/service/recovery.rs +++ b/apps/auth-service/src/admin/service/recovery.rs @@ -161,12 +161,7 @@ impl AdminService { let mut tx = self.database.begin().await?; let since = Utc::now() - PROBATION; let recent = tx.recoveries().recent(user_id, since).await?; - tx.record( - &operator.context(), - Some(user_id), - DomainEvent::AccountViewed {}, - ) - .await?; + operator.record_view(&mut tx, user_id).await?; tx.commit().await?; Ok(recent) } diff --git a/apps/auth-service/src/admin/tests/accounts.rs b/apps/auth-service/src/admin/tests/accounts.rs index c5a8f93cf..607b0966b 100644 --- a/apps/auth-service/src/admin/tests/accounts.rs +++ b/apps/auth-service/src/admin/tests/accounts.rs @@ -4,6 +4,35 @@ use super::*; use piquel_common::events::RevocationReason; use serde_json::json; +/// The event list shows changes: an administrator's views of an account only +/// when asked for. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn views_are_listed_only_when_asked_for() { + let harness = Harness::new().await; + let service = harness.service(); + let administrator = operator(harness.admin().await, Utc::now()); + let user = harness.account().await.user_id; + service.view_user(&administrator, user).await.expect("view"); + let kinds = async |views| { + let search = EventSearch { + user: Some(user), + views, + ..EventSearch::default() + }; + let page = service + .events(&administrator, search) + .await + .expect("events"); + page.events + .into_iter() + .map(|event| event.event["kind"].clone()) + .collect::>() + }; + assert!(!kinds(false).await.contains(&json!("account_viewed"))); + assert!(kinds(true).await.contains(&json!("account_viewed"))); +} + /// Disabling an account ends its sessions at once and records why; enabling it /// restores it, and both show in the events, attributed to the administrator. #[tokio::test] @@ -77,7 +106,7 @@ async fn disabling_ends_sessions_and_is_recorded() { EventSearch { user: Some(user.user_id), kind: Some("account_disabled".into()), - page: None, + ..EventSearch::default() }, ) .await diff --git a/apps/auth-service/src/cli/audit.rs b/apps/auth-service/src/cli/audit.rs index 32e9ec260..6e407e952 100644 --- a/apps/auth-service/src/cli/audit.rs +++ b/apps/auth-service/src/cli/audit.rs @@ -139,6 +139,10 @@ pub(super) struct ListEvents { /// Only events of this kind, e.g. `session_revoked`. #[arg(long)] kind: Option, + /// List administrators' and operators' views of accounts too, which are left + /// out unless `--kind account_viewed` asks for them. + #[arg(long)] + views: bool, /// The page to list, counting from 1 at the newest events. #[arg(long)] page: Option, @@ -157,6 +161,7 @@ impl ListEvents { let search = EventSearch { user, kind: self.kind, + views: self.views, page: self.page, }; self.output.print( diff --git a/apps/auth-service/src/web/admin/lists.rs b/apps/auth-service/src/web/admin/lists.rs index e1be60469..0b35dca5d 100644 --- a/apps/auth-service/src/web/admin/lists.rs +++ b/apps/auth-service/src/web/admin/lists.rs @@ -6,7 +6,7 @@ use piquel_common::{ admin::{Event, EventSearch}, events::Actor, }; -use piquel_ui::{EventRow, Pager, Query}; +use piquel_ui::{Checkbox, EventRow, Pager, Query}; use topcoat::{ Result, context::Cx, @@ -21,11 +21,14 @@ struct EventsQuery { user: Option, /// Only events of this kind. kind: Option, + /// Whether administrators' views of accounts are listed too. + views: Option, /// The page wanted, counting from 1. page: Option, } -/// `/events`: domain events, newest first, filtered by account and kind. +/// `/events`: domain events, newest first, filtered by account and kind, with +/// administrators' views of accounts only when asked for. #[route(GET "/events")] pub(super) async fn events(cx: &Cx) -> Result { let admin = App::admin(cx).await?; @@ -33,6 +36,7 @@ pub(super) async fn events(cx: &Cx) -> Result { let filter = EventSearch { user: query.user, kind: query.kind.clone(), + views: query.views.is_some(), page: query.page, }; let found = App::of(cx) @@ -47,9 +51,16 @@ pub(super) async fn events(cx: &Cx) -> Result { } .on(&action) })?; + let toggle_views = EventSearch { + views: !filter.views, + page: None, + ..filter.clone() + } + .on(&action)?; let rows = &App::event_rows(cx, &found.events); - let (action, user, kind, pager) = ( + let (action, toggle_views, user, kind, pager) = ( &action, + &toggle_views, filter.user.map(|user| user.to_string()), filter.kind.as_deref(), &pager, @@ -59,6 +70,8 @@ pub(super) async fn events(cx: &Cx) -> Result { action: action.as_str(), user: user, kind: kind, + views: filter.views, + toggle_views: toggle_views.as_str(), rows: rows, pages: pager, ) diff --git a/crates/common/src/admin.rs b/crates/common/src/admin.rs index ffe9056b5..769e9cd8b 100644 --- a/crates/common/src/admin.rs +++ b/crates/common/src/admin.rs @@ -323,6 +323,10 @@ pub struct EventSearch { /// Only events of this kind, e.g. `session_revoked`. #[serde(default, skip_serializing_if = "Option::is_none")] pub kind: Option, + /// Whether administrators' views of accounts are listed too. They are left + /// out unless asked for, here or as the `kind`, so the list shows changes. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub views: bool, /// The page wanted, counting from 1 at the newest; the first when absent. #[serde(default, skip_serializing_if = "Option::is_none")] pub page: Option, diff --git a/crates/database/.sqlx/query-0448dbb57f6793276820a304f03049c5626f1b0b3dda24acc79027ada2210203.json b/crates/database/.sqlx/query-0448dbb57f6793276820a304f03049c5626f1b0b3dda24acc79027ada2210203.json new file mode 100644 index 000000000..58ae3b6c9 --- /dev/null +++ b/crates/database/.sqlx/query-0448dbb57f6793276820a304f03049c5626f1b0b3dda24acc79027ada2210203.json @@ -0,0 +1,25 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (\n SELECT 1 FROM domain_events\n WHERE kind = $1 AND occurred_at >= $2 AND subject_user_id = $3\n AND actor = $4\n ) AS \"caused!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "caused!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Timestamptz", + "Uuid", + "Jsonb" + ] + }, + "nullable": [ + null + ] + }, + "hash": "0448dbb57f6793276820a304f03049c5626f1b0b3dda24acc79027ada2210203" +} diff --git a/crates/database/.sqlx/query-62e2741405b6723c771f2dc5330892c66240420e28eabb7332e8c699770b8a5b.json b/crates/database/.sqlx/query-40b8beca8d5dbb61c48256f3bb7ef4f52b086fd440b6c80263a6bba18d8f0a95.json similarity index 75% rename from crates/database/.sqlx/query-62e2741405b6723c771f2dc5330892c66240420e28eabb7332e8c699770b8a5b.json rename to crates/database/.sqlx/query-40b8beca8d5dbb61c48256f3bb7ef4f52b086fd440b6c80263a6bba18d8f0a95.json index 19c6f5dec..c01736611 100644 --- a/crates/database/.sqlx/query-62e2741405b6723c771f2dc5330892c66240420e28eabb7332e8c699770b8a5b.json +++ b/crates/database/.sqlx/query-40b8beca8d5dbb61c48256f3bb7ef4f52b086fd440b6c80263a6bba18d8f0a95.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT count(*) AS \"count!\"\n FROM domain_events\n WHERE ($1::uuid IS NULL OR subject_user_id = $1)\n AND ($2::text IS NULL OR kind = $2)", + "query": "SELECT count(*) AS \"count!\"\n FROM domain_events\n WHERE ($1::uuid IS NULL OR subject_user_id = $1)\n AND ($2::text IS NULL OR kind = $2)\n AND ($3::text IS NULL OR kind <> $3)", "describe": { "columns": [ { @@ -12,6 +12,7 @@ "parameters": { "Left": [ "Uuid", + "Text", "Text" ] }, @@ -19,5 +20,5 @@ null ] }, - "hash": "62e2741405b6723c771f2dc5330892c66240420e28eabb7332e8c699770b8a5b" + "hash": "40b8beca8d5dbb61c48256f3bb7ef4f52b086fd440b6c80263a6bba18d8f0a95" } diff --git a/crates/database/.sqlx/query-aed5f8e218471c67765fcb0d02da397eb01375e2b162ee0f2758174a59130beb.json b/crates/database/.sqlx/query-4833ab3d27cf74b6d52868bfce8e3b9b17eb8667bfb707be788e04e9f4065a95.json similarity index 92% rename from crates/database/.sqlx/query-aed5f8e218471c67765fcb0d02da397eb01375e2b162ee0f2758174a59130beb.json rename to crates/database/.sqlx/query-4833ab3d27cf74b6d52868bfce8e3b9b17eb8667bfb707be788e04e9f4065a95.json index 5c5cb98dd..d816d9a65 100644 --- a/crates/database/.sqlx/query-aed5f8e218471c67765fcb0d02da397eb01375e2b162ee0f2758174a59130beb.json +++ b/crates/database/.sqlx/query-4833ab3d27cf74b6d52868bfce8e3b9b17eb8667bfb707be788e04e9f4065a95.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT\n e.id AS \"id: EventId\", e.txid::text::bigint AS \"txid!\", e.sequence,\n e.occurred_at, e.kind, e.version, e.payload, 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.sequence < (\n SELECT 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 ORDER BY e.sequence DESC\n LIMIT $4 OFFSET $6", + "query": "SELECT\n e.id AS \"id: EventId\", e.txid::text::bigint AS \"txid!\", e.sequence,\n e.occurred_at, e.kind, e.version, e.payload, 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.sequence < (\n SELECT 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.sequence DESC\n LIMIT $4 OFFSET $6", "describe": { "columns": [ { @@ -91,7 +91,8 @@ "Uuid", "Int8", "Uuid", - "Int8" + "Int8", + "Text" ] }, "nullable": [ @@ -113,5 +114,5 @@ true ] }, - "hash": "aed5f8e218471c67765fcb0d02da397eb01375e2b162ee0f2758174a59130beb" + "hash": "4833ab3d27cf74b6d52868bfce8e3b9b17eb8667bfb707be788e04e9f4065a95" } diff --git a/crates/database/src/repositories/events/mod.rs b/crates/database/src/repositories/events/mod.rs index 6177d88ec..a1711dac7 100644 --- a/crates/database/src/repositories/events/mod.rs +++ b/crates/database/src/repositories/events/mod.rs @@ -43,6 +43,8 @@ pub struct EventFilter { /// Only events of this kind, the serde tag of a [`DomainEvent`] variant, e.g. /// `session_revoked`. pub kind: Option, + /// No events of this kind, e.g. `account_viewed`. + pub except_kind: Option, /// Only events recorded before this one, to page through older events. With a /// `subject`, the cursor must be one of that account's events. pub before: Option, @@ -391,9 +393,11 @@ impl EventRepository<'_> { r#"SELECT count(*) AS "count!" FROM domain_events WHERE ($1::uuid IS NULL OR subject_user_id = $1) - AND ($2::text IS NULL OR kind = $2)"#, + AND ($2::text IS NULL OR kind = $2) + AND ($3::text IS NULL OR kind <> $3)"#, filter.subject.map(UserId::as_uuid), filter.kind.as_deref(), + filter.except_kind.as_deref(), ) )?; Ok(count.try_into().unwrap_or_default()) @@ -438,6 +442,7 @@ impl EventRepository<'_> { ) ) AND ($5::uuid IS NULL OR e.id = $5) + AND ($7::text IS NULL OR e.kind <> $7) ORDER BY e.sequence DESC LIMIT $4 OFFSET $6"#, filter.subject.map(UserId::as_uuid), @@ -446,6 +451,7 @@ impl EventRepository<'_> { i64::from(limit), filter.id.map(EventId::as_uuid), i64::from(filter.offset), + filter.except_kind.as_deref(), ) )? .into_iter() @@ -483,6 +489,36 @@ impl EventRepository<'_> { Ok(count.try_into().unwrap_or_default()) } + /// Whether `actor` caused an event of `kind`, a [`DomainEvent`] variant's serde + /// tag, concerning `subject` since `since`: how a view is recorded once an hour. + /// + /// # Errors + /// + /// Returns [`DatabaseError`] if the query fails. + pub async fn caused_since( + &mut self, + actor: &Actor, + subject: UserId, + kind: &str, + since: DateTime, + ) -> Result { + run!( + self, + fetch_one, + sqlx::query_scalar!( + r#"SELECT EXISTS ( + SELECT 1 FROM domain_events + WHERE kind = $1 AND occurred_at >= $2 AND subject_user_id = $3 + AND actor = $4 + ) AS "caused!""#, + kind, + since, + subject.as_uuid(), + Json(actor) as _, + ) + ) + } + /// Lists the events concerning a client, newest first, for tests of client changes. /// /// # Errors diff --git a/crates/ui/src/admin/events.rs b/crates/ui/src/admin/events.rs index 80f196c52..968b96d4c 100644 --- a/crates/ui/src/admin/events.rs +++ b/crates/ui/src/admin/events.rs @@ -422,7 +422,10 @@ impl EventRow<'_> { } /// Domain events, newest first: the filter form posting `user` and `kind` back to -/// `action` by `GET`, the events, and the `pages` through them. +/// `action` by `GET`, keeping whether administrators' `views` of accounts are +/// shown, a link to the same list with the views shown or hidden the other way, +/// `toggle_views`, offered only when no kind is chosen (a kind decides the views +/// by itself), the events, and the `pages` through them. #[component] pub async fn event_list<'a>( action: &'a str, @@ -432,6 +435,8 @@ pub async fn event_list<'a>( #[into] #[default] kind: Option<&'a str>, + #[default] views: bool, + toggle_views: &'a str, rows: &'a [EventRow<'a>], pages: &'a Pager, ) -> Result { @@ -443,7 +448,15 @@ pub async fn event_list<'a>(
event_rows(rows: rows) diff --git a/docs/architecture/rust-conventions.md b/docs/architecture/rust-conventions.md index 75e77abe5..de6433379 100644 --- a/docs/architecture/rust-conventions.md +++ b/docs/architecture/rust-conventions.md @@ -231,8 +231,10 @@ on it: `Operator` with the reason it must give; - a `Viewer`, for reads, which need no reason. For an operator, `Viewer::authorize` calls `Operator::authorize_read`, as every admin read does, - and records the first read through that viewer as a view, so a page reading - several settings records one; an owner's reads are not recorded. + and records the read as a view through `Operator::record_view`, which skips + it when the same administrator session or operator viewed the account within + the hour, so a page reading several settings, or reloaded, records one; an + owner's reads are not recorded. Only the extractors and `AccountService::owner`, which pages call, build an owner's `Owner`, from the session cookie; their `Subject` and `Viewer` come from it, or diff --git a/docs/architecture/surfaces.md b/docs/architecture/surfaces.md index f0308e6d9..f1de3a3a0 100644 --- a/docs/architecture/surfaces.md +++ b/docs/architecture/surfaces.md @@ -152,9 +152,12 @@ When an administrator or operator acts: - Every change needs their reason, renaming the handle included. It is stored with each event as personal data, and the owner sees it in their security history, next to "By a Piquel administrator". -- Events record the administrator or operator as their actor. A page's reads are - recorded as one view of the account, as `user show` is. The owner's history - leaves views out: it shows changes, with their reasons, not reads. +- Events record the administrator or operator as their actor. Their reads are + recorded as a view of the account, as `user show` is, once an hour per + administrator session or operator. The owner's history leaves views out: it + shows changes, with their reasons, not reads. The dashboard's event lists and + `audit list` leave them out too, unless "Show views" or `--views` asks for + them, or the kind filter is `account_viewed`. - An administrator may not change another administrator's account: it is refused before waiting for the account lock and again under it. A change checks the administrator's rights, session and passkey confirmation once more before it diff --git a/tests/browser/README.md b/tests/browser/README.md index d96f7fa52..5e84e7cce 100644 --- a/tests/browser/README.md +++ b/tests/browser/README.md @@ -110,7 +110,9 @@ those external systems. through auth's handoff page, confirms a change with a passkey for the dashboard only, and disables an account, whose settings page then loses its session; signing out of the dashboard keeps the Piquel session, and signed out of both, a passkey -sign-in on auth goes on to the dashboard. Its other tests grant administrator +sign-in on auth goes on to the dashboard. Another lists an account's events without +the administrator's view of it until "Show views", which keeps the account filter, +and hides it again with "Hide views". Its other tests grant administrator rights from a search and revoke them, each change moving on the audit chain, which stays intact; create an invitation, whose link signs one account up once, and revoke another, which then signs nobody up, when `E2E_INVITE` is set; approve diff --git a/tests/browser/admin.spec.ts b/tests/browser/admin.spec.ts index 87f2758db..4f3356db6 100644 --- a/tests/browser/admin.spec.ts +++ b/tests/browser/admin.spec.ts @@ -129,6 +129,29 @@ test('an administrator disables a user from the dashboard, and the user is signe await expect(admin.getByRole('heading', { name: 'Users', exact: true })).toBeVisible(); }); +test("an administrator's views of an account are listed only when shown", async ({ browser }) => { + const suffix = Date.now().toString(36); + const admin = await administrator(browser, `admin-${suffix}`); + await signedUp(browser, `user-${suffix}`); + await openAccount(admin, `user-${suffix}`); + await admin.getByRole('link', { name: 'All events', exact: true }).click(); + const viewed = admin.getByText('Account details viewed'); + const created = admin.getByText('Account created with a passkey'); + + // The toggle is a link, so it applies at once, keeping the account filter, which + // the form then keeps it through. + await expect(created).toBeVisible(); + await expect(viewed).toHaveCount(0); + await admin.getByRole('link', { name: 'Show views', exact: true }).click(); + await expect(viewed).toBeVisible(); + await expect(created).toBeVisible(); + await admin.getByRole('button', { name: 'Filter', exact: true }).click(); + await expect(viewed).toBeVisible(); + await admin.getByRole('link', { name: 'Hide views', exact: true }).click(); + await expect(viewed).toHaveCount(0); + await expect(created).toBeVisible(); +}); + test('rights granted from the dashboard open it, until revoked, and the audit chain keeps both', async ({ browser }) => {