Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ just auth user restore alice --reason "Changed their mind"
just auth session revoke <session-id> # 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"
Expand Down Expand Up @@ -285,8 +286,8 @@ just auth account alice apps remove <client-id> --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
Expand Down
38 changes: 12 additions & 26 deletions apps/auth-service/src/account/subject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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),
}
}

Expand All @@ -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(())
}
Expand Down
15 changes: 11 additions & 4 deletions apps/auth-service/src/account/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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
Expand All @@ -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 {
Expand Down
30 changes: 28 additions & 2 deletions apps/auth-service/src/admin/operator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
7 changes: 1 addition & 6 deletions apps/auth-service/src/admin/service/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
2 changes: 2 additions & 0 deletions apps/auth-service/src/admin/service/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ impl AdminService {
search: EventSearch,
) -> Result<EventPage, AdminError> {
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()
};
Expand Down
7 changes: 1 addition & 6 deletions apps/auth-service/src/admin/service/recovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
31 changes: 30 additions & 1 deletion apps/auth-service/src/admin/tests/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>()
};
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]
Expand Down Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions apps/auth-service/src/cli/audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ pub(super) struct ListEvents {
/// Only events of this kind, e.g. `session_revoked`.
#[arg(long)]
kind: Option<String>,
/// 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<u32>,
Expand All @@ -157,6 +161,7 @@ impl ListEvents {
let search = EventSearch {
user,
kind: self.kind,
views: self.views,
page: self.page,
};
self.output.print(
Expand Down
19 changes: 16 additions & 3 deletions apps/auth-service/src/web/admin/lists.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -21,18 +21,22 @@ struct EventsQuery {
user: Option<UserId>,
/// Only events of this kind.
kind: Option<String>,
/// Whether administrators' views of accounts are listed too.
views: Option<Checkbox>,
/// The page wanted, counting from 1.
page: Option<u32>,
}

/// `/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<Response> {
let admin = App::admin(cx).await?;
let query = query_params::<EventsQuery>(cx)?;
let filter = EventSearch {
user: query.user,
kind: query.kind.clone(),
views: query.views.is_some(),
page: query.page,
};
let found = App::of(cx)
Expand All @@ -47,9 +51,16 @@ pub(super) async fn events(cx: &Cx) -> Result<Response> {
}
.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,
Expand All @@ -59,6 +70,8 @@ pub(super) async fn events(cx: &Cx) -> Result<Response> {
action: action.as_str(),
user: user,
kind: kind,
views: filter.views,
toggle_views: toggle_views.as_str(),
rows: rows,
pages: pager,
)
Expand Down
4 changes: 4 additions & 0 deletions crates/common/src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
/// 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<u32>,
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading