diff --git a/apps/auth-service/src/admin/service/clients.rs b/apps/auth-service/src/admin/service/clients.rs index 5dcb1bd08..c4056b18e 100644 --- a/apps/auth-service/src/admin/service/clients.rs +++ b/apps/auth-service/src/admin/service/clients.rs @@ -3,12 +3,12 @@ use super::AdminService; use crate::{ - Applied, ClientDetails, ClientRegistry, ClientRegistryError, GracePeriod, + Applied, ClientRegistry, ClientRegistryError, GracePeriod, admin::{AdminError, Operator, Reason}, }; use sourceorigin_common::{ ClientId, - admin::{ApprovedOrigin, Client}, + admin::{ApprovedOrigin, Client, ClientDetail}, clients::{ClientField, ClientOwner, ClientRegistration, RelatedOrigin}, }; use sourceorigin_crypto::ClientSecret; @@ -24,22 +24,22 @@ impl AdminService { Ok(Self::views(self.database.oidc().list_clients().await?)) } - /// Describes one OIDC client as stored, with the lifetimes of its secrets. - pub(crate) async fn client_details( + /// Describes one OIDC client, deleted or not, with the lifetimes of its + /// secrets. + pub(crate) async fn client_detail( &self, operator: &Operator, id: &ClientId, - ) -> Result { + ) -> Result { operator.authorize_read(&self.database).await?; let mut tx = self.database.begin().await?; - let client = tx + let detail = tx .oidc() - .find_client(id.as_str()) + .client_detail(id) .await? .ok_or(AdminError::ClientNotFound)?; - let secrets = tx.oidc().client_secrets(id).await?; tx.commit().await?; - Ok(ClientDetails { client, secrets }) + Ok(detail) } /// Runs `change` on the client registry in one transaction, attributed to diff --git a/apps/auth-service/src/admin/service/recovery.rs b/apps/auth-service/src/admin/service/recovery.rs index e349fb2ab..5e8c6eec3 100644 --- a/apps/auth-service/src/admin/service/recovery.rs +++ b/apps/auth-service/src/admin/service/recovery.rs @@ -12,9 +12,10 @@ use crate::{ use chrono::Utc; use sourceorigin_common::{ AccountStatus, RecoveryId, UserId, + admin::Recovery, events::{DomainEvent, EventContext, RecoveryRevocation, RevocationReason}, }; -use sourceorigin_repository::{DatabaseTransaction, InsertRecovery, RecentRecovery}; +use sourceorigin_repository::{DatabaseTransaction, InsertRecovery}; use url::Url; impl AdminService { @@ -157,7 +158,7 @@ impl AdminService { &self, operator: &Operator, user_id: UserId, - ) -> Result, AdminError> { + ) -> Result, AdminError> { operator.authorize_read(&self.database).await?; let mut tx = self.database.begin().await?; let since = Utc::now() - PROBATION; diff --git a/apps/auth-service/src/admin/tests/reads.rs b/apps/auth-service/src/admin/tests/reads.rs index 5dd1ae918..6ceaa98ff 100644 --- a/apps/auth-service/src/admin/tests/reads.rs +++ b/apps/auth-service/src/admin/tests/reads.rs @@ -45,7 +45,7 @@ impl AdminOperation { ], Self::ViewClient => vec![ service - .client_details(operator, &client.parse().expect("client ID")) + .client_detail(operator, &client.parse().expect("client ID")) .await .map(drop), ], diff --git a/apps/auth-service/src/cli/client.rs b/apps/auth-service/src/cli/client.rs index 49f63bbd9..1bf2a3583 100644 --- a/apps/auth-service/src/cli/client.rs +++ b/apps/auth-service/src/cli/client.rs @@ -4,11 +4,11 @@ use super::{ CliError, Confirm, Console, Why, output::{Cell, Joined, Single, Style, report}, }; -use crate::{Applied, ClientDetails, GracePeriod, PUBLIC_BASE_URL, Reason}; +use crate::{Applied, GracePeriod, PUBLIC_BASE_URL, Reason}; use clap::{Args, Subcommand}; use sourceorigin_common::{ ClientId, UserId, - admin::{ApprovedOrigin, Client}, + admin::{ApprovedOrigin, Client, ClientDetail}, clients::{ AllowedScopes, BackchannelLogoutUri, ClientKind, ClientRegistration, ClientStatus, DisplayName, PostLogoutUris, RedirectUri, RedirectUris, RelatedOrigin, ScopeName, @@ -192,7 +192,7 @@ impl ClientCommand { } Self::Apply(apply) => apply.run(console).await, Self::List => out.emit(&service.list_clients(operator).await?[..]), - Self::Show { id } => out.emit(&service.client_details(operator, &id).await?), + Self::Show { id } => out.emit(&service.client_detail(operator, &id).await?), Self::Update(update) => { let (id, reason) = (update.id.clone(), update.why.reason.clone()); service @@ -332,7 +332,7 @@ report!([Client], self, out, { }); // A client's registration, then its secrets, never their values. -report!(ClientDetails, self, out, { +report!(ClientDetail, self, out, { let client = &self.client; out.title(format_args!("{} ({})", client.display_name, client.id))?; let list = |items: &[String]| { @@ -343,15 +343,8 @@ report!(ClientDetails, self, out, { } }; out.fields(&[ - ("Kind", Cell::new(client.kind)), - ( - "Status", - ClientCommand::status(ClientStatus::of( - client.enabled, - client.suspended_at, - client.deleted_at, - )), - ), + ("Kind", Cell::new(self.kind)), + ("Status", ClientCommand::status(client.status())), ("Owner", ClientCommand::owner(client.owner_id)), ("Redirect URIs", list(&client.redirect_uris)), ("Post-logout URIs", list(&client.post_logout_uris)), @@ -366,8 +359,8 @@ report!(ClientDetails, self, out, { "Back-channel logout", client.backchannel_logout_uri.as_deref().into(), ), - ("Created", client.created_at.into()), - ("Updated", client.updated_at.into()), + ("Created", self.created_at.into()), + ("Updated", self.updated_at.into()), ("Last used", client.last_used_at.into()), ("Suspended", client.suspended_at.into()), ("Deleted", client.deleted_at.into()), diff --git a/apps/auth-service/src/cli/user.rs b/apps/auth-service/src/cli/user.rs index 9aeef276e..fe059c858 100644 --- a/apps/auth-service/src/cli/user.rs +++ b/apps/auth-service/src/cli/user.rs @@ -11,9 +11,8 @@ use crate::{ use clap::Subcommand; use sourceorigin_common::{ PasskeyId, - admin::{UserDetail, UserPage}, + admin::{Recovery, RecoveryState, UserDetail, UserPage}, }; -use sourceorigin_repository::{RecentRecovery, RecoveryState}; /// Accounts, in any status. #[derive(Subcommand)] @@ -263,7 +262,7 @@ impl UserCommand { /// Shows the account's recent recoveries, if it has any, before another is /// started or one is undone. On standard error, which leaves standard output /// to the new link. - fn show_recent(console: &Console, recent: &[RecentRecovery]) -> Result<(), CliError> { + fn show_recent(console: &Console, recent: &[Recovery]) -> Result<(), CliError> { if recent.is_empty() { return Ok(()); } @@ -307,7 +306,7 @@ impl UserCommand { // An account's recent recoveries, newest first, with where each stands and the // passkey it enrolled, shown before another is started or one is undone. -report!([RecentRecovery], self, out, { +report!([Recovery], self, out, { out.table( ["RECOVERY", "STARTED", "STATE", "PASSKEY", "NAME", "ACTIVE"], "", diff --git a/apps/auth-service/src/clients/mod.rs b/apps/auth-service/src/clients/mod.rs index 43f007720..21dd7c06d 100644 --- a/apps/auth-service/src/clients/mod.rs +++ b/apps/auth-service/src/clients/mod.rs @@ -9,16 +9,13 @@ //! Nothing is cached: every request reads the registration it needs from the //! database, so a change applies to the next request on every replica. -use serde::Serialize; use sourceorigin_common::{ ClientId, UserId, clients::{ClientField, ClientKind, ClientOwner, ClientRegistration, RelatedOrigin}, events::{DomainEvent, EventContext}, }; use sourceorigin_crypto::{ClientSecret, CryptoError}; -use sourceorigin_repository::{ - DatabaseError, DatabaseTransaction, StoredClientSecret, StoredOidcClient, -}; +use sourceorigin_repository::{DatabaseError, DatabaseTransaction, StoredOidcClient}; use std::collections::BTreeSet; use thiserror::Error; use url::Url; @@ -149,17 +146,6 @@ pub enum Applied { Unchanged, } -/// A client's registration and the lifetimes of its secrets, as `client show` -/// shows them. -#[derive(Serialize)] -pub struct ClientDetails { - /// The registration. - #[serde(flatten)] - pub client: StoredOidcClient, - /// Its secrets, oldest first; never their values. - pub secrets: Vec, -} - impl ClientRegistryError { /// Reports `NotFound` as an unknown client `id`. fn lookup(id: &ClientId) -> impl FnOnce(DatabaseError) -> Self { diff --git a/apps/auth-service/src/clients/owned.rs b/apps/auth-service/src/clients/owned.rs index 36c8b900a..c6bc47cc2 100644 --- a/apps/auth-service/src/clients/owned.rs +++ b/apps/auth-service/src/clients/owned.rs @@ -17,6 +17,7 @@ use chrono::{DateTime, Utc}; use serde::Serialize; use sourceorigin_common::{ ClientId, + admin::SecretLifetime, clients::{ AllowedScopes, ClientField, ClientKind, ClientOwner, ClientRegistration, PostLogoutUris, RedirectUri, RedirectUris, ScopeName, @@ -24,7 +25,7 @@ use sourceorigin_common::{ protocol::oauth::Scope, }; use sourceorigin_crypto::{ClientSecret, Secret}; -use sourceorigin_repository::{DatabaseTransaction, StoredClientSecret, StoredOidcClient}; +use sourceorigin_repository::{DatabaseTransaction, StoredOidcClient}; use std::error::Error; use thiserror::Error; @@ -398,12 +399,13 @@ impl AccountService { pub(crate) async fn client_secrets( &self, owned: &OwnedClient, - ) -> Result, AccountError> { - Ok(self + ) -> Result, AccountError> { + let secrets = self .database .oidc() .client_secrets(&owned.client.id) - .await?) + .await?; + Ok(secrets.into_iter().map(Into::into).collect()) } /// Runs `change` on the client registry in one transaction, attributed to diff --git a/apps/auth-service/src/deletion/export/mod.rs b/apps/auth-service/src/deletion/export/mod.rs index b6f06d8ac..bed0d07fc 100644 --- a/apps/auth-service/src/deletion/export/mod.rs +++ b/apps/auth-service/src/deletion/export/mod.rs @@ -15,15 +15,17 @@ use base64::Engine; use chrono::{DateTime, Utc}; use serde::Serialize; use serde_json::Value; -use sourceorigin_common::admin::{ApprovedOrigin, Consent, DashboardSession, KnownDevice}; +use sourceorigin_common::admin::{ + self, ApprovedOrigin, Consent, DashboardSession, KnownDevice, RecoveryState, +}; use sourceorigin_common::{ AccountStatus, ClientId, ErrorChain, Handle, PasskeyId, PictureId, RecoveryId, SessionId, UserId, notifications::NotificationPreference, }; use sourceorigin_repository::{ AnnouncementRecord, DatabaseError, DatabaseTransaction, EventFilter, IdentityRecord, - NotificationRecord, RecentRecovery, RecordedEvent, RecoveryState, SessionRecord, StoredGrant, - StoredHandle, StoredOidcClient, StoredPasskey, StoredPicture, StoredUser, + NotificationRecord, RecordedEvent, SessionRecord, StoredGrant, StoredHandle, StoredOidcClient, + StoredPasskey, StoredPicture, StoredUser, }; use std::{collections::BTreeMap, time::Duration}; use tokio::sync::{ @@ -325,9 +327,9 @@ struct Recovery { settles_at: Option>, } -impl From for Recovery { +impl From for Recovery { /// Keeps its dates, state and passkey. - fn from(recovery: RecentRecovery) -> Self { + fn from(recovery: admin::Recovery) -> Self { let (state, settles_at) = match recovery.state { RecoveryState::Open => ("open", None), RecoveryState::Probation { settles_at } => ("probation", Some(settles_at)), diff --git a/apps/auth-service/src/deletion/export/tests.rs b/apps/auth-service/src/deletion/export/tests.rs index 0125aea79..a7d8ed112 100644 --- a/apps/auth-service/src/deletion/export/tests.rs +++ b/apps/auth-service/src/deletion/export/tests.rs @@ -4,12 +4,11 @@ use chrono::TimeZone; use serde_json::json; use sourceorigin_common::{ AnnouncementId, AuthenticationMethod, EmailId, EventId, NotificationId, Provider, TokenId, - admin::DashboardSession, + admin::{DashboardSession, RecoveryPasskey}, clients::ClientKind, events::{Browser, Platform, UserAgentFamily}, notifications::{EmailCategory, NotificationPreference}, }; -use sourceorigin_repository::RecoveryPasskey; /// Every section but the events serializes under its documented name and shape. #[test] @@ -152,7 +151,7 @@ fn serializes_every_section_in_its_documented_shape() { approved_at: at, }], }], - recoveries: vec![Recovery::from(RecentRecovery { + recoveries: vec![Recovery::from(admin::Recovery { id: recovery, started_at: at, expires_at: at, diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index 8f572d956..30a703022 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -73,8 +73,7 @@ use audit::AuditApplication; pub use audit::{AuditError, AuditKeys}; pub use cli::Cli; pub use clients::{ - Applied, ClientDetails, ClientRegistry, ClientRegistryError, MAX_DAILY_REGISTRATIONS, - MAX_OWNED_CLIENTS, + Applied, ClientRegistry, ClientRegistryError, MAX_DAILY_REGISTRATIONS, MAX_OWNED_CLIENTS, }; pub use config::{ AuditConfig, AuthConfig, DashboardConfig, KeyEncryptionKeys, PUBLIC_BASE_URL, TokenDigestKeys, diff --git a/apps/auth-service/src/recovery/mod.rs b/apps/auth-service/src/recovery/mod.rs index 353c6656d..b48eee213 100644 --- a/apps/auth-service/src/recovery/mod.rs +++ b/apps/auth-service/src/recovery/mod.rs @@ -40,13 +40,14 @@ use chrono::{DateTime, Duration, Utc}; use serde::Serialize; use sourceorigin_common::{ AccountStatus, Handle, PasskeyId, RecoveryId, UserId, + admin::RecoveryState, config::Origin, events::{DomainEvent, EventContext, RevocationReason}, protocol::api::Passkey, }; use sourceorigin_crypto::Secret; use sourceorigin_repository::{ - DatabaseError, DatabaseTransaction, RecoveryState, SessionScope, StoredPasskey, StoredRecovery, + DatabaseError, DatabaseTransaction, SessionScope, StoredPasskey, StoredRecovery, }; use url::Url; diff --git a/apps/auth-service/src/web/admin/clients.rs b/apps/auth-service/src/web/admin/clients.rs index 2de2c8c4d..3dbcf0558 100644 --- a/apps/auth-service/src/web/admin/clients.rs +++ b/apps/auth-service/src/web/admin/clients.rs @@ -19,7 +19,7 @@ use super::{ origins::{self, OriginQuery}, }; use crate::{ - AdminError, AdminService, ClientDetails, ClientRegistryError, Operator, Reason, + AdminError, AdminService, ClientRegistryError, Operator, Reason, admin::SignedInAdmin, clients::{ClientSettings, InvalidSetting, OperatorSettings}, security::ApiError, @@ -28,9 +28,9 @@ use chrono::Utc; use serde::Deserialize; use sourceorigin_common::{ ClientId, + admin::ClientDetail, clients::{ClientKind, ClientRegistration, ClientStatus}, }; -use sourceorigin_repository::StoredOidcClient; use sourceorigin_ui::{ Action, AdminClientRow, Change, ClientChanges, ClientDraft, ClientPage, ClientRow, Crumb, NewClientForm, OperatorDraft, Query, Registration, Revealed, SecretRow, SecretsChange, @@ -74,19 +74,12 @@ pub(super) async fn detail(cx: &Cx) -> Result { }; return App::render(cx, StatusCode::OK, "Client registered", page).await; } - let details = service.client_details(&admin.operator, &id).await?; + let found = service.client_detail(&admin.operator, &id).await?; let approved = service.list_related_origins(&admin.operator).await?; - let stored = &details.client; - let client = App::client_row(stored); + let client = &found.client; + let row = ClientRow::from(&found); let page = || Client(id.clone()); - let secrets: Vec<_> = details - .secrets - .iter() - .map(|secret| SecretRow { - created_at: secret.created_at, - expires_at: secret.expires_at, - }) - .collect(); + let secrets: Vec<_> = found.secrets.iter().map(SecretRow::from).collect(); let origins = approved .iter() .filter(|approved| approved.client_id == id) @@ -98,9 +91,9 @@ pub(super) async fn detail(cx: &Cx) -> Result { Ok((approved.origin.as_str(), remove)) }) .collect::>()?; - let approve = if stored.deleted_at.is_some() { + let approve = if client.deleted_at.is_some() { Err("Deleted clients sign nobody in.") - } else if stored.trusted { + } else if client.trusted { Ok(href!(origins::approve, page()).resolve(cx)) } else { Err("Only trusted clients' pages sign users in themselves.") @@ -109,32 +102,31 @@ pub(super) async fn detail(cx: &Cx) -> Result { // is not links the change's page, which confirms first. let inline = admin.operator.is_confirmed(super::FORM_TIME); let action = |href: String| Action { href, inline }; - let changes = stored.deleted_at.is_none().then(|| ClientChanges { + let changes = client.deleted_at.is_none().then(|| ClientChanges { settings: href!(edit, page()).resolve(cx), - status: match client.status { + status: match row.status { ClientStatus::Deleted { .. } | ClientStatus::Suspended { .. } => None, ClientStatus::Enabled => Some(action(href!(disable, page()).resolve(cx))), ClientStatus::Disabled => Some(action(href!(enable, page()).resolve(cx))), }, - suspension: action(match client.status { + suspension: action(match row.status { ClientStatus::Suspended { .. } => href!(unsuspend, page()).resolve(cx), ClientStatus::Deleted { .. } | ClientStatus::Enabled | ClientStatus::Disabled => { href!(suspend, page()).resolve(cx) } }), delete: action(href!(delete, page()).resolve(cx)), - secret: (stored.kind == ClientKind::Confidential) - .then(|| href!(rotate, page()).resolve(cx)), + secret: (found.kind == ClientKind::Confidential).then(|| href!(rotate, page()).resolve(cx)), }); let shown = ClientPage { - client, - trusted: stored.trusted, - audiences: &stored.allowed_audiences, - owner: stored + client: row, + trusted: client.trusted, + audiences: &client.allowed_audiences, + owner: client .owner_id .map(|owner| (owner, App::account(cx, owner))), - created_at: stored.created_at, - updated_at: stored.updated_at, + created_at: found.created_at, + updated_at: found.updated_at, secrets: &secrets, origins, approve, @@ -148,7 +140,7 @@ pub(super) async fn detail(cx: &Cx) -> Result { Box::pin(App::render( cx, StatusCode::OK, - Crumb::Name(App::title(stored)), + Crumb::Name(App::title(&found)), page, )) .await @@ -199,8 +191,8 @@ pub(super) async fn create(cx: &Cx, form: Option>) -> Result pub(super) async fn edit(cx: &Cx, form: Option>) -> Result { let admin = App::confirmed(cx).await?; let service = &App::of(cx).service; - let stored = App::changing(cx, admin).await?.client; - let id = stored.id.clone(); + let found = App::changing(cx, admin).await?; + let id = found.client.id.clone(); let back = href!(detail, Client(id.clone())).resolve(cx); let refusal = App::submit(cx, form, back.clone(), async |draft: OperatorDraft| { let reason = Reason::parse(draft.reason.clone())?; @@ -216,10 +208,10 @@ pub(super) async fn edit(cx: &Cx, form: Option>) -> Result refused.form.clone(), - None => OperatorDraft::of(&App::client_row(&stored), stored.trusted), + None => OperatorDraft::of(&ClientRow::from(&found), found.client.trusted), }; let registration = Registration::Edit { - name: App::title(&stored), + name: App::title(&found), }; Box::pin(App::registration_page( cx, @@ -242,9 +234,9 @@ pub(super) async fn rotate(cx: &Cx, form: Option>) -> Result>) -> Result = details - .secrets - .iter() - .map(|secret| SecretRow { - created_at: secret.created_at, - expires_at: secret.expires_at, - }) - .collect(); + let secrets: Vec<_> = found.secrets.iter().map(SecretRow::from).collect(); let (here, name, secrets, state, reason, refusal) = ( &here, - App::title(&details.client), + App::title(&found), &secrets, &state, &reason, @@ -466,16 +451,16 @@ impl App { /// The client the path names, for a page that changes it. A deleted client /// changes no more, so each of its change pages answers at once with the /// registry's refusal, as its form would once posted. - pub(super) async fn changing(cx: &Cx, admin: &SignedInAdmin) -> Result { + pub(super) async fn changing(cx: &Cx, admin: &SignedInAdmin) -> Result { let id = path_param::(cx)?; - let details = Self::of(cx) + let found = Self::of(cx) .service - .client_details(&admin.operator, id) + .client_detail(&admin.operator, id) .await?; - if details.client.deleted_at.is_some() { + if found.client.deleted_at.is_some() { return Err(AdminError::from(ClientRegistryError::Deleted(id.clone())).into()); } - Ok(details) + Ok(found) } /// `clients` as a list shows them, each linking its page. @@ -492,30 +477,14 @@ impl App { .collect() } - /// The client `stored`, as the console's pieces show it. - fn client_row(stored: &StoredOidcClient) -> ClientRow<'_> { - ClientRow { - id: &stored.id, - name: &stored.display_name, - kind: stored.kind, - status: ClientStatus::of(stored.enabled, stored.suspended_at, stored.deleted_at), - redirect_uris: &stored.redirect_uris, - post_logout_uris: &stored.post_logout_uris, - allowed_scopes: &stored.allowed_scopes, - allow_refresh: stored.allow_refresh, - require_pushed_authorization_requests: stored.require_pushed_authorization_requests, - backchannel_logout_uri: stored.backchannel_logout_uri.as_deref(), - last_used_at: stored.last_used_at, - } - } - - /// The name of client `stored`'s pages: its own, or its ID once deleted, which - /// erases its name. - pub(super) fn title(stored: &StoredOidcClient) -> &str { - if stored.display_name.is_empty() { - stored.id.as_str() + /// The name of client `found`'s pages: its own, or its ID once deleted, + /// which erases its name. + pub(super) fn title(found: &ClientDetail) -> &str { + let client = &found.client; + if client.display_name.is_empty() { + client.id.as_str() } else { - &stored.display_name + &client.display_name } } diff --git a/apps/auth-service/src/web/admin/mod.rs b/apps/auth-service/src/web/admin/mod.rs index 7ee05418f..02bd47820 100644 --- a/apps/auth-service/src/web/admin/mod.rs +++ b/apps/auth-service/src/web/admin/mod.rs @@ -1085,9 +1085,9 @@ impl AdminApplication { if path == href { return None; } - let details = service.client_details(&admin.operator, &id).await.ok()?; + let detail = service.client_detail(&admin.operator, &id).await.ok()?; Some(Parent { - name: Self::title(&details.client).to_owned(), + name: Self::title(&detail).to_owned(), href, id: id.to_string(), }) diff --git a/apps/auth-service/src/web/admin/users.rs b/apps/auth-service/src/web/admin/users.rs index b3f17648e..7b8096b50 100644 --- a/apps/auth-service/src/web/admin/users.rs +++ b/apps/auth-service/src/web/admin/users.rs @@ -9,9 +9,8 @@ use crate::{ }; use sourceorigin_common::{ AccountStatus, PictureId, SessionId, UserId, - admin::{EventSearch, MessageIntent, MessageUser, User, UserSearch}, + admin::{EventSearch, MessageIntent, MessageUser, Recovery, RecoveryState, User, UserSearch}, }; -use sourceorigin_repository::{RecentRecovery, RecoveryState}; use sourceorigin_ui::{ AccountPages, Action, Change, Crumb, MessagePreview, Pager, Query, RecoveryKey, RecoveryRow, RecoveryStanding, SessionRow, Target, UserRow, @@ -424,7 +423,7 @@ impl AccountChange { impl App { /// `recent` recoveries as the recovery pages list them. - fn recovery_rows(recent: &[RecentRecovery]) -> Vec { + fn recovery_rows(recent: &[Recovery]) -> Vec { recent .iter() .map(|recovery| RecoveryRow { diff --git a/apps/auth-service/src/web/developers/app.rs b/apps/auth-service/src/web/developers/app.rs index 70a453540..b8d071f00 100644 --- a/apps/auth-service/src/web/developers/app.rs +++ b/apps/auth-service/src/web/developers/app.rs @@ -206,13 +206,7 @@ impl AccountPage for AppSecrets { return Err(Failure::Missing); } let secrets = web.account.client_secrets(&app).await?; - let rows: Vec<_> = secrets - .iter() - .map(|secret| SecretRow { - created_at: secret.created_at, - expires_at: secret.expires_at, - }) - .collect(); + let rows: Vec<_> = secrets.iter().map(SecretRow::from).collect(); let page = developers::of(APP_SECRETS, &client.id); let view = view! { cx => sourceorigin_ui::app_secrets( diff --git a/crates/common/src/admin.rs b/crates/common/src/admin.rs index 530c75a41..b2097be03 100644 --- a/crates/common/src/admin.rs +++ b/crates/common/src/admin.rs @@ -10,9 +10,9 @@ pub use crate::protocol::api::{Identity, Passkey}; pub use crate::user_agent::{Browser, Platform, UserAgentFamily}; use crate::{ - AccountStatus, AnnouncementId, AuthenticationMethod, ClientId, DeliveryId, EventId, Handle, - PictureId, SessionId, TokenId, TraceId, UserId, - clients::{ClientStatus, RelatedOrigin}, + AccountStatus, AnnouncementId, AuthenticationMethod, ClientId, ClientSecretId, DeliveryId, + EventId, Handle, PasskeyId, PictureId, RecoveryId, SessionId, TokenId, TraceId, UserId, + clients::{ClientKind, ClientStatus, RelatedOrigin}, form::Checkbox, protocol::{jwt::KeyId, oauth::ClientAuthMethod}, }; @@ -384,6 +384,97 @@ impl Client { } } +/// One OIDC client as its page and `client show` show it: the client as listed, +/// with its kind, when it was registered and changed, and its secrets. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ClientDetail { + /// The client, as the list shows it. + #[serde(flatten)] + pub client: Client, + /// Public, or confidential with secrets. + pub kind: ClientKind, + /// When it was registered. + pub created_at: DateTime, + /// When its registration last changed. + pub updated_at: DateTime, + /// A confidential client's secrets, oldest first, expired ones included. + pub secrets: Vec, +} + +/// One of a confidential client's secrets: when it was made and when it stops +/// working, never its value. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SecretLifetime { + /// The secret. + pub id: ClientSecretId, + /// When it was made. + pub created_at: DateTime, + /// When a rotation made it stop working, if one did. + pub expires_at: Option>, +} + +/// Where an account recovery stands. The database crate computes it as it reads +/// one; the migration's `undoable_recovery` is the one SQL copy, which the +/// database's backstops use. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum RecoveryState { + /// Its link works: not used, cancelled or undone, and not expired. + Open, + /// Its link was used and its probation has not ended: its passkey signs in + /// but never confirms a session, and a passkey from before it can undo it. + Probation { + /// When the probation ends. + settles_at: DateTime, + }, + /// Its probation ended: its passkey is an ordinary passkey. + Settled, + /// It expired unused, or was cancelled or undone. + Ended, +} + +impl RecoveryState { + /// Whether the recovery can still be undone: its link works, or it is in + /// probation. + #[must_use] + pub const fn undoable(self) -> bool { + matches!(self, Self::Open | Self::Probation { .. }) + } +} + +/// A recent recovery of an account, as support reviews it before starting +/// another: where it stands, and the passkey its link enrolled. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Recovery { + /// The recovery. + pub id: RecoveryId, + /// When it started. + pub started_at: DateTime, + /// When its link stops, or stopped, working unused. + pub expires_at: DateTime, + /// When its link enrolled a passkey, if it did. + pub completed_at: Option>, + /// When it was cancelled before its link was used. + pub cancelled_at: Option>, + /// When it was undone, by its owner or by support. + pub undone_at: Option>, + /// Where it stands now. + pub state: RecoveryState, + /// The passkey its link enrolled, if it did. + pub passkey: Option, +} + +/// The passkey a recovery's link enrolled. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RecoveryPasskey { + /// The passkey. + pub id: PasskeyId, + /// Its label, while its row exists. + pub friendly_name: Option, + /// Whether it is still active. + pub active: bool, +} + /// The event list's query. Every filter is optional. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct EventSearch { diff --git a/crates/common/src/tests.rs b/crates/common/src/tests.rs index edd01152a..baa5a3010 100644 --- a/crates/common/src/tests.rs +++ b/crates/common/src/tests.rs @@ -468,6 +468,51 @@ fn paging_has_no_zero_page_or_page_size() { ); } +/// A client's detail, which `client show --json` prints, is the client as the +/// list prints it, with its kind, dates and secrets beside it. +#[cfg(feature = "admin")] +#[test] +fn a_client_detail_extends_the_listed_client() { + let at = chrono::DateTime::::UNIX_EPOCH; + let client = admin::Client { + id: "notes".parse().expect("client ID"), + display_name: "Notes".to_owned(), + redirect_uris: vec!["https://notes.example/callback".to_owned()], + post_logout_uris: Vec::new(), + allowed_scopes: vec!["openid".to_owned()], + allowed_audiences: vec!["notes".to_owned()], + allow_refresh: false, + enabled: true, + trusted: false, + require_pushed_authorization_requests: false, + token_endpoint_auth_method: protocol::oauth::ClientAuthMethod::None, + backchannel_logout_uri: None, + owner_id: None, + last_used_at: None, + suspended_at: None, + deleted_at: None, + }; + let detail = admin::ClientDetail { + client: client.clone(), + kind: clients::ClientKind::Public, + created_at: at, + updated_at: at, + secrets: Vec::new(), + }; + let listed = serde_json::to_value(&client).expect("serialize"); + let mut shown = serde_json::to_value(&detail).expect("serialize"); + let shown = shown.as_object_mut().expect("an object"); + for extra in ["kind", "created_at", "updated_at", "secrets"] { + assert!(shown.remove(extra).is_some(), "{extra}"); + } + assert_eq!(serde_json::Value::Object(shown.clone()), listed); + let json = serde_json::to_string(&detail).expect("serialize"); + assert_eq!( + serde_json::from_str::(&json).expect("deserialize"), + detail + ); +} + /// Only public addresses pass the shared check, however they are written: an /// embedded IPv4 address (mapped, NAT64, 6to4) is checked too. A back-channel /// logout URI on a literal address registers exactly when deliveries could reach diff --git a/crates/database/src/lib.rs b/crates/database/src/lib.rs index ecdc3e01f..2e2fd20c7 100644 --- a/crates/database/src/lib.rs +++ b/crates/database/src/lib.rs @@ -63,7 +63,7 @@ pub use repositories::{ }, passkeys::{CeremonyKind, ConsumedCeremony, InsertCeremony, InsertPasskey, StoredPasskey}, pictures::StoredPicture, - recoveries::{InsertRecovery, RecentRecovery, RecoveryPasskey, RecoveryState, StoredRecovery}, + recoveries::{InsertRecovery, StoredRecovery}, security::{InsertInvitation, InvitationKey, OpenInvitation}, sessions::{ InsertSession, LAST_SEEN_INTERVAL, SessionAuthentication, SessionScope, StoredSession, diff --git a/crates/database/src/repositories/oidc/clients.rs b/crates/database/src/repositories/oidc/clients.rs index 129fb4ec5..72fe96620 100644 --- a/crates/database/src/repositories/oidc/clients.rs +++ b/crates/database/src/repositories/oidc/clients.rs @@ -13,7 +13,7 @@ use chrono::{DateTime, Duration, Utc}; use serde::Serialize; use sourceorigin_common::{ ClientId, ClientSecretId, UserId, - admin::{ApprovedOrigin, Client}, + admin::{ApprovedOrigin, Client, ClientDetail, SecretLifetime}, clients::{ BackchannelLogoutUri, ClientField, ClientKind, ClientOwner, ClientRegistration, RedirectUri, RelatedOrigin, ScopeName, @@ -169,6 +169,17 @@ impl From for Client { } } +impl From for SecretLifetime { + /// Keeps its ID and lifetime. + fn from(secret: StoredClientSecret) -> Self { + Self { + id: secret.id, + created_at: secret.created_at, + expires_at: secret.expires_at, + } + } +} + /// One of a confidential client's secrets. Its digest stays in the database. #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct StoredClientSecret { @@ -749,6 +760,29 @@ impl OidcRepository<'_> { ) } + /// The client `id` as its admin page shows it, with its secrets, deleted or + /// not, or `None` if no client ever had this ID. + /// + /// # Errors + /// + /// Returns [`DatabaseError`] if a query fails or a row is invalid. + pub async fn client_detail( + &mut self, + id: &ClientId, + ) -> Result, DatabaseError> { + let Some(client) = self.find_client(id.as_str()).await? else { + return Ok(None); + }; + let secrets = self.client_secrets(id).await?; + Ok(Some(ClientDetail { + kind: client.kind, + created_at: client.created_at, + updated_at: client.updated_at, + client: client.into(), + secrets: secrets.into_iter().map(Into::into).collect(), + })) + } + /// Every secret of the client, expired ones included, oldest first. /// /// # Errors diff --git a/crates/database/src/repositories/recoveries.rs b/crates/database/src/repositories/recoveries.rs index c996b7252..3dd2db763 100644 --- a/crates/database/src/repositories/recoveries.rs +++ b/crates/database/src/repositories/recoveries.rs @@ -4,8 +4,10 @@ use super::{RecoveryRepository, RepositoryExecutor}; use crate::DatabaseError; use chrono::{DateTime, Duration, Utc}; -use serde::Serialize; -use sourceorigin_common::{PasskeyId, RecoveryId, UserId}; +use sourceorigin_common::{ + PasskeyId, RecoveryId, UserId, + admin::{Recovery, RecoveryPasskey, RecoveryState}, +}; /// A new recovery, whose link works until `expires_at`. pub struct InsertRecovery<'a> { @@ -59,35 +61,6 @@ macro_rules! recoveries { }; } -/// Where a recovery stands. [`StoredRecovery::state`] is the only place auth -/// computes it; the migration's `undoable_recovery` is the one SQL copy, which -/// the database's backstops use. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum RecoveryState { - /// Its link works: not used, cancelled or undone, and not expired. - Open, - /// Its link was used and its probation has not ended: its passkey signs in - /// but never confirms a session, and a passkey from before it can undo it. - Probation { - /// When the probation ends. - settles_at: DateTime, - }, - /// Its probation ended: its passkey is an ordinary passkey. - Settled, - /// It expired unused, or was cancelled or undone. - Ended, -} - -impl RecoveryState { - /// Whether the recovery can still be undone: its link works, or it is in - /// probation. - #[must_use] - pub const fn undoable(self) -> bool { - matches!(self, Self::Open | Self::Probation { .. }) - } -} - impl StoredRecovery { /// Where the recovery stood when it was read. #[must_use] @@ -106,40 +79,7 @@ impl StoredRecovery { } } -/// A recent recovery of an account, as support reviews it before starting -/// another: where it stands, and the passkey its link enrolled. -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] -pub struct RecentRecovery { - /// The recovery. - pub id: RecoveryId, - /// When it started. - pub started_at: DateTime, - /// When its link stops, or stopped, working unused. - pub expires_at: DateTime, - /// When its link enrolled a passkey, if it did. - pub completed_at: Option>, - /// When it was cancelled before its link was used. - pub cancelled_at: Option>, - /// When it was undone, by its owner or by support. - pub undone_at: Option>, - /// Where it stands now. - pub state: RecoveryState, - /// The passkey its link enrolled, if it did. - pub passkey: Option, -} - -/// The passkey a recovery's link enrolled. -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] -pub struct RecoveryPasskey { - /// The passkey. - pub id: PasskeyId, - /// Its label, while its row exists. - pub friendly_name: Option, - /// Whether it is still active. - pub active: bool, -} - -/// A [`RecentRecovery`] as one row: the recovery, and its passkey's columns. +/// A [`Recovery`] as one row: the recovery, and its passkey's columns. struct RecentRow { /// The recovery. recovery: StoredRecovery, @@ -149,7 +89,7 @@ struct RecentRow { passkey_active: bool, } -impl From for RecentRecovery { +impl From for Recovery { /// Computes its state, and gathers the enrolled passkey's columns. fn from(row: RecentRow) -> Self { let RecentRow { @@ -348,7 +288,7 @@ impl RecoveryRepository<'_> { &mut self, user_id: UserId, since: DateTime, - ) -> Result, DatabaseError> { + ) -> Result, DatabaseError> { let rows = run!( self, fetch_all, diff --git a/crates/database/tests/recoveries.rs b/crates/database/tests/recoveries.rs index df9ab0cc7..a856c38ba 100644 --- a/crates/database/tests/recoveries.rs +++ b/crates/database/tests/recoveries.rs @@ -7,10 +7,11 @@ )] use chrono::{DateTime, Duration, Utc}; -use sourceorigin_common::{AuthenticationMethod, PasskeyId, RecoveryId, SessionId, UserId}; +use sourceorigin_common::{ + AuthenticationMethod, PasskeyId, RecoveryId, SessionId, UserId, admin::RecoveryState, +}; use sourceorigin_repository::{ - Database, DatabaseConfig, InsertPasskey, InsertRecovery, InsertSession, RecoveryState, - StoredRecovery, + Database, DatabaseConfig, InsertPasskey, InsertRecovery, InsertSession, StoredRecovery, }; /// How long a probation lasts in these tests. diff --git a/crates/ui/src/clients.rs b/crates/ui/src/clients.rs index 78a0ef189..48978234d 100644 --- a/crates/ui/src/clients.rs +++ b/crates/ui/src/clients.rs @@ -10,6 +10,7 @@ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use sourceorigin_common::{ ClientId, + admin::{ClientDetail, SecretLifetime}, clients::{ClientField, ClientKind, ClientStatus}, protocol::oauth::Scope, }; @@ -46,6 +47,26 @@ pub struct ClientRow<'a> { pub last_used_at: Option>, } +impl<'a> From<&'a ClientDetail> for ClientRow<'a> { + /// The client as the dashboard reads it. + fn from(detail: &'a ClientDetail) -> Self { + let client = &detail.client; + Self { + id: &client.id, + name: &client.display_name, + kind: detail.kind, + status: client.status(), + redirect_uris: &client.redirect_uris, + post_logout_uris: &client.post_logout_uris, + allowed_scopes: &client.allowed_scopes, + allow_refresh: client.allow_refresh, + require_pushed_authorization_requests: client.require_pushed_authorization_requests, + backchannel_logout_uri: client.backchannel_logout_uri.as_deref(), + last_used_at: client.last_used_at, + } + } +} + impl ClientRow<'_> { /// What its kind means for its owner. pub(crate) const fn kind_name(&self) -> &'static str { @@ -66,6 +87,16 @@ pub struct SecretRow { pub expires_at: Option>, } +impl From<&SecretLifetime> for SecretRow { + /// The secret's lifetime, as the dashboard reads it. + fn from(secret: &SecretLifetime) -> Self { + Self { + created_at: secret.created_at, + expires_at: secret.expires_at, + } + } +} + /// Where a client's `OpenID` Connect library finds Origin Auth. #[derive(Clone, Copy, Debug)] pub struct Connection<'a> { diff --git a/docs/dev/operations/administration.md b/docs/dev/operations/administration.md index c74174abd..7600d0e23 100644 --- a/docs/dev/operations/administration.md +++ b/docs/dev/operations/administration.md @@ -570,8 +570,9 @@ Each alert says what to look at. Auth raises these: read only the lines that start with `{`. A usage error is clap's own text. A result has the shape of the view the dashboard shows, as defined in `sourceorigin_common::admin`: `user search` (`UserPage`), `user show` - (`UserDetail`), `audit list` (`EventPage`), `client list`, `invite list`, - `admin list`, `announcement list`, `announcement show` + (`UserDetail`), `audit list` (`EventPage`), `client list`, `client show` + (`ClientDetail`: a listed client with its kind, dates and secrets), + `invite list`, `admin list`, `announcement list`, `announcement show` (`AnnouncementDetail`), `audit verify`'s result, and `alerts list` (`AlertDetail`, from `sourceorigin_common::alerts`). A single value is an object with one key, such as `{"link":"…"}`.