Skip to content

Commit 0beb6d4

Browse files
authored
feat(auth): auth verifies the audit chain on its own once no one has for six hours (#415)
The audit chain was only verified when someone asked, so a break went unnoticed until an operator checked. Now auth verifies it on its own. A new background job runs on one replica at a time. Every ten minutes it reads the newest recorded verification. Once that is six hours old, whoever made it, the job verifies the whole chain with the dashboard's keys and records the result as the `audit_verification` job. The dashboard's Audit tab then always shows a recent verification, and **Verify now** or `audit verify` push the next one back. - It has its own lock, not the sealer's, and its read-only snapshot holds no transaction ID, so it never holds sealing back. - The dashboard, the CLI and the job share how a verification is made and recorded. Stacked on #411, which makes `audit_verification` readable first: a release fails to decode a job name it doesn't know. Left for later: when verification itself errors rather than finding a break (say, an event that doesn't canonicalize), the job only logs it and tries again ten minutes later. The alert PRs further up this stack bring the signal admins actually see. **Proof:** - A focused test: the job verifies when nothing was recorded lately, records as itself, and skips the next pass. - The audit and dashboard audit tests pass (12/12). clippy, fmt and rustdoc are clean. - On a preview, the job verified the chain on its own at startup: `audit list --kind audit_chain_verified` shows one event by `job AuditVerification`, with the server's own (uncommitted) keys. Reviewed with review-loop: 1 round with 2× GPT-6.1 Sol and Claude Opus 5.5. Verdict: approved > [!NOTE] > Written by Claude Opus 5.5 in Claude Code and reviewed by GPT-6.1 Sol and Claude Opus 5.5 (via T3 Code) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
1 parent 355325c commit 0beb6d4

12 files changed

Lines changed: 168 additions & 23 deletions

File tree

‎apps/auth-service/src/admin/service/events.rs‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,8 @@ impl AdminService {
6363
) -> Result<AuditVerification, AdminError> {
6464
operator.authorize_read(&self.database).await?;
6565
let verification = AuditChain::new(self.database.clone()).verify(keys).await?;
66-
let mut tx = self.database.begin().await?;
67-
let verified = DomainEvent::AuditChainVerified(verification.clone());
68-
tx.record(&operator.context(), None, verified).await?;
69-
tx.commit().await?;
66+
let tx = self.database.begin().await?;
67+
AuditChain::record(tx, &operator.context(), &verification).await?;
7068
Ok(verification)
7169
}
7270

‎apps/auth-service/src/audit/mod.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ mod sealer;
1414
/// Focused tests for sealing, verification and pruning.
1515
#[cfg(test)]
1616
mod tests;
17+
/// The verifier job.
18+
mod verifier;
1719
/// Chain verification, and the checks before pruning.
1820
mod verify;
1921

@@ -23,6 +25,7 @@ pub(crate) use piquel_common::admin::{
2325
};
2426
pub(crate) use routes::AuditApplication;
2527
pub(crate) use sealer::Sealer;
28+
pub(crate) use verifier::Verifier;
2629
pub(crate) use verify::TrustedCheckpoint;
2730

2831
use base64::{Engine, engine::general_purpose::STANDARD};

‎apps/auth-service/src/audit/tests.rs‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use chrono::{SubsecRound, TimeDelta};
1010
use piquel_common::{
1111
Personal, Provider,
1212
config::Origin,
13-
events::{Actor, DomainEvent, EventContext, RequestOrigin},
13+
events::{Actor, DomainEvent, EventContext, JobName, RequestOrigin},
1414
};
1515
use piquel_crypto::NoteKey;
1616
use piquel_repository::{
@@ -579,6 +579,41 @@ async fn the_audit_page_shows_the_newest_recorded_verification() {
579579
);
580580
}
581581

582+
/// The verifier job verifies the chain when no verification was recorded lately,
583+
/// and records what it found as itself, which then holds off its next pass.
584+
#[tokio::test]
585+
#[ignore = "requires TEST_DATABASE_URL"]
586+
async fn the_verifier_verifies_when_no_verification_is_recent() {
587+
let fixture = Fixture::sealed_six().await;
588+
let verifier = Verifier::new(AuditKeys {
589+
verifiers: fixture.keys.verifiers.clone(),
590+
source: fixture.keys.source,
591+
});
592+
let mut lock = fixture
593+
.database
594+
.try_exclusive(LockKey::AuditVerification)
595+
.await
596+
.expect("lock")
597+
.expect("no other test verifies");
598+
let intact = fixture.verify().await;
599+
assert_eq!(verifier.pass(&mut lock).await.expect("pass"), Some(intact));
600+
let newest = fixture
601+
.database
602+
.events()
603+
.newest_audit_verification()
604+
.await
605+
.expect("newest")
606+
.expect("recorded");
607+
assert_eq!(
608+
newest.actor,
609+
Actor::System {
610+
job: JobName::AuditVerification
611+
}
612+
);
613+
assert_eq!(verifier.pass(&mut lock).await.expect("pass"), None);
614+
lock.release().await.expect("release");
615+
}
616+
582617
/// The newest checkpoint is served as its signed note, and the list pages through
583618
/// checkpoints oldest first; both are cacheable.
584619
#[tokio::test]
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
//! Verifies the chain on a schedule, so the dashboard's Audit tab shows a recent
2+
//! verification without an operator asking for one.
3+
4+
use super::{AuditChain, AuditError, AuditKeys, AuditVerification};
5+
use crate::jobs::{ExclusiveJob, Shutdown};
6+
use chrono::{TimeDelta, Utc};
7+
use piquel_common::events::{Actor, EventContext, JobName, RequestOrigin};
8+
use piquel_repository::{ExclusiveConnection, LockKey};
9+
use std::time::Duration;
10+
11+
/// Verifies the whole chain, on one replica at a time, once the newest recorded
12+
/// verification, whoever made it, is [`Self::VERIFY_EVERY`] old, and records
13+
/// what it found as [`JobName::AuditVerification`].
14+
pub(crate) struct Verifier {
15+
/// The keys it verifies with, the dashboard's (see [`AuditKeys::for_server`]).
16+
keys: AuditKeys,
17+
}
18+
19+
impl Verifier {
20+
/// How old the newest recorded verification may get.
21+
const VERIFY_EVERY: TimeDelta = TimeDelta::hours(6);
22+
23+
/// A verifier checking checkpoints against `keys`.
24+
pub(crate) const fn new(keys: AuditKeys) -> Self {
25+
Self { keys }
26+
}
27+
28+
/// Verifies and records the chain, unless a verification was recorded in the
29+
/// last [`Self::VERIFY_EVERY`]. Returns what it found, if it verified.
30+
pub(super) async fn pass(
31+
&self,
32+
connection: &mut ExclusiveConnection,
33+
) -> Result<Option<AuditVerification>, AuditError> {
34+
let newest = connection.events().newest_audit_verification().await?;
35+
if newest.is_some_and(|newest| Utc::now() - newest.occurred_at < Self::VERIFY_EVERY) {
36+
return Ok(None);
37+
}
38+
let verification = AuditChain::verify_in(connection.begin().await?, &self.keys).await?;
39+
let context = EventContext {
40+
actor: Actor::System {
41+
job: JobName::AuditVerification,
42+
},
43+
origin: RequestOrigin::default(),
44+
reason: None,
45+
};
46+
AuditChain::record(connection.begin().await?, &context, &verification).await?;
47+
Ok(Some(verification))
48+
}
49+
}
50+
51+
impl ExclusiveJob for Verifier {
52+
const NAME: &'static str = "audit-verifier";
53+
const LOCK: LockKey = LockKey::AuditVerification;
54+
const EVERY: Duration = Duration::from_mins(10);
55+
type Error = AuditError;
56+
57+
/// One verification reads one snapshot, so shutdown cancels it rather than
58+
/// stopping it early.
59+
async fn run(
60+
&self,
61+
connection: &mut ExclusiveConnection,
62+
_: &Shutdown,
63+
) -> Result<(), AuditError> {
64+
self.pass(connection).await.map(drop)
65+
}
66+
}

‎apps/auth-service/src/audit/verify.rs‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use super::{
66
AuditChain, AuditCheckpoint, AuditError, AuditKeys, AuditPage, AuditVerification, Chain,
77
ChainBreak, ChainProblem, CheckpointText, Pruning, RecordedVerification, StoredChain,
88
};
9-
use piquel_common::events::DomainEvent;
9+
use piquel_common::events::{DomainEvent, EventContext};
1010
use piquel_crypto::CryptoError;
1111
use piquel_repository::{
1212
AuditRepository, ChainLink, ChainedEvent, Checkpoint, DatabaseTransaction, RecordedEvent,
@@ -146,18 +146,39 @@ impl AuditChain {
146146
/// Returns [`AuditError`] if the database fails or an event cannot be
147147
/// canonicalized; a broken chain is a result, not an error.
148148
pub(crate) async fn verify(&self, keys: &AuditKeys) -> Result<AuditVerification, AuditError> {
149-
let mut tx = self.database.begin().await?;
149+
Self::verify_in(self.database.begin().await?, keys).await
150+
}
151+
152+
/// [`Self::verify`], in `tx`, a transaction just begun, which it makes see one
153+
/// snapshot and commits.
154+
pub(super) async fn verify_in(
155+
mut tx: DatabaseTransaction<'_>,
156+
keys: &AuditKeys,
157+
) -> Result<AuditVerification, AuditError> {
150158
tx.audit().read_snapshot().await?;
151-
let verification = Self::verify_in(&mut tx, keys).await?;
159+
let verification = Self::verify_snapshot(&mut tx, keys).await?;
152160
tx.commit().await?;
153161
Ok(verification)
154162
}
155163

164+
/// Records `verification`, made as `context`, in `tx`, and commits: the
165+
/// dashboard's audit page shows the newest one recorded.
166+
pub(crate) async fn record(
167+
mut tx: DatabaseTransaction<'_>,
168+
context: &EventContext,
169+
verification: &AuditVerification,
170+
) -> Result<(), AuditError> {
171+
let verified = DomainEvent::AuditChainVerified(verification.clone());
172+
tx.record(context, None, verified).await?;
173+
Ok(tx.commit().await?)
174+
}
175+
156176
/// The dashboard's audit page: the chain as stored, the newest verification
157177
/// the audit log records, and up to [`Self::PAGE`] checkpoints after `after`,
158178
/// or after the anchor, each judged by that verification, all from one
159179
/// snapshot. It recomputes nothing, so it costs the same however long the
160-
/// history: [`Self::verify`] runs only when an operator asks.
180+
/// history: [`Self::verify`] runs only when an operator asks, or the
181+
/// [`Verifier`](super::Verifier) job finds the newest verification too old.
161182
///
162183
/// # Errors
163184
/// Returns [`AuditError`] if the database fails or the recorded verification
@@ -221,7 +242,7 @@ impl AuditChain {
221242
}
222243

223244
/// [`Self::verify`], in a transaction that sees one snapshot.
224-
async fn verify_in(
245+
async fn verify_snapshot(
225246
tx: &mut DatabaseTransaction<'_>,
226247
keys: &AuditKeys,
227248
) -> Result<AuditVerification, AuditError> {

‎apps/auth-service/src/jobs/mod.rs‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
//! workers every replica runs (see `crate::deliveries`).
33
44
use crate::{
5-
AuthConfig, KeyStore, SigningKeys, StartupError,
6-
audit::Sealer,
5+
AuditKeys, AuthConfig, KeyStore, SigningKeys, StartupError,
6+
audit::{Sealer, Verifier},
77
deletion::{DeletionError, Deletions},
88
deliveries::{AnnouncementSender, BackchannelLogoutSender, EmailSender, OutboundClient},
99
};
@@ -80,10 +80,12 @@ pub struct Jobs {
8080
impl Jobs {
8181
/// Starts every job on `database`: signing key rotation in `store` and the
8282
/// reloads of this replica's `keys`, audit chain sealing with `config`'s audit
83-
/// key, and the delivery workers of every channel, configured by `config`.
83+
/// key and its verification, and the delivery workers of every channel,
84+
/// configured by `config`.
8485
///
8586
/// # Errors
86-
/// Fails if the outbound HTTP client cannot initialize.
87+
/// Fails if the committed audit keys are malformed, or the outbound HTTP
88+
/// client cannot initialize.
8789
pub fn start(
8890
database: &Database,
8991
config: &AuthConfig,
@@ -95,6 +97,9 @@ impl Jobs {
9597
AccountPurge::observe();
9698
jobs.exclusive(AccountPurge, database.clone());
9799
jobs.exclusive(Sealer::new(&config.audit), database.clone());
100+
let audit_keys = AuditKeys::for_server(&config.passkey.origin, config.audit.verifier())
101+
.map_err(StartupError::AuditKeys)?;
102+
jobs.exclusive(Verifier::new(audit_keys), database.clone());
98103
let (store, reloaded) = (store.clone(), keys.clone());
99104
jobs.spawn(|shutdown| store.run(reloaded, shutdown));
100105
let logout = BackchannelLogoutSender::new(

‎apps/auth-service/src/lib.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,9 @@ pub enum StartupError {
119119
/// The OIDC metadata or signing keys could not be serialized.
120120
#[error("could not initialize OIDC application")]
121121
Oidc(#[from] oidc::OidcConfigError),
122+
/// The audit keys committed to the repository are malformed.
123+
#[error("could not read the committed audit keys")]
124+
AuditKeys(#[source] AuditError),
122125
/// The HTTP client that sends deliveries could not initialize.
123126
#[error("could not initialize the outbound HTTP client")]
124127
Outbound(#[source] reqwest::Error),

‎crates/common/src/events/mod.rs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -399,8 +399,9 @@ pub enum DomainEvent {
399399
/// How many events were deleted.
400400
deleted: u64,
401401
},
402-
/// The audit chain was verified, by `auth-service audit verify` or from the
403-
/// dashboard, with what that found. It concerns no account.
402+
/// The audit chain was verified, by `auth-service audit verify`, from the
403+
/// dashboard or by auth's own verifier job, with what that found. It concerns
404+
/// no account.
404405
AuditChainVerified(AuditVerification),
405406
/// An administrator or operator sent an announcement, such as a security
406407
/// incident or a change to the privacy policy, to every account or to chosen

‎crates/database/src/exclusive/mod.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ pub enum LockKey {
2626
/// Schema migrations, held by `Database::run_migrations` for its connection, so
2727
/// overlapping `migrate` runs take turns.
2828
Migrations = 7,
29+
/// The periodic verification of the audit chain, apart from
30+
/// [`Self::AuditChain`] so it never holds sealing back.
31+
AuditVerification = 8,
2932
/// The job runner panic test; no release takes it.
3033
#[cfg(any(test, feature = "test-util"))]
3134
Test = -1,

‎crates/ui/src/admin/audit.rs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,8 +160,9 @@ async fn chain_card<'a>(page: &'a AuditPage, uncommitted: bool) -> Result<impl V
160160
<p class="help">
161161
"This is the newest verification the audit log records, not a check made now: \
162162
events sealed since were not checked, and someone with auth's database role could \
163-
record a forged result. Verifying recomputes the whole history, as \
164-
auth-service audit verify does, and records what it finds."
163+
record a forged result. Auth verifies on its own once no one has for six hours. Verifying \
164+
recomputes the whole history, as auth-service audit verify does, and records \
165+
what it finds."
165166
</p>
166167
<div class="row actions"><button class="secondary">"Verify now"</button></div>
167168
</form>

0 commit comments

Comments
 (0)