Skip to content
Draft
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
23 changes: 9 additions & 14 deletions apps/auth-service/src/cli/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::{
use clap::Subcommand;
use sourceorigin_common::{
PasskeyId,
admin::{Recovery, RecoveryState, UserDetail, UserPage},
admin::{Recovery, RecoveryStanding, RecoveryState, UserDetail, UserPage},
};

/// Accounts, in any status.
Expand Down Expand Up @@ -311,22 +311,17 @@ report!([Recovery], self, out, {
["RECOVERY", "STARTED", "STATE", "PASSKEY", "NAME", "ACTIVE"],
"",
self.iter().map(|recovery| {
let state = match recovery.state {
RecoveryState::Open => Cell::new("link not used").style(Style::Notice),
RecoveryState::Probation { settles_at } => {
let ended = |what: &str, at| Cell::new(format_args!("{what} {}", Time(at)));
let state = match recovery.standing() {
RecoveryStanding::Unused => Cell::new("link not used").style(Style::Notice),
RecoveryStanding::Probation { settles_at } => {
Cell::new(format_args!("in probation until {}", Time(settles_at)))
.style(Style::Notice)
}
RecoveryState::Settled => Cell::new("settled"),
RecoveryState::Ended => {
let ended = |what: &str, at| Cell::new(format_args!("{what} {}", Time(at)));
match (recovery.undone_at, recovery.cancelled_at) {
(Some(at), _) => ended("undone", at),
(None, Some(at)) => ended("cancelled", at),
(None, None) => Cell::new("link expired"),
}
.style(Style::Muted)
}
RecoveryStanding::Settled => Cell::new("settled"),
RecoveryStanding::Undone(at) => ended("undone", at).style(Style::Muted),
RecoveryStanding::Cancelled(at) => ended("cancelled", at).style(Style::Muted),
RecoveryStanding::Expired => Cell::new("link expired").style(Style::Muted),
};
let passkey = recovery.passkey.as_ref();
[
Expand Down
11 changes: 6 additions & 5 deletions apps/auth-service/src/web/admin/invitations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::{AdminError, InviteExpiry, Reason};
use chrono::Utc;
use sourceorigin_common::{
TokenId,
admin::{CreateInvitation, CreatedInvitation},
admin::{CreateInvitation, CreatedInvitation, InvitationState},
email::NormalizedEmail,
};
use sourceorigin_ui::{Action, Change, InvitationRow, Target};
Expand All @@ -30,16 +30,17 @@ pub(super) async fn list(cx: &Cx) -> Result<Response> {
let rows: Vec<_> = invitations
.iter()
.map(|invitation| {
let open = invitation.redeemed_at.is_none() && invitation.revoked_at.is_none();
let state = invitation.state(now);
let action = |href: String| Action { href, inline };
InvitationRow {
invitation,
resend: (open
&& invitation.expires_at > now
resend: (state == InvitationState::Open
&& invitation.email.is_some()
&& app.service.mails())
.then(|| action(href!(resend, Invitation(invitation.id)).resolve(cx))),
revoke: open.then(|| action(href!(revoke, Invitation(invitation.id)).resolve(cx))),
// Until it is redeemed or revoked, expired or not.
revoke: matches!(state, InvitationState::Open | InvitationState::Expired)
.then(|| action(href!(revoke, Invitation(invitation.id)).resolve(cx))),
}
})
.collect();
Expand Down
17 changes: 3 additions & 14 deletions apps/auth-service/src/web/admin/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ use crate::{
};
use sourceorigin_common::{
AccountStatus, PictureId, SessionId, UserId,
admin::{EventSearch, MessageIntent, MessageUser, Recovery, RecoveryState, User, UserSearch},
admin::{EventSearch, MessageIntent, MessageUser, Recovery, User, UserSearch},
};
use sourceorigin_ui::{
AccountPages, Action, Change, Crumb, MessagePreview, Pager, Query, RecoveryKey, RecoveryRow,
RecoveryStanding, SessionRow, Target, UserRow,
SessionRow, Target, UserRow,
};
use topcoat::{
Result,
Expand Down Expand Up @@ -428,18 +428,7 @@ impl App {
.iter()
.map(|recovery| RecoveryRow {
started_at: recovery.started_at,
standing: match recovery.state {
RecoveryState::Open => RecoveryStanding::Unused,
RecoveryState::Probation { settles_at } => {
RecoveryStanding::Probation { settles_at }
}
RecoveryState::Settled => RecoveryStanding::Settled,
RecoveryState::Ended => match (recovery.undone_at, recovery.cancelled_at) {
(Some(at), _) => RecoveryStanding::Undone(at),
(None, Some(at)) => RecoveryStanding::Cancelled(at),
(None, None) => RecoveryStanding::Expired,
},
},
standing: recovery.standing(),
passkey: recovery.passkey.as_ref().zip(recovery.completed_at).map(
|(passkey, enrolled_at)| RecoveryKey {
id: passkey.id,
Expand Down
69 changes: 69 additions & 0 deletions crates/common/src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,36 @@ pub struct Invitation {
pub revoked_at: Option<DateTime<Utc>>,
}

impl Invitation {
/// Whether it can still be used, as of `now`.
#[must_use]
pub fn state(&self, now: DateTime<Utc>) -> InvitationState {
if self.redeemed_at.is_some() {
InvitationState::Redeemed
} else if self.revoked_at.is_some() {
InvitationState::Revoked
} else if self.expires_at <= now {
InvitationState::Expired
} else {
InvitationState::Open
}
}
}

/// Whether an invitation can still be used: the first that applies. The
/// database finds and redeems only an open one, by the same rule in SQL.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InvitationState {
/// An account was created with it.
Redeemed,
/// An administrator or operator revoked it.
Revoked,
/// Its link expired unused.
Expired,
/// Its link works.
Open,
}

/// The form creating an invitation.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CreateInvitation {
Expand Down Expand Up @@ -464,6 +494,45 @@ pub struct Recovery {
pub passkey: Option<RecoveryPasskey>,
}

impl Recovery {
/// Where it stands, as people read it: its state, with why one ended.
#[must_use]
pub const fn standing(&self) -> RecoveryStanding {
match self.state {
RecoveryState::Open => RecoveryStanding::Unused,
RecoveryState::Probation { settles_at } => RecoveryStanding::Probation { settles_at },
RecoveryState::Settled => RecoveryStanding::Settled,
RecoveryState::Ended => match (self.undone_at, self.cancelled_at) {
(Some(at), _) => RecoveryStanding::Undone(at),
(None, Some(at)) => RecoveryStanding::Cancelled(at),
(None, None) => RecoveryStanding::Expired,
},
}
}
}

/// Where a recovery stands, as the dashboard and the CLI say it: its
/// [`RecoveryState`], with an ended one split by why it ended.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RecoveryStanding {
/// Its link works, and was not used yet.
Unused,
/// Its link was used: its passkey signs in, confirms no change, and the
/// recovery can be undone until `settles_at`.
Probation {
/// When the probation ends.
settles_at: DateTime<Utc>,
},
/// Its probation ended.
Settled,
/// It was undone, after its link was used.
Undone(DateTime<Utc>),
/// It was cancelled before its link was used.
Cancelled(DateTime<Utc>),
/// Its link expired unused.
Expired,
}

/// The passkey a recovery's link enrolled.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RecoveryPasskey {
Expand Down
73 changes: 73 additions & 0 deletions crates/common/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,79 @@ fn a_client_detail_extends_the_listed_client() {
);
}

/// An invitation is redeemed, revoked, expired or open: the first that applies,
/// so a revoked one, which revoking also expires, reads as revoked.
#[cfg(feature = "admin")]
#[test]
fn an_invitation_state_takes_the_first_that_applies() {
use admin::InvitationState::{Expired, Open, Redeemed, Revoked};
let now = chrono::DateTime::<chrono::Utc>::UNIX_EPOCH;
let (past, future) = (
now - chrono::Duration::hours(1),
now + chrono::Duration::hours(1),
);
for (expires_at, redeemed_at, revoked_at, state) in [
(future, Some(past), Some(past), Redeemed),
(past, None, Some(past), Revoked),
(now, None, None, Expired),
(future, None, None, Open),
] {
let invitation = admin::Invitation {
id: TokenId::new(),
email: None,
created_at: past,
expires_at,
redeemed_at,
revoked_at,
};
assert_eq!(invitation.state(now), state, "{invitation:?}");
}
}

/// An ended recovery's standing says why it ended: undone outranks cancelled,
/// and one neither undone nor cancelled expired.
#[cfg(feature = "admin")]
#[test]
fn an_ended_recovery_says_why() {
use admin::{RecoveryStanding, RecoveryState};
let (undone, cancelled) = (
chrono::DateTime::<chrono::Utc>::UNIX_EPOCH,
chrono::DateTime::<chrono::Utc>::UNIX_EPOCH + chrono::Duration::days(1),
);
let recovery = |state, undone_at, cancelled_at| admin::Recovery {
id: RecoveryId::new(),
started_at: undone,
expires_at: undone,
completed_at: None,
cancelled_at,
undone_at,
state,
passkey: None,
};
for (undone_at, cancelled_at, standing) in [
(
Some(undone),
Some(cancelled),
RecoveryStanding::Undone(undone),
),
(
None,
Some(cancelled),
RecoveryStanding::Cancelled(cancelled),
),
(None, None, RecoveryStanding::Expired),
] {
assert_eq!(
recovery(RecoveryState::Ended, undone_at, cancelled_at).standing(),
standing
);
}
assert_eq!(
recovery(RecoveryState::Open, None, None).standing(),
RecoveryStanding::Unused
);
}

/// 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
Expand Down
16 changes: 6 additions & 10 deletions crates/ui/src/admin/lists.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{
use chrono::{DateTime, Utc};
use sourceorigin_common::{
AccountStatus,
admin::{Administrator, Invitation, InvitationSent},
admin::{Administrator, Invitation, InvitationSent, InvitationState},
};
use topcoat::{
Result,
Expand Down Expand Up @@ -47,15 +47,11 @@ pub struct InvitationRow<'a> {
impl InvitationRow<'_> {
/// Whether it can still be used, as of `now`, as a badge.
fn state(&self, now: DateTime<Utc>) -> Badge {
let invitation = self.invitation;
if invitation.redeemed_at.is_some() {
Badge::new("ok", "Redeemed")
} else if invitation.revoked_at.is_some() {
Badge::new("danger", "Revoked")
} else if invitation.expires_at <= now {
Badge::new("neutral", "Expired")
} else {
Badge::new("", "Open")
match self.invitation.state(now) {
InvitationState::Redeemed => Badge::new("ok", "Redeemed"),
InvitationState::Revoked => Badge::new("danger", "Revoked"),
InvitationState::Expired => Badge::new("neutral", "Expired"),
InvitationState::Open => Badge::new("", "Open"),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/ui/src/admin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub use lists::{
invitation_list,
};
pub use overview::{AdminOverview, Measure, Problem, admin_overview};
pub use recoveries::{RecoveryKey, RecoveryRow, RecoveryStanding, recovery_list};
pub use recoveries::{RecoveryKey, RecoveryRow, recovery_list};
pub use users::{
AccountPages, MessagePreview, SessionRow, UserRow, message_page, user_page, user_search,
};
Expand Down
23 changes: 1 addition & 22 deletions crates/ui/src/admin/recoveries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,12 @@

use super::moment;
use chrono::{DateTime, Utc};
use sourceorigin_common::PasskeyId;
use sourceorigin_common::{PasskeyId, admin::RecoveryStanding};
use topcoat::{
Result,
view::{View, component, view},
};

/// Where a recovery stands.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RecoveryStanding {
/// Its link works, and was not used yet.
Unused,
/// Its link was used: its passkey signs in, confirms no change, and the
/// recovery can be undone until `settles_at`.
Probation {
/// When the probation ends.
settles_at: DateTime<Utc>,
},
/// Its probation ended.
Settled,
/// It was undone, after its link was used.
Undone(DateTime<Utc>),
/// It was cancelled before its link was used.
Cancelled(DateTime<Utc>),
/// Its link expired unused.
Expired,
}

/// The passkey a recovery's link enrolled, named by its ID and when it was
/// enrolled, never by its label, which whoever used the link may have changed to
/// pass it off as one of the owner's.
Expand Down
18 changes: 9 additions & 9 deletions crates/ui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,15 @@ pub use admin::{
AlertCard, Change, ClientChanges, ClientPage, Confirmation as DashboardConfirmation, Dashboard,
DeliveryRow, DraftActions, EventRow, FoundAccount, HandlesPage, HandoffProof, HandoffQuery,
InvitationRow, Measure, MessagePreview, NewClientForm, OperatorDraft, Problem, RecoveryKey,
RecoveryRow, RecoveryStanding, Registration, ReleasedRow, ReservationRow, ReservedHolder,
SearchAction, SessionRow, SigningKeyRow, Tab as DashboardTab, Target, UserRow,
account_settings, admin_overview, administrator_list, alert_list, alert_update_fields,
announcement_form, announcement_list, announcement_page, audit_page, client_created,
client_list, client_page, client_registration, client_secrets, dashboard_change,
dashboard_failure, dashboard_frame, dashboard_signed_out, delivery_list, event_list,
event_rows, grant_search, handle_list, handoff_proof, invitation_created, invitation_list,
message_page, no_access, previous_alerts, recovery_list, reserved_handle_choice,
signing_key_list, signing_key_rotation, user_page, user_search,
RecoveryRow, Registration, ReleasedRow, ReservationRow, ReservedHolder, SearchAction,
SessionRow, SigningKeyRow, Tab as DashboardTab, Target, UserRow, account_settings,
admin_overview, administrator_list, alert_list, alert_update_fields, announcement_form,
announcement_list, announcement_page, audit_page, client_created, client_list, client_page,
client_registration, client_secrets, dashboard_change, dashboard_failure, dashboard_frame,
dashboard_signed_out, delivery_list, event_list, event_rows, grant_search, handle_list,
handoff_proof, invitation_created, invitation_list, message_page, no_access, previous_alerts,
recovery_list, reserved_handle_choice, signing_key_list, signing_key_rotation, user_page,
user_search,
};
pub use asset::{Asset, FONTS, STYLESHEET};
pub use clients::{
Expand Down
4 changes: 4 additions & 0 deletions docs/dev/security/account-recovery.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ stands, against the database's clock read with the row
| `Settled` | Its probation ended. Its passkey is an ordinary passkey. |
| `Ended` | It expired unused, or was cancelled or undone. |

`sourceorigin_common::admin::Recovery::standing` is the one place that splits
an `Ended` recovery into undone, cancelled and expired, for the CLI and the
dashboard.

A recovery that is `Open` or in `Probation` can still be undone. An account has
at most one (S2, S4). The migration's `undoable_recovery` is the one SQL copy of
that condition, which the [database backstops](#database-backstops) share.
Expand Down