Skip to content

Commit e9095db

Browse files
authored
fix(auth): the audit sealer only builds on checkpoints that verify, and signs on schedule under load (#369)
The sealer had several gaps: - It trusted whatever checkpoint was newest in the database, without checking its signature, and `/audit/checkpoints/latest` served it the same way. - Under sustained traffic it only checked for a due checkpoint once a batch came back short, so a backlog postponed signing. - Histories listed events by `sequence`, which the chain doesn't cover, so anyone with the schema owner's rights could reorder displayed history without breaking verification. - The canonical event had no format tag, so any future field would break every existing hash. Closes #251. Stacked on #361 (#250): its migration is 0036, after #361's 0035. It merges after #361, and GitHub then retargets it to `main`. ## What changes - **Checkpoints that don't verify:** - The sealer builds on the newest checkpoint the environment's audit keys verify, or on the anchor if that's newer. It also trusts its own key, so an uncommitted key can't make it distrust and re-sign its own checkpoints. - Someone with auth's database role but not the key can plant checkpoints the database can't check. The sealer logs them, counts them in `piquel.auth.audit.untrusted_checkpoints`, and passes over them. - It looks past at most 1,000. Past that, as removing a key that signed for days would leave, it recomputes from the anchor and signs above them rather than failing. - If a planted checkpoint holds the head's position, the sealer stops before recomputing anything. - `/audit/checkpoints/latest` serves only a checkpoint that verifies. The list endpoint still serves every stored one, for readers to verify themselves. - **Under load:** - The sealer checks whether a checkpoint is due after every batch, and the interval counts only from a trusted checkpoint. - A failed checkpoint no longer ends the pass: sealing goes on. The next try waits one interval, timed on a monotonic clock from when the attempt ended, so a broken chain isn't recomputed on every pass. - **Order:** - Histories list events by `(txid, sequence)`, the order they're sealed in, through a new index. - `audit verify` and the sealer report a new `out_of_order` problem when that order disagrees with the chain, including across the checkpoint the sealer starts from. - `sequence` alone legitimately disagrees with sealing order when transactions overlap, so it isn't compared on its own. - A verification that finds `out_of_order` is recorded in payload version 2 of `audit_chain_verified`, which older releases read as unknown. - **Format tag:** - `domain_events.chain_format` (migration 0036) records each sealed event's canonical format. Format 1 is today's untagged form; format 2 only adds `"format": 2`. - This release verifies both but keeps sealing format 1, so every deploy and rollback stays verifiable. A one-line follow-up starts sealing format 2. - The column accepts only 1 and 2, so a forged value reads as a changed event at its position. - **Errors:** note verification no longer reports OpenSSL failures as an invalid signature, and an `after` past 2^63−1 gets a 400 instead of a 500. ## Left as is, on purpose - **Repeated planting:** the database role can seal events itself. Someone who keeps sealing one and planting a checkpoint at the new head can keep postponing signing while their access lasts. The sealer logs and counts every plant, and `audit verify` reports them. Closing this would mean letting several checkpoints share a position, a primary key change; listed under Limits. - **Moving the database:** the order check and the history order assume transaction IDs only increase. A logical dump restored into a new cluster breaks that, so the docs say to move the database with `pg_upgrade` or a physical copy. - **Follow-ups:** - caching `/latest` while planted checkpoints are present; - finding the trusted checkpoint once per pass rather than once per batch; - the admin dashboard's `/audit?after=` overflow. ## Deploying and rolling back - **Deploy:** migration 0036 adds the column, which PostgreSQL 11+ adds without rewriting the table, and builds one index on `domain_events`. The build blocks writes to that table while it runs; with no real users yet, that's brief. - **Beside the previous release:** it keeps working beside this one: - its events get the default format 1, and it seals in format 1 without touching the column; - it lists histories by `sequence`, through the old index, which stays until no release needs it (a pending contract). Existing sealed events are all format 1 and were sealed in `(txid, sequence)` order since #159, so they verify unchanged, `out_of_order` included. - **During the rollout:** a request that pages with `before` across an old and a new replica can briefly skip or repeat events, since the two releases order history differently. Nothing is stored wrong. - **Rolling back:** the previous image runs on this schema. Everything this release seals is format 1, so the previous release still verifies the whole chain and keeps signing. As with any migration, its `migrate` job refuses a database with a migration it doesn't know (sqlx's `VersionMissing`), so a rollback runs the previous image without that job. ## Proof - `forged_checkpoints_are_passed_over_and_not_served`: a checkpoint signed by another key, dated ahead, is never served and postpones nothing. - `forged_checkpoints_are_never_built_on`: a forged checkpoint over a tampered event isn't built on. - `checkpoints_never_sign_events_out_of_order`, across the starting checkpoint. - `signing_resumes_above_too_many_untrusted_checkpoints`: with 1,001 planted checkpoints, the sealer recomputes and signs above them. - `sealing_goes_on_when_a_checkpoint_fails`. - `signing_resumes_from_the_anchor_when_no_checkpoint_verifies`: after a prune, with no checkpoint that verifies, signing resumes from the anchor. - `a_failed_checkpoint_is_retried_after_the_interval`. - `checkpoints_keep_their_interval_while_batches_stay_full`. - `the_chain_format_is_per_event`. - `verification_checks_the_recorded_order`. - `checkpoints_are_published`, which also covers the 400. - Garbage signatures read as invalid, not as provider failures. - On the final head, rebased onto `main` with #361: `just db test` passes, 389 of 389, as do the query cache check, clippy and fmt. Reviewed with review-loop: 5 rounds with 2× GPT 6.1 Sol and 3× Claude Opus 5.5, all on xhigh, together with #361. Sol hit its usage limit in rounds 2–4, and both Sol reviewers reviewed the final heads in round 5. Verdict: approved by all five. > [!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 2755f40 commit e9095db

30 files changed

Lines changed: 1079 additions & 202 deletions

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

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ pub(crate) use piquel_common::admin::{
2323
};
2424
pub(crate) use routes::AuditApplication;
2525
pub(crate) use sealer::Sealer;
26+
pub(crate) use verify::TrustedCheckpoint;
2627

2728
use base64::{Engine, engine::general_purpose::STANDARD};
2829
use chrono::{DateTime, SecondsFormat, Utc};
@@ -82,6 +83,17 @@ pub enum AuditError {
8283
/// No checkpoint was signed at the position to prune through.
8384
#[error("no checkpoint was signed at position {0}; prune through a checkpoint's position")]
8485
NoCheckpoint(u64),
86+
/// An event was sealed in a format this release does not know, by a newer one.
87+
#[error(
88+
"the event at position {position} was sealed in chain format {format}, which this \
89+
release does not know; use a newer release"
90+
)]
91+
UnknownFormat {
92+
/// The event's position.
93+
position: u64,
94+
/// Its format.
95+
format: i16,
96+
},
8597
}
8698

8799
/// How the chain extends: each event's hash covers the hash before it and its
@@ -91,6 +103,10 @@ trait Chain: Sized {
91103
const GENESIS: Self;
92104

93105
/// The link of `content`, sealed right after this one.
106+
///
107+
/// # Errors
108+
/// Returns [`AuditError::UnknownFormat`] for a format newer than
109+
/// [`EventContent::NEWEST_FORMAT`], or [`AuditError::Canonical`].
94110
fn extend(&self, content: &EventContent) -> Result<Self, AuditError>;
95111

96112
/// This link as verification reports it.
@@ -116,6 +132,12 @@ impl Chain for ChainLink {
116132

117133
fn extend(&self, content: &EventContent) -> Result<Self, AuditError> {
118134
let position = self.position + 1;
135+
if content.format() > EventContent::NEWEST_FORMAT {
136+
return Err(AuditError::UnknownFormat {
137+
position,
138+
format: content.format(),
139+
});
140+
}
119141
let canonical = serde_json_canonicalizer::to_vec(&CanonicalEvent { position, content })
120142
.map_err(AuditError::Canonical)?;
121143
let mut input = self.hash.to_vec();
@@ -233,6 +255,21 @@ impl AuditKeys {
233255
}
234256
}
235257

258+
/// The keys the server trusts the checkpoints it builds on and publishes with:
259+
/// [`Self::for_server`]'s, and always its `own`, which signs them. Without it,
260+
/// an uncommitted key would make the sealer distrust, and re-sign, its own
261+
/// checkpoints; `audit verify` still reports them against the committed keys.
262+
///
263+
/// # Errors
264+
/// Returns [`AuditError::Keys`] if the committed file is malformed.
265+
pub(crate) fn for_sealer(origin: &Origin, own: &NoteVerifier) -> Result<Self, AuditError> {
266+
let keys = Self::for_server(origin, own)?;
267+
Ok(Self {
268+
verifiers: keys.verifiers.with(own),
269+
..keys
270+
})
271+
}
272+
236273
/// The name of the audit key of the environment at `origin`, which is also its
237274
/// checkpoints' origin line.
238275
pub(crate) fn name(origin: &Origin) -> String {

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

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Publishes signed checkpoints, so anyone can keep copies the server cannot
22
//! change and later check that the history still extends them.
33
4-
use super::{Chain, ChainPoint};
4+
use super::{AuditKeys, Chain, ChainPoint};
55
use crate::{
66
routes::audit,
77
security::{ApiError, CacheClass, Cached},
@@ -16,19 +16,23 @@ use axum::{
1616
use chrono::{DateTime, Utc};
1717
use piquel_repository::{ChainLink, Checkpoint, Database};
1818
use serde::{Deserialize, Serialize};
19+
use std::sync::Arc;
1920

2021
/// Public, cacheable checkpoint routes. Checkpoints hold only positions and
2122
/// hashes, so serving them reveals nothing but how many events were recorded.
2223
#[derive(Clone)]
2324
pub(crate) struct AuditApplication {
2425
/// Where checkpoints are stored.
2526
database: Database,
27+
/// Verifies the latest checkpoint before it is served.
28+
keys: Arc<AuditKeys>,
2629
}
2730

2831
/// The query of [`audit::CHECKPOINTS`].
2932
#[derive(Deserialize)]
3033
struct CheckpointQuery {
31-
/// Only checkpoints after this position; all of them when absent.
34+
/// Only checkpoints after this position; all of them when absent. Positions
35+
/// fit in a signed 64-bit integer.
3236
#[serde(default)]
3337
after: u64,
3438
}
@@ -69,9 +73,10 @@ impl AuditApplication {
6973
max_age: std::time::Duration::from_secs(60),
7074
};
7175

72-
/// Builds the routes over `database`.
73-
pub(crate) const fn new(database: Database) -> Self {
74-
Self { database }
76+
/// Builds the routes over `database`, serving only a latest checkpoint `keys`
77+
/// verify.
78+
pub(crate) const fn new(database: Database, keys: Arc<AuditKeys>) -> Self {
79+
Self { database, keys }
7580
}
7681

7782
/// Returns the checkpoint routes with this application as state.
@@ -82,14 +87,18 @@ impl AuditApplication {
8287
.with_state(self)
8388
}
8489

85-
/// The newest checkpoint's signed note, as `text/plain`.
90+
/// The signed note of the newest checkpoint that verifies, as `text/plain`.
91+
/// Newer ones that do not are never served; `audit verify` reports them.
8692
async fn latest(State(app): State<Self>) -> Result<Response, ApiError> {
8793
let checkpoint = app
88-
.database
89-
.audit()
90-
.latest_checkpoint()
91-
.await?
92-
.ok_or_else(|| ApiError::not_found("no checkpoint has been signed yet"))?;
94+
.keys
95+
.newest_trusted(&mut app.database.audit())
96+
.await
97+
.map_err(ApiError::internal)?
98+
.trusted
99+
.ok_or_else(|| {
100+
ApiError::not_found("no checkpoint that verifies has been signed yet")
101+
})?;
93102
Ok(Cached(
94103
Self::CACHE,
95104
(
@@ -105,6 +114,11 @@ impl AuditApplication {
105114
State(app): State<Self>,
106115
Query(query): Query<CheckpointQuery>,
107116
) -> Result<Response, ApiError> {
117+
if i64::try_from(query.after).is_err() {
118+
return Err(ApiError::bad_request(
119+
"after must be at most 9223372036854775807",
120+
));
121+
}
108122
let checkpoints: Vec<PublishedCheckpoint> = app
109123
.database
110124
.audit()

0 commit comments

Comments
 (0)