Skip to content

Commit c853cd9

Browse files
authored
perf(admin): the audit page loads in constant time, and verifies the chain only when asked (#386)
The dashboard's Audit tab recomputed the whole audit chain on every load, so each view cost O(history). It now reads the chain as stored and the newest verification recorded. Verify now runs the same AdminService operation as the CLI's audit verify, and every verification is recorded as an audit_chain_verified event, which the page shows with when it ran.
1 parent 5585c40 commit c853cd9

19 files changed

Lines changed: 540 additions & 157 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ just auth session revoke <session-id> # one session, as `user show` lists it
259259
just auth session revoke-all alice # every session of the account
260260
just auth audit list --user alice --kind session_revoked
261261
just auth audit list --user alice --views # with administrators' views of the account
262-
just auth audit verify # recompute the tamper-evident chain
262+
just auth audit verify # recompute the tamper-evident chain, and record what it found
263263
just auth account alice passkeys list # the account's settings, as its owner sees them
264264
just auth account alice name set "Alice B" --reason "Asked by email"
265265
just auth account alice passkeys revoke <passkey-id> --reason "Phone stolen"

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

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -53,30 +53,34 @@ impl AdminService {
5353
Ok(EventPage { events, paging })
5454
}
5555

56-
/// Recomputes the audit chain and checks every checkpoint against `keys`. A
57-
/// broken chain is a result, naming where it breaks.
56+
/// Recomputes the audit chain and checks every checkpoint against `keys`, and
57+
/// records what it found, which the dashboard's audit page shows. A broken
58+
/// chain is a result, naming where it breaks.
5859
pub(crate) async fn verify_audit_chain(
5960
&self,
6061
operator: &Operator,
6162
keys: &AuditKeys,
6263
) -> Result<AuditVerification, AdminError> {
6364
operator.authorize_read(&self.database).await?;
64-
Ok(AuditChain::new(self.database.clone()).verify(keys).await?)
65+
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?;
70+
Ok(verification)
6571
}
6672

67-
/// [`Self::verify_audit_chain`], with up to 100 checkpoints after `after`, or
68-
/// after the anchor, and whether the chain may be pruned through each, by the
69-
/// rules [`Self::prune_audit_chain`] applies.
73+
/// The chain as stored, the newest verification [`Self::verify_audit_chain`]
74+
/// recorded, and up to 100 checkpoints after `after`, or after the anchor, with
75+
/// whether the chain may be pruned through each, by the rules
76+
/// [`Self::prune_audit_chain`] applies to that verification. Verifies nothing.
7077
pub(crate) async fn audit_page(
7178
&self,
7279
operator: &Operator,
73-
keys: &AuditKeys,
7480
after: Option<u64>,
7581
) -> Result<AuditPage, AdminError> {
7682
operator.authorize_read(&self.database).await?;
77-
Ok(AuditChain::new(self.database.clone())
78-
.page(keys, after)
79-
.await?)
83+
Ok(AuditChain::new(self.database.clone()).page(after).await?)
8084
}
8185

8286
/// Deletes every event through the checkpoint at `through`, which becomes the

‎apps/auth-service/src/admin/tests/reads.rs‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,7 @@ impl AdminOperation {
6464
.verify_audit_chain(operator, &committed_keys())
6565
.await
6666
.map(drop),
67-
service
68-
.audit_page(operator, &committed_keys(), None)
69-
.await
70-
.map(drop),
67+
service.audit_page(operator, None).await.map(drop),
7168
],
7269
// Pruning checks its operator before anything else too.
7370
Self::PruneAuditChain => vec![

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ mod verify;
1919

2020
pub(crate) use piquel_common::admin::{
2121
AuditCheckpoint, AuditPage, AuditVerification, ChainBreak, ChainPoint, ChainProblem, Pruning,
22-
VerificationKeys,
22+
RecordedVerification, StoredChain, VerificationKeys,
2323
};
2424
pub(crate) use routes::AuditApplication;
2525
pub(crate) use sealer::Sealer;
@@ -192,7 +192,7 @@ pub struct AuditKeys {
192192
/// The verifier keys.
193193
verifiers: NoteVerifiers,
194194
/// Where they came from, as the verification reports it.
195-
source: VerificationKeys,
195+
pub(crate) source: VerificationKeys,
196196
}
197197

198198
impl AuditKeys {

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

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -416,47 +416,78 @@ async fn pruning_refuses_broken_chains_and_leaves_a_working_anchor() {
416416
assert_eq!(pruned.len(), 2);
417417
}
418418

419-
/// The dashboard's audit page judges each checkpoint by `audit prune`'s rules:
420-
/// from a break on, none may be pruned through, and once pruned, the page starts
421-
/// after the anchor.
419+
/// The dashboard's audit page verifies nothing: it shows the newest verification
420+
/// recorded, so a break shows only once an operator verifies again, and judges each
421+
/// checkpoint by `audit prune`'s rules against that verification. Once pruned, the
422+
/// page starts after the anchor.
422423
#[tokio::test]
423424
#[ignore = "requires TEST_DATABASE_URL"]
424-
async fn the_audit_page_says_where_pruning_is_allowed() {
425-
let pruning = async |fixture: &Fixture, after| {
425+
async fn the_audit_page_shows_the_newest_recorded_verification() {
426+
let page = async |fixture: &Fixture, after| {
426427
AuditChain::new(fixture.database.clone())
427-
.page(&fixture.keys, after)
428+
.page(after)
428429
.await
429430
.expect("page")
430-
.checkpoints
431-
.into_iter()
432-
.map(|checkpoint| (checkpoint.point.position, checkpoint.pruning))
431+
};
432+
let pruning = |page: &AuditPage| {
433+
page.checkpoints
434+
.iter()
435+
.map(|checkpoint| (checkpoint.point.position, checkpoint.pruning.clone()))
433436
.collect::<Vec<_>>()
434437
};
438+
let verify = async |fixture: &Fixture| {
439+
AdminService::new(fixture.database.clone(), false)
440+
.verify_audit_chain(&operator(), &fixture.keys)
441+
.await
442+
.expect("verification")
443+
};
435444
let broken = Fixture::sealed_six().await;
445+
let unverified = page(&broken, None).await;
446+
assert_eq!(unverified.verified, None);
436447
assert_eq!(
437-
pruning(&broken, None).await,
438-
[(3, Pruning::Prunable), (6, Pruning::Prunable)]
448+
unverified.chain.newest.map(|newest| newest.position),
449+
Some(6)
439450
);
451+
let intact = verify(&broken).await;
440452
broken
441453
.tamper(Tamper::EditPayload(5, serde_json::json!({})))
442454
.await;
455+
let stale = page(&broken, None).await;
456+
assert_eq!(
457+
pruning(&stale),
458+
[(3, Pruning::Prunable), (6, Pruning::Prunable)]
459+
);
460+
assert_eq!(
461+
stale.verified.map(|verified| verified.verification),
462+
Some(intact)
463+
);
464+
let found = verify(&broken).await;
443465
let at = ChainBreak {
444466
position: 5,
445467
problem: ChainProblem::EventChanged,
446468
};
469+
assert_eq!(found.broken.as_ref(), Some(&at));
470+
let reverified = page(&broken, None).await;
447471
assert_eq!(
448-
pruning(&broken, None).await,
472+
pruning(&reverified),
449473
[(3, Pruning::Prunable), (6, Pruning::Broken(at))]
450474
);
475+
assert_eq!(
476+
reverified.verified.map(|verified| verified.verification),
477+
Some(found)
478+
);
451479

452480
let pruned = Fixture::sealed_six().await;
453481
AdminService::new(pruned.database.clone(), false)
454482
.prune_audit_chain(&operator(), &pruned.keys, 3)
455483
.await
456484
.expect("prune");
457-
assert_eq!(pruning(&pruned, None).await, [(6, Pruning::Prunable)]);
458485
assert_eq!(
459-
pruning(&pruned, Some(0)).await,
486+
pruning(&page(&pruned, None).await),
487+
[(6, Pruning::Prunable)]
488+
);
489+
assert_eq!(
490+
pruning(&page(&pruned, Some(0)).await),
460491
[(3, Pruning::Pruned { anchor: 3 }), (6, Pruning::Prunable)]
461492
);
462493
}

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

Lines changed: 50 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
//! Recomputes the chain from its anchor, checks every checkpoint against it, and
2-
//! checks that it verifies before it is pruned.
2+
//! checks that it verifies before it is pruned. Also reads the dashboard's audit
3+
//! page, which shows the newest verification recorded instead of making one.
34
45
use super::{
56
AuditChain, AuditCheckpoint, AuditError, AuditKeys, AuditPage, AuditVerification, Chain,
6-
ChainBreak, ChainProblem, CheckpointText, Pruning,
7+
ChainBreak, ChainProblem, CheckpointText, Pruning, RecordedVerification, StoredChain,
78
};
9+
use piquel_common::events::DomainEvent;
810
use piquel_crypto::CryptoError;
9-
use piquel_repository::{ChainLink, Checkpoint, DatabaseTransaction};
11+
use piquel_repository::{ChainLink, Checkpoint, DatabaseTransaction, RecordedEvent};
1012
use std::collections::BTreeMap;
1113

1214
/// A checkpoint checked on its own, before the chain is compared with it.
@@ -75,26 +77,46 @@ impl AuditChain {
7577
Ok(verification)
7678
}
7779

78-
/// Verifies the chain, and returns it with up to [`Self::PAGE`] checkpoints after
79-
/// `after`, or after the anchor, each judged by [`Self::pruning`], all from one
80-
/// snapshot.
80+
/// The dashboard's audit page: the chain as stored, the newest verification
81+
/// the audit log records, and up to [`Self::PAGE`] checkpoints after `after`,
82+
/// or after the anchor, each judged by that verification, all from one
83+
/// snapshot. It recomputes nothing, so it costs the same however long the
84+
/// history: [`Self::verify`] runs only when an operator asks.
8185
///
8286
/// # Errors
83-
/// As [`Self::verify`].
84-
pub(crate) async fn page(
85-
&self,
86-
keys: &AuditKeys,
87-
after: Option<u64>,
88-
) -> Result<AuditPage, AuditError> {
87+
/// Returns [`AuditError`] if the database fails or the recorded verification
88+
/// does not decode.
89+
pub(crate) async fn page(&self, after: Option<u64>) -> Result<AuditPage, AuditError> {
8990
let mut tx = self.database.begin().await?;
9091
tx.audit().read_snapshot().await?;
91-
let verification = Self::verify_in(&mut tx, keys).await?;
92-
let after = after.unwrap_or_else(|| {
93-
verification
94-
.anchor
95-
.as_ref()
96-
.map_or(0, |anchor| anchor.position)
97-
});
92+
let point = |checkpoint: Checkpoint| {
93+
ChainLink {
94+
position: checkpoint.position,
95+
hash: checkpoint.head,
96+
}
97+
.point()
98+
};
99+
let chain = StoredChain {
100+
anchor: tx.audit().anchor().await?.map(point),
101+
newest: tx.audit().head().await?.as_ref().map(Chain::point),
102+
unsealed: tx.audit().unsealed_count().await?,
103+
};
104+
// A verification a newer release recorded reads as unknown, so as none.
105+
let verified =
106+
tx.events()
107+
.newest_audit_verification()
108+
.await?
109+
.and_then(|stored| match stored.event {
110+
RecordedEvent::Known(DomainEvent::AuditChainVerified(verification)) => {
111+
Some(RecordedVerification {
112+
at: stored.occurred_at,
113+
verification,
114+
})
115+
}
116+
_ => None,
117+
});
118+
let after =
119+
after.unwrap_or_else(|| chain.anchor.as_ref().map_or(0, |anchor| anchor.position));
98120
// One more than a page tells whether another follows.
99121
let mut stored = tx.audit().checkpoints(after, Self::PAGE + 1).await?;
100122
tx.commit().await?;
@@ -103,38 +125,25 @@ impl AuditChain {
103125
let next = more
104126
.then(|| stored.last().map(|checkpoint| checkpoint.position))
105127
.flatten();
128+
let broken = verified
129+
.as_ref()
130+
.and_then(|verified| verified.verification.broken.as_ref());
106131
let checkpoints = stored
107132
.into_iter()
108133
.map(|checkpoint| AuditCheckpoint {
109-
point: ChainLink {
110-
position: checkpoint.position,
111-
hash: checkpoint.head,
112-
}
113-
.point(),
134+
pruning: Pruning::of(chain.anchor.as_ref(), broken, checkpoint.position),
114135
signed_at: checkpoint.created_at,
115-
pruning: Self::pruning(&verification, checkpoint.position),
136+
point: point(checkpoint),
116137
})
117138
.collect();
118139
Ok(AuditPage {
119-
verification,
140+
chain,
141+
verified,
120142
checkpoints,
121143
next,
122144
})
123145
}
124146

125-
/// Whether `verification`'s chain may be pruned through the checkpoint at
126-
/// `position`: only after the anchor, and only if the chain verifies through it.
127-
/// `audit prune` and the dashboard's audit page both apply it.
128-
fn pruning(verification: &AuditVerification, position: u64) -> Pruning {
129-
match (&verification.anchor, &verification.broken) {
130-
(Some(anchor), _) if anchor.position >= position => Pruning::Pruned {
131-
anchor: anchor.position,
132-
},
133-
(_, Some(broken)) if broken.position <= position => Pruning::Broken(broken.clone()),
134-
_ => Pruning::Prunable,
135-
}
136-
}
137-
138147
/// [`Self::verify`], in a transaction that sees one snapshot.
139148
async fn verify_in(
140149
tx: &mut DatabaseTransaction<'_>,
@@ -313,7 +322,8 @@ impl AuditChain {
313322
return Err(AuditError::NoCheckpoint(through));
314323
}
315324
let verification = self.verify(keys).await?;
316-
match Self::pruning(&verification, through) {
325+
let (anchor, broken) = (verification.anchor.as_ref(), verification.broken.as_ref());
326+
match Pruning::of(anchor, broken, through) {
317327
Pruning::Prunable => Ok(()),
318328
Pruning::Pruned { anchor } => Err(AuditError::AlreadyPruned { anchor }),
319329
Pruning::Broken(broken) => Err(AuditError::Broken(broken)),

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,9 @@ use std::path::PathBuf;
1818
pub(super) enum AuditCommand {
1919
/// Page through recorded events, newest first.
2020
List(ListEvents),
21-
/// Recompute the chain and check every checkpoint against it. Exits non-zero,
22-
/// naming the first position that does not match, when the chain is broken.
21+
/// Recompute the chain and check every checkpoint against it, and record what
22+
/// it found, which the dashboard's Audit tab shows. Exits non-zero, naming the
23+
/// first position that does not match, when the chain is broken.
2324
Verify {
2425
/// The keys to check checkpoints against.
2526
#[command(flatten)]

‎apps/auth-service/src/web/admin/audit.rs‎

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22
33
use super::AdminApplication as App;
44
use crate::{AdminError, AuditKeys};
5+
use serde::de::IgnoredAny;
56
use topcoat::{
67
Result,
78
context::Cx,
8-
router::{StatusCode, href, query_params, response::Response, route},
9+
router::{StatusCode, content::Form, href, query_params, response::Response, route},
910
view::view,
1011
};
1112

@@ -16,23 +17,35 @@ struct AuditQuery {
1617
after: Option<u64>,
1718
}
1819

19-
/// `/audit`: the chain verified as `auth-service audit verify` does, and its
20-
/// checkpoints, each with whether the chain may be pruned through it and the
21-
/// command that would. Pruning itself needs the database owner, so the page
22-
/// changes nothing.
23-
#[route(GET "/audit")]
24-
pub(super) async fn verify(cx: &Cx) -> Result<Response> {
20+
/// `/audit`: the chain as stored and as its newest recorded verification found
21+
/// it, and its checkpoints, each with whether the chain may be pruned through it
22+
/// and the command that would. Showing it verifies nothing; posting its form
23+
/// verifies the whole chain, as `auth-service audit verify` does, and comes back
24+
/// to the page, which then shows that verification. Pruning itself needs the
25+
/// database owner, so the page never prunes.
26+
#[route([GET, POST] "/audit")]
27+
pub(super) async fn verify(cx: &Cx, form: Option<Form<IgnoredAny>>) -> Result<Response> {
2528
let admin = App::admin(cx).await?;
2629
let app = App::of(cx);
2730
let query = query_params::<AuditQuery>(cx)?;
2831
let keys = AuditKeys::for_server(&app.auth, &app.audit_key).map_err(AdminError::from)?;
29-
let page = &app
30-
.service
31-
.audit_page(&admin.operator, &keys, query.after)
32-
.await?;
33-
let later = page
34-
.next
35-
.map(|after| format!("{}?after={after}", href!(verify).resolve(cx)));
36-
let view = view! { cx => piquel_ui::audit_page(page: page, later: later) };
32+
let here = href!(verify).resolve(cx);
33+
let refusal = App::submit(cx, form, here.clone(), |_| async {
34+
app.service
35+
.verify_audit_chain(&admin.operator, &keys)
36+
.await
37+
.map(drop)
38+
})
39+
.await?;
40+
let page = &app.service.audit_page(&admin.operator, query.after).await?;
41+
let later = page.next.map(|after| format!("{here}?after={after}"));
42+
let view = view! { cx =>
43+
piquel_ui::audit_page(
44+
page: page,
45+
keys: keys.source,
46+
refusal: refusal.as_deref(),
47+
later: later,
48+
)
49+
};
3750
App::render(cx, StatusCode::OK, "Audit", view).await
3851
}

0 commit comments

Comments
 (0)