Skip to content

Commit 669e203

Browse files
committed
feat(auth): the sealer raises an alert when it refuses to sign a checkpoint
When events sealed since the latest checkpoint no longer match their hashes, the sealer signs nothing more until it is fixed, and only logged it. It now raises checkpoint_refused, as the audit_sealer job, saying where, and clears it once the events match again. It is its own kind, so it never flaps with audit_chain_broken, which a full verification may find at an earlier position. Background jobs build their event context with EventContext::system.
1 parent 855108b commit 669e203

12 files changed

Lines changed: 107 additions & 59 deletions

File tree

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

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use chrono::Utc;
1010
use piquel_common::{
1111
admin::{ChainBreak, ChainProblem},
1212
alerts::{AlertAuthor, AlertState, AlertStatus},
13-
events::{Actor, JobName, RequestOrigin},
13+
events::{Actor, JobName},
1414
};
1515
use piquel_repository::{Database, EventFilter, RecordedEvent};
1616

@@ -25,13 +25,7 @@ fn broken(position: u64) -> Alert {
2525
/// Raises `alert` if `Some`, or clears the chain's alert, in a transaction of its
2626
/// own.
2727
async fn found(database: &Database, alert: Option<Alert>) {
28-
let context = EventContext {
29-
actor: Actor::System {
30-
job: JobName::AuditVerification,
31-
},
32-
origin: RequestOrigin::default(),
33-
reason: None,
34-
};
28+
let context = EventContext::system(JobName::AuditVerification);
3529
let mut tx = database.begin().await.expect("transaction");
3630
let mut alerts = Alerts::new(&mut tx, &context);
3731
match alert {
@@ -126,13 +120,7 @@ async fn the_current_alert_changes_only_with_its_condition() {
126120
#[ignore = "requires TEST_DATABASE_URL"]
127121
async fn concurrent_raises_leave_one_alert() {
128122
let database = Harness::isolated().await.database;
129-
let context = EventContext {
130-
actor: Actor::System {
131-
job: JobName::AuditVerification,
132-
},
133-
origin: RequestOrigin::default(),
134-
reason: None,
135-
};
123+
let context = EventContext::system(JobName::AuditVerification);
136124
let mut first = database.begin().await.expect("transaction");
137125
Alerts::new(&mut first, &context)
138126
.raise(broken(5))

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,15 @@
22
33
use super::{AuditChain, AuditError, AuditKeys, Chain, CheckpointText, TrustedCheckpoint};
44
use crate::{
5+
alerts::Alerts,
56
config::AuditConfig,
67
jobs::{ExclusiveJob, Shutdown},
78
};
89
use chrono::{SubsecRound, TimeDelta, Utc};
10+
use piquel_common::{
11+
alerts::{Alert, AlertKind},
12+
events::{EventContext, JobName},
13+
};
914
use piquel_crypto::NoteKey;
1015
use piquel_repository::{
1116
ChainLink, Checkpoint, EventContent, ExclusiveConnection, LockKey, SealedEvent,
@@ -139,6 +144,9 @@ impl Sealer {
139144
/// After a failure, nothing is tried until [`Self::checkpoint_every`] has
140145
/// passed.
141146
///
147+
/// Refusing raises the [`Alert::CheckpointRefused`] alert, and the next
148+
/// recomputation that matches clears it.
149+
///
142150
/// # Errors
143151
/// Returns [`AuditError::Broken`], signing nothing, if the events sealed since
144152
/// that checkpoint no longer match their hashes.
@@ -207,9 +215,16 @@ impl Sealer {
207215
return Ok(());
208216
}
209217
let (head, broken) = AuditChain::walk(&mut tx, start, |_| None).await?;
218+
let context = EventContext::system(JobName::AuditSealer);
219+
let mut alerts = Alerts::new(&mut tx, &context);
210220
if let Some(broken) = broken {
221+
alerts
222+
.raise(Alert::CheckpointRefused(broken.clone()))
223+
.await?;
224+
tx.commit().await?;
211225
return Err(AuditError::Broken(broken));
212226
}
227+
alerts.clear(AlertKind::CheckpointRefused).await?;
213228
let text = CheckpointText {
214229
origin: self.key.verifier().name().to_owned(),
215230
head,

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

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
use super::*;
44
use crate::{
55
AdminError, AdminService, AuthConfig,
6+
alerts::Alerts,
67
config::AuditConfig,
78
tests::{Replicas, operator},
89
};
@@ -384,7 +385,8 @@ async fn recomputed_hashes_do_not_match_signed_checkpoints() {
384385
}
385386

386387
/// The sealer recomputes the events sealed since the latest checkpoint before
387-
/// signing the next one, and refuses to sign a chain that no longer matches.
388+
/// signing the next one, and refuses to sign a chain that no longer matches,
389+
/// raising an alert that says where, which a checkpoint signed later clears.
388390
#[tokio::test]
389391
#[ignore = "requires TEST_DATABASE_URL"]
390392
async fn checkpoints_never_sign_a_chain_that_does_not_match() {
@@ -395,14 +397,43 @@ async fn checkpoints_never_sign_a_chain_that_does_not_match() {
395397
fixture
396398
.tamper(Tamper::EditPayload(7, serde_json::json!({})))
397399
.await;
400+
let at = ChainBreak {
401+
position: 7,
402+
problem: ChainProblem::EventChanged,
403+
};
398404
assert!(matches!(
399405
fixture.sealer.checkpoint(&mut lock).await,
400-
Err(AuditError::Broken(ChainBreak {
401-
position: 7,
402-
problem: ChainProblem::EventChanged
403-
}))
406+
Err(AuditError::Broken(broken)) if broken == at
404407
));
405408
lock.release().await.expect("release");
409+
let mut tx = fixture.database.begin().await.expect("transaction");
410+
let alert = tx
411+
.alerts()
412+
.current(AlertKind::CheckpointRefused)
413+
.await
414+
.expect("current")
415+
.and_then(|current| current.alert);
416+
tx.commit().await.expect("commit");
417+
assert_eq!(alert, Some(Alert::CheckpointRefused(at.clone())));
418+
419+
// Once the events match again, the next checkpoint clears it.
420+
let intact = Fixture::sealed_six().await;
421+
let mut tx = intact.database.begin().await.expect("transaction");
422+
let context = EventContext::system(JobName::AuditSealer);
423+
Alerts::new(&mut tx, &context)
424+
.raise(Alert::CheckpointRefused(at))
425+
.await
426+
.expect("raise");
427+
tx.commit().await.expect("commit");
428+
intact.seal().await;
429+
let mut tx = intact.database.begin().await.expect("transaction");
430+
let current = tx
431+
.alerts()
432+
.current(AlertKind::CheckpointRefused)
433+
.await
434+
.expect("current");
435+
tx.commit().await.expect("commit");
436+
assert_eq!(current, None);
406437
let latest = fixture
407438
.database
408439
.audit()
@@ -946,6 +977,11 @@ async fn sealing_goes_on_when_a_checkpoint_fails() {
946977
fixture
947978
.tamper(Tamper::EditPayload(7, serde_json::json!({})))
948979
.await;
980+
// The first refusal raises its alert, an event of its own; later ones only
981+
// see it again. Raise and seal it before counting.
982+
let refused = fixture.sealer.pass(&mut lock, None).await;
983+
assert!(matches!(refused, Err(AuditError::Broken(_))), "{refused:?}");
984+
fixture.seal_with(&mut lock).await;
949985
fixture.sealer = fixture.sealer.sealing(2, EventContent::UNTAGGED);
950986
let database = fixture.database.clone();
951987
let mut tx = database.begin().await.expect("transaction");

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

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
use super::{AuditChain, AuditError, AuditKeys, AuditVerification};
55
use crate::jobs::{ExclusiveJob, Shutdown};
66
use chrono::{TimeDelta, Utc};
7-
use piquel_common::events::{Actor, EventContext, JobName, RequestOrigin};
7+
use piquel_common::events::{EventContext, JobName};
88
use piquel_repository::{ExclusiveConnection, LockKey};
99
use std::time::Duration;
1010

@@ -36,13 +36,7 @@ impl Verifier {
3636
return Ok(None);
3737
}
3838
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-
};
39+
let context = EventContext::system(JobName::AuditVerification);
4640
AuditChain::record(connection.begin().await?, &context, &verification).await?;
4741
Ok(Some(verification))
4842
}

‎apps/auth-service/src/deliveries/email/tests.rs‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -571,13 +571,7 @@ async fn a_raised_alert_is_emailed_to_active_administrators() {
571571
problem: ChainProblem::EventChanged,
572572
});
573573
let alert_id = AlertId::new();
574-
let context = EventContext {
575-
actor: Actor::System {
576-
job: JobName::AuditVerification,
577-
},
578-
origin: RequestOrigin::default(),
579-
reason: None,
580-
};
574+
let context = EventContext::system(JobName::AuditVerification);
581575
let mut tx = database.begin().await.expect("transaction");
582576
let raised = DomainEvent::AlertRaised {
583577
alert_id,

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

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use crate::{
1010
use chrono::Utc;
1111
use piquel_common::{
1212
AccountStatus, ErrorChain, UserId,
13-
events::{Actor, EventContext, JobName, RequestOrigin},
13+
events::{EventContext, JobName},
1414
};
1515
use piquel_repository::{
1616
Database, DatabaseError, DatabaseTransaction, ExclusiveConnection, LockKey,
@@ -382,14 +382,9 @@ impl AccountPurge {
382382
if user.status != AccountStatus::Deleting || !due {
383383
return Ok(());
384384
}
385-
let context = EventContext {
386-
actor: Actor::System {
387-
job: JobName::AccountPurge,
388-
},
389-
origin: RequestOrigin::default(),
390-
reason: None,
391-
};
392-
Deletions::new(&mut tx, context).purge(&user).await?;
385+
Deletions::new(&mut tx, EventContext::system(JobName::AccountPurge))
386+
.purge(&user)
387+
.await?;
393388
Ok(tx.commit().await?)
394389
}
395390
}

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

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1867,19 +1867,13 @@ async fn alerts_take_updates_from_the_dashboard() {
18671867
use piquel_common::{
18681868
admin::{ChainBreak, ChainProblem},
18691869
alerts::{Alert, AlertKind},
1870-
events::{EventContext, JobName, RequestOrigin},
1870+
events::{EventContext, JobName},
18711871
};
18721872
let harness = Harness::new().await;
18731873
let admin = harness.admin().await;
18741874
// The test database outlives a run, so each raises an alert of its own.
18751875
let position = Utc::now().timestamp_micros().unsigned_abs();
1876-
let context = EventContext {
1877-
actor: Actor::System {
1878-
job: JobName::AuditVerification,
1879-
},
1880-
origin: RequestOrigin::default(),
1881-
reason: None,
1882-
};
1876+
let context = EventContext::system(JobName::AuditVerification);
18831877
let mut tx = harness.database.begin().await.expect("transaction");
18841878
let alert = Alert::AuditChainBroken(ChainBreak {
18851879
position,

‎crates/common/src/alerts.rs‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ crate::str_enum! {
1616
pub enum AlertKind {
1717
/// See [`Alert::AuditChainBroken`].
1818
AuditChainBroken = "audit_chain_broken",
19+
/// See [`Alert::CheckpointRefused`].
20+
CheckpointRefused = "checkpoint_refused",
1921
}
2022
}
2123

@@ -29,6 +31,9 @@ crate::str_enum! {
2931
pub enum Alert {
3032
/// The newest verification of the audit chain found it broken.
3133
AuditChainBroken(ChainBreak),
34+
/// The sealer refuses to sign a checkpoint: the events sealed since the
35+
/// latest one no longer match their hashes.
36+
CheckpointRefused(ChainBreak),
3237
}
3338

3439
impl Alert {
@@ -40,15 +45,18 @@ impl Alert {
4045
pub const fn kind(&self) -> AlertKind {
4146
match self {
4247
Self::AuditChainBroken(_) => AlertKind::AuditChainBroken,
48+
Self::CheckpointRefused(_) => AlertKind::CheckpointRefused,
4349
}
4450
}
4551

4652
/// Its payload version inside a recorded event. A new kind, or a new
4753
/// [`ChainProblem`], is one older releases cannot decode, so it fails to
48-
/// compile here until it is given the next version.
54+
/// compile here until it is given the next version: [`Self::CheckpointRefused`]
55+
/// came in the second.
4956
#[must_use]
5057
pub const fn version(&self) -> i16 {
5158
match self {
59+
Self::CheckpointRefused(_) => 2,
5260
Self::AuditChainBroken(ChainBreak { problem, .. }) => match problem {
5361
ChainProblem::MissingEvent
5462
| ChainProblem::EventBeforeAnchor
@@ -67,6 +75,7 @@ impl Alert {
6775
pub const fn subject(&self) -> &'static str {
6876
match self {
6977
Self::AuditChainBroken(_) => "The audit chain is broken",
78+
Self::CheckpointRefused(_) => "The audit chain's checkpoints stopped",
7079
}
7180
}
7281

@@ -81,6 +90,13 @@ impl Alert {
8190
and the audit history documentation says what each problem means.",
8291
broken.position, broken.problem
8392
),
93+
Self::CheckpointRefused(broken) => format!(
94+
"The sealer refuses to sign a checkpoint: at position {}, {}. Events sealed \
95+
since the latest checkpoint were changed or deleted, so nothing newer is \
96+
signed until it is fixed. Find out what changed; \
97+
docs/dev/security/audit-history.md says what each problem means.",
98+
broken.position, broken.problem
99+
),
84100
}
85101
}
86102
}

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

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,11 +89,11 @@ pub enum JobName {
8989
/// Signing key rotation. Nothing records it yet: a release may write a new
9090
/// value only once the previous release reads it (see `docs/dev/architecture/database.md`).
9191
KeyRotation,
92-
/// The periodic verification of the audit chain. Nothing records it yet,
93-
/// for the same reason.
92+
/// The periodic verification of the audit chain, which records what it found
93+
/// and the alert of a broken chain.
9494
AuditVerification,
95-
/// The sealer of the audit chain, which refuses to sign a checkpoint over
96-
/// events that no longer match. Nothing records it yet, for the same reason.
95+
/// The sealer of the audit chain, which records the alert of a checkpoint it
96+
/// refuses to sign over events that no longer match.
9797
AuditSealer,
9898
}
9999

@@ -240,3 +240,15 @@ pub struct EventContext {
240240
/// and shown to the account's owner in their security history.
241241
pub reason: Option<String>,
242242
}
243+
244+
impl EventContext {
245+
/// What background `job` does on its own, outside any request.
246+
#[must_use]
247+
pub fn system(job: JobName) -> Self {
248+
Self {
249+
actor: Actor::System { job },
250+
origin: RequestOrigin::default(),
251+
reason: None,
252+
}
253+
}
254+
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -438,7 +438,7 @@ impl EventRow<'_> {
438438
let description =
439439
Description::new(format!("{what}: {}", alert.subject())).with("alert", id);
440440
match alert {
441-
Alert::AuditChainBroken(broken) => description
441+
Alert::AuditChainBroken(broken) | Alert::CheckpointRefused(broken) => description
442442
.with("position", broken.position)
443443
.with("problem", broken.problem),
444444
}

0 commit comments

Comments
 (0)