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
24 changes: 7 additions & 17 deletions apps/auth-service/src/audit/sealer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@ use sourceorigin_common::{
events::{EventContext, JobName},
};
use sourceorigin_crypto::NoteKey;
use sourceorigin_repository::{
ChainLink, Checkpoint, EventContent, ExclusiveConnection, LockKey, SealedEvent,
};
use sourceorigin_repository::{ChainLink, Checkpoint, ExclusiveConnection, LockKey, SealedEvent};
use sourceorigin_telemetry::Counter;
use std::{
sync::{Arc, Mutex, PoisonError},
Expand Down Expand Up @@ -44,8 +42,6 @@ pub(crate) struct Sealer {
checkpoint_every: TimeDelta,
/// Events sealed per transaction.
batch: u32,
/// The canonical format events are sealed in.
format: i16,
/// When an attempt to sign a checkpoint last ended in failure. The next try
/// waits as long as the interval, so a broken chain is not recomputed on
/// every pass.
Expand All @@ -54,21 +50,19 @@ pub(crate) struct Sealer {

impl Sealer {
/// Events sealed per transaction in production: few enough that a batch of
/// the largest events migration 0035 allows still fits in memory.
/// the largest events the schema allows still fits in memory.
const BATCH: u32 = 100;
/// The least time between two checkpoints in production.
const CHECKPOINT_EVERY: TimeDelta = TimeDelta::minutes(5);

/// A sealer signing with `audit`'s key, and building only on checkpoints its
/// keys verify. It seals in [`EventContent::NEWEST_FORMAT`], which the release
/// before this one verifies too.
/// keys verify.
pub(crate) fn new(audit: &AuditConfig) -> Self {
Self {
key: audit.key.clone(),
keys: audit.keys.clone(),
checkpoint_every: Self::CHECKPOINT_EVERY,
batch: Self::BATCH,
format: EventContent::NEWEST_FORMAT,
failed_at: Mutex::new(None),
}
}
Expand All @@ -91,14 +85,10 @@ impl Sealer {
}
}

/// This sealer, sealing `batch` events per transaction, in `format`, for tests.
/// This sealer, sealing `batch` events per transaction, for tests.
#[cfg(test)]
pub(crate) fn sealing(self, batch: u32, format: i16) -> Self {
Self {
batch,
format,
..self
}
pub(crate) fn sealing(self, batch: u32) -> Self {
Self { batch, ..self }
}

/// Seals up to [`Self::batch`] events after the head in one transaction, and
Expand All @@ -113,7 +103,7 @@ impl Sealer {
let mut tx = connection.begin().await?;
let mut head = tx.audit().head().await?.unwrap_or(ChainLink::GENESIS);
let mut sealed = Vec::new();
for content in tx.audit().unsealed(self.batch, self.format).await? {
for content in tx.audit().unsealed(self.batch).await? {
head = head.extend(&content)?;
sealed.push(SealedEvent {
link: head,
Expand Down
26 changes: 7 additions & 19 deletions apps/auth-service/src/audit/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1046,7 +1046,7 @@ async fn sealing_goes_on_when_a_checkpoint_fails() {
let refused = fixture.sealer.pass(&mut lock, None).await;
assert!(matches!(refused, Err(AuditError::Broken(_))), "{refused:?}");
fixture.seal_with(&mut lock).await;
fixture.sealer = fixture.sealer.sealing(2, EventContent::UNTAGGED);
fixture.sealer = fixture.sealer.sealing(2);
let database = fixture.database.clone();
let mut tx = database.begin().await.expect("transaction");
for _ in 0..5 {
Expand Down Expand Up @@ -1139,7 +1139,7 @@ async fn a_failed_checkpoint_is_retried_after_the_interval() {
#[ignore = "requires TEST_DATABASE_URL"]
async fn checkpoints_keep_their_interval_while_batches_stay_full() {
let mut fixture = Fixture::new().await;
fixture.sealer = fixture.sealer.sealing(2, EventContent::UNTAGGED);
fixture.sealer = fixture.sealer.sealing(2);
// One transaction, so all five become ready to seal at once.
let database = fixture.database.clone();
let mut tx = database.begin().await.expect("transaction");
Expand Down Expand Up @@ -1173,29 +1173,17 @@ async fn checkpoints_keep_their_interval_while_batches_stay_full() {
);
}

/// Auth seals format 2, which names itself in the canonical form, and events
/// sealed before in the untagged format keep hashing without it; one chain holds
/// both and verifies.
/// Auth seals in its newest format, which the canonical event names, so a later
/// format can add a field without breaking the hashes of events sealed before it.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL"]
async fn the_chain_format_is_per_event() {
async fn the_canonical_event_names_its_format() {
let mut fixture = Fixture::new().await;
let sealer = std::mem::replace(
&mut fixture.sealer,
Sealer::eager(&fixture.audit).sealing(1_000, EventContent::UNTAGGED),
);
fixture.record(1).await;
fixture.seal().await;
fixture.sealer = sealer;
fixture.record(1).await;
fixture.seal().await;
let chain = fixture.database.audit().chain(0, 10).await.expect("chain");
let canonical = chain
.iter()
.map(|event| serde_json::to_value(&event.sealed.content).expect("content"))
.collect::<Vec<_>>();
assert_eq!(canonical[0].get("format"), None);
assert_eq!(canonical[1]["format"], 2);
let canonical = serde_json::to_value(&chain[0].sealed.content).expect("content");
assert_eq!(canonical["format"], EventContent::NEWEST_FORMAT);
assert_eq!(fixture.verify().await.broken, None);
}

Expand Down
4 changes: 2 additions & 2 deletions apps/auth-service/src/audit/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,8 @@ impl AuditKeys {
}

impl AuditChain {
/// Rows read per query: few enough that a page of the largest events migration
/// 0035 allows still fits in memory.
/// Rows read per query: few enough that a page of the largest events the
/// schema allows still fits in memory.
const BATCH: u32 = 100;
/// Checkpoints per [`AuditPage`].
const PAGE: u32 = 100;
Expand Down
1 change: 0 additions & 1 deletion apps/auth-service/src/cli/audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,6 @@ impl ListEvents {
Ok(Actor::Client { client_id }) => format!("client {client_id}"),
Ok(Actor::System { job }) => format!("job {job:?}"),
Ok(Actor::Anonymous) => "anonymous".to_owned(),
Ok(Actor::Unrecorded) => "unrecorded".to_owned(),
Err(_) => event.actor.to_string(),
}
}
Expand Down
6 changes: 3 additions & 3 deletions apps/auth-service/src/cli/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ impl KeysCommand {
.await?
.into_iter()
.map(|usage| KeyUsage {
key: keys.name(usage.digest_key.as_deref()),
key: keys.name(&usage.digest_key),
usage,
})
.collect();
Expand Down Expand Up @@ -243,7 +243,7 @@ struct KeyUsage {
/// The count.
#[serde(flatten)]
usage: DigestUsage,
/// `current`, `accepted`, `unrecorded` or `unknown`.
/// `current`, `accepted` or `unknown`.
key: &'static str,
}

Expand All @@ -256,7 +256,7 @@ report!([KeyUsage], self, out, {
[
Cell::new(usage.secret),
Cell::new(key),
usage.digest_key.as_deref().into(),
usage.digest_key.as_str().into(),
usage.stored.into(),
]
}),
Expand Down
9 changes: 3 additions & 6 deletions apps/auth-service/src/config/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,13 +326,10 @@ impl TokenDigestKeys {
.collect()
}

/// Names the key a stored fingerprint belongs to: `current`, `accepted`,
/// `unrecorded` for digests made before fingerprints were stored, or `unknown`.
/// Names the key a stored fingerprint belongs to: `current`, `accepted` or
/// `unknown`.
#[must_use]
pub fn name(&self, fingerprint: Option<&str>) -> &'static str {
let Some(fingerprint) = fingerprint else {
return "unrecorded";
};
pub fn name(&self, fingerprint: &str) -> &'static str {
if fingerprint == self.current.fingerprint {
"current"
} else if self
Expand Down
3 changes: 1 addition & 2 deletions apps/auth-service/src/history/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ impl Activity {
/// feed agree, as far as a count by kind can: a refresh grant's revocation
/// is left out, since the history shows only a replay's, and a session's
/// expiry is counted, since the history hides only that reason.
const SECURITY: [&'static str; 32] = [
const SECURITY: [&'static str; 31] = [
"account_created",
"signed_in",
"session_revoked",
Expand Down Expand Up @@ -241,7 +241,6 @@ impl Activity {
"account_deletion_scheduled",
"account_restored",
"compromise_reported",
"imported",
];
}

Expand Down
4 changes: 2 additions & 2 deletions apps/auth-service/src/recovery/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
//! unused or its probation running, no passkey but its own is removed, by anyone, so nothing takes that ability away
//! ([`AccountService::refuse_mid_recovery`]). Support undoes for an owner with
//! none (`AdminService::undo_recovery`). The database backs the probation and
//! that rule for every writer, an older release included: see migration
//! `0019_account_recoveries`.
//! that rule for every writer, whatever it is granted: see the account
//! recoveries section of the initial migration.

/// Recovery failures and their browser response mapping.
mod error;
Expand Down
3 changes: 1 addition & 2 deletions apps/auth-service/src/recovery/tests/undo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,7 @@ async fn the_owner_undoes_a_disabled_accounts_recovery() {
.keys
.start("/webauthn/authenticate/start", "", body)
.await;
// Written as a release older than this one would, which knows nothing of
// recoveries.
// Written directly, as a code path that knows nothing of recoveries would.
let disabled = scenario
.database()
.users()
Expand Down
2 changes: 1 addition & 1 deletion crates/common/src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1020,7 +1020,7 @@ pub struct SigningKey {
pub key_type: SigningKeyType,
/// Where it is in its lifecycle.
pub state: SigningKeyState,
/// When it was generated or imported.
/// When it was generated.
pub created_at: DateTime<Utc>,
/// When it started signing.
pub activated_at: Option<DateTime<Utc>>,
Expand Down
11 changes: 2 additions & 9 deletions crates/common/src/events/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ pub enum Actor {
},
/// An unauthenticated browser, e.g. one failing to sign in.
Anonymous,
/// Unknown: imported audit rows never recorded who acted.
Unrecorded,
}

impl Actor {
Expand All @@ -60,8 +58,7 @@ impl Actor {
| Self::Admin { .. }
| Self::Cli { .. }
| Self::System { .. }
| Self::Anonymous
| Self::Unrecorded => None,
| Self::Anonymous => None,
}
}

Expand All @@ -71,11 +68,7 @@ impl Actor {
match self {
Self::User { session_id, .. } => *session_id,
Self::Admin { session_id, .. } => Some(*session_id),
Self::Cli { .. }
| Self::Client { .. }
| Self::System { .. }
| Self::Anonymous
| Self::Unrecorded => None,
Self::Cli { .. } | Self::Client { .. } | Self::System { .. } | Self::Anonymous => None,
}
}
}
Expand Down
21 changes: 2 additions & 19 deletions crates/common/src/events/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,6 @@ impl DomainEvent {
purge_after: *purge_after,
},
Self::AccountRestored {} => HistoryEntry::AccountRestored,
Self::Imported(audit) => HistoryEntry::Legacy {
action: audit.action.clone(),
outcome: audit.outcome.clone(),
},
Self::SignInFailed { .. }
| Self::PasskeyConfirmed { .. }
| Self::GrantIssued { .. }
Expand Down Expand Up @@ -389,14 +385,6 @@ pub enum HistoryEntry {
/// The account was restored before its deletion.
#[serde(rename = "account.restored")]
AccountRestored,
/// A row of the audit log that preceded typed events.
#[serde(rename = "legacy")]
Legacy {
/// The logged action, e.g. `passkey.login`.
action: String,
/// `success`, `failure` or `rejected`.
outcome: String,
},
}
}

Expand Down Expand Up @@ -445,8 +433,7 @@ impl HistoryEntry {
| Self::SignedOutEverywhere
| Self::NotificationPreferenceChanged(_)
| Self::DeletionScheduled { .. }
| Self::AccountRestored
| Self::Legacy { .. } => true,
| Self::AccountRestored => true,
}
}

Expand Down Expand Up @@ -498,8 +485,7 @@ impl HistoryEntry {
| Self::SignedOutEverywhere
| Self::NotificationPreferenceChanged(_)
| Self::DeletionScheduled { .. }
| Self::AccountRestored
| Self::Legacy { .. } => None,
| Self::AccountRestored => None,
}
}
}
Expand Down Expand Up @@ -542,8 +528,6 @@ crate::str_enum! {
System = "system",
/// An unauthenticated browser.
Anonymous = "anonymous",
/// Unknown: imported audit rows never recorded who acted.
Unrecorded = "unrecorded",
}
}

Expand All @@ -557,7 +541,6 @@ impl From<&Actor> for HistoryActor {
Actor::Client { .. } => Self::Client,
Actor::System { .. } => Self::System,
Actor::Anonymous => Self::Anonymous,
Actor::Unrecorded => Self::Unrecorded,
}
}
}
15 changes: 4 additions & 11 deletions crates/common/src/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ pub use context::{
};
pub use history::{FollowUp, HistoryActor, HistoryEntry};
pub use payload::{
CodeRedemptionFailure, GrantRevocation, ImportedAudit, InlineSignIn, RecordedOrigin,
RecoveryRevocation, RevocationReason, SignInFailure, SigningKeyChange,
CodeRedemptionFailure, GrantRevocation, InlineSignIn, RecordedOrigin, RecoveryRevocation,
RevocationReason, SignInFailure, SigningKeyChange,
};

use crate::{
Expand Down Expand Up @@ -505,9 +505,6 @@ pub enum DomainEvent {
/// The owner turned a category of notifications' email on or off, in their
/// settings or with an email's unsubscribe link.
NotificationPreferenceChanged(NotificationPreference),
/// A row of the security audit log that preceded typed events. Only
/// migrations write these; its fields are private, so one is only ever read back.
Imported(ImportedAudit),
}

impl DomainEvent {
Expand Down Expand Up @@ -623,8 +620,7 @@ impl DomainEvent {
| Self::AlertRaised { .. }
| Self::AlertUpdated { .. }
| Self::AlertCleared { .. }
| Self::NotificationPreferenceChanged(_)
| Self::Imported(_) => None,
| Self::NotificationPreferenceChanged(_) => None,
}
}

Expand Down Expand Up @@ -699,8 +695,7 @@ impl DomainEvent {
| Self::AlertRaised { .. }
| Self::AlertUpdated { .. }
| Self::AlertCleared { .. }
| Self::NotificationPreferenceChanged(_)
| Self::Imported(_) => None,
| Self::NotificationPreferenceChanged(_) => None,
}
}

Expand Down Expand Up @@ -776,7 +771,6 @@ impl DomainEvent {
Self::AlertUpdated { .. } => "alert_updated",
Self::AlertCleared { .. } => "alert_cleared",
Self::NotificationPreferenceChanged(_) => "notification_preference_changed",
Self::Imported(_) => "imported",
}
}
}
Expand All @@ -789,7 +783,6 @@ impl SigningKeyChange {
pub const fn version(self) -> i16 {
match self {
Self::Generated
| Self::Imported
| Self::Activated
| Self::Retiring
| Self::Retired
Expand Down
Loading
Loading