Skip to content

Commit dec1dd2

Browse files
committed
feat(auth): a verifier that keeps failing raises an alert
When the verifier failed to verify the chain, rather than finding it broken or intact, it only logged the error and tried again ten minutes later, so nothing checked the history and nobody heard of it. Now the third failed run in a row on a replica raises the verification_failing alert, and the next recorded verification clears it. One failure may be the database's passing failure, so it raises nothing. Runs in a row are counted by Streak, which cleanup's overruns now use too.
1 parent 46cd5c7 commit dec1dd2

9 files changed

Lines changed: 175 additions & 20 deletions

File tree

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

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -643,6 +643,53 @@ async fn the_verifier_verifies_when_no_verification_is_recent() {
643643
lock.release().await.expect("release");
644644
}
645645

646+
/// The verifier's third failed run in a row raises the alert of a verification
647+
/// that keeps failing; a run that works in between starts the count again, and a
648+
/// recorded verification clears the alert.
649+
#[tokio::test]
650+
#[ignore = "requires TEST_DATABASE_URL"]
651+
async fn a_verification_that_keeps_failing_raises_its_alert() {
652+
let fixture = Fixture::sealed_six().await;
653+
let verifier = Verifier::new(AuditKeys {
654+
source: VerificationKeys::Uncommitted,
655+
..(*fixture.keys).clone()
656+
});
657+
let mut lock = fixture
658+
.database
659+
.try_exclusive(LockKey::AuditVerification)
660+
.await
661+
.expect("lock")
662+
.expect("no other test verifies");
663+
let current = async || {
664+
let mut tx = fixture.database.begin().await.expect("transaction");
665+
let current = tx
666+
.alerts()
667+
.current(AlertKind::VerificationFailing)
668+
.await
669+
.expect("current");
670+
tx.commit().await.expect("commit");
671+
current.and_then(|current| current.alert)
672+
};
673+
let failed = || Err::<(), _>(AuditError::NoKeys);
674+
for _ in 0..2 {
675+
assert!(verifier.ended(&mut lock, failed()).await.is_err());
676+
}
677+
verifier
678+
.ended(&mut lock, Ok(()))
679+
.await
680+
.expect("a run that works");
681+
for _ in 0..2 {
682+
assert!(verifier.ended(&mut lock, failed()).await.is_err());
683+
}
684+
assert_eq!(current().await, None);
685+
assert!(verifier.ended(&mut lock, failed()).await.is_err());
686+
assert_eq!(current().await, Some(Alert::VerificationFailing {}));
687+
688+
verifier.pass(&mut lock).await.expect("verification");
689+
assert_eq!(current().await, None);
690+
lock.release().await.expect("release");
691+
}
692+
646693
/// A verification that finds the chain broken with this environment's keys
647694
/// raises the chain's alert. One with keys an operator gave changes nothing.
648695
#[tokio::test]

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

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22
//! verification without an operator asking for one.
33
44
use super::{AuditChain, AuditError, AuditKeys, AuditVerification, VerificationKeys};
5-
use crate::jobs::{ExclusiveJob, JobCount, Shutdown};
5+
use crate::jobs::{ExclusiveJob, JobCount, Shutdown, Streak};
66
use chrono::{TimeDelta, Utc};
7-
use piquel_common::events::{DomainEvent, EventContext, JobName};
7+
use piquel_common::{
8+
alerts::Alert,
9+
events::{DomainEvent, EventContext, JobName},
10+
};
811
use piquel_repository::{ExclusiveConnection, LockKey, RecordedEvent};
912
use piquel_telemetry::Gauge;
1013
use std::time::Duration;
@@ -23,19 +26,47 @@ static BROKEN: JobCount = JobCount::new(
2326

2427
/// Verifies the whole chain, on one replica at a time, once the newest recorded
2528
/// verification, whoever made it, is [`Self::VERIFY_EVERY`] old, and records
26-
/// what it found as [`JobName::AuditVerification`].
29+
/// what it found as [`JobName::AuditVerification`]. Runs that keep failing raise
30+
/// the [`Alert::VerificationFailing`] alert, which a recorded verification
31+
/// clears.
2732
pub(crate) struct Verifier {
2833
/// The keys it verifies with, the dashboard's (see [`AuditKeys::for_server`]).
2934
keys: AuditKeys,
35+
/// Runs in a row on this replica that failed.
36+
failures: Streak,
3037
}
3138

3239
impl Verifier {
3340
/// How old the newest recorded verification may get.
3441
const VERIFY_EVERY: TimeDelta = TimeDelta::hours(6);
42+
/// Failed runs in a row that raise [`Alert::VerificationFailing`]: a single
43+
/// one may be the database's passing failure.
44+
const FAILING_AFTER: u32 = 3;
3545

3646
/// A verifier checking checkpoints against `keys`.
3747
pub(crate) const fn new(keys: AuditKeys) -> Self {
38-
Self { keys }
48+
Self {
49+
keys,
50+
failures: Streak::new(Self::FAILING_AFTER),
51+
}
52+
}
53+
54+
/// Counts a run that ended with `ran`, raising the alert of a verification
55+
/// that keeps failing once enough fail in a row, and returns how it ended.
56+
pub(super) async fn ended<T>(
57+
&self,
58+
connection: &mut ExclusiveConnection,
59+
ran: Result<T, AuditError>,
60+
) -> Result<T, AuditError> {
61+
if ran.is_ok() {
62+
self.failures.reset();
63+
} else {
64+
let alert = Alert::VerificationFailing {};
65+
self.failures
66+
.failed(connection, JobName::AuditVerification, alert)
67+
.await;
68+
}
69+
ran
3970
}
4071

4172
/// Registers the [`BROKEN`] gauge.
@@ -86,6 +117,7 @@ impl ExclusiveJob for Verifier {
86117
connection: &mut ExclusiveConnection,
87118
_: &Shutdown,
88119
) -> Result<(), AuditError> {
89-
self.pass(connection).await.map(drop)
120+
let ran = self.pass(connection).await;
121+
self.ended(connection, ran).await.map(drop)
90122
}
91123
}

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,8 @@ impl AuditChain {
166166

167167
/// Records `verification`, made as `context`, in `tx`, and commits: the
168168
/// dashboard's audit page shows the newest one recorded. A broken chain raises
169-
/// its alert, and an intact one clears it, unless the keys were given with
169+
/// its alert, and an intact one clears it; either clears the alert of a
170+
/// verification that keeps failing. None of this happens when the keys were given with
170171
/// `--key`, such as another environment's, which say nothing of this one's
171172
/// checkpoints.
172173
pub(crate) async fn record(
@@ -182,6 +183,7 @@ impl AuditChain {
182183
Some(broken) => alerts.raise(Alert::AuditChainBroken(broken.clone())).await,
183184
None => alerts.clear(AlertKind::AuditChainBroken).await,
184185
}?;
186+
alerts.clear(AlertKind::VerificationFailing).await?;
185187
}
186188
Ok(tx.commit().await?)
187189
}

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

Lines changed: 61 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ struct Cleanup {
276276
/// Maximum time spent draining one pass.
277277
budget: Duration,
278278
/// Passes in a row on this replica that ran out of time.
279-
overruns: AtomicU32,
279+
overruns: Streak,
280280
}
281281

282282
impl Cleanup {
@@ -296,7 +296,7 @@ impl Cleanup {
296296
const fn new() -> Self {
297297
Self {
298298
budget: Self::BUDGET,
299-
overruns: AtomicU32::new(0),
299+
overruns: Streak::new(Self::BEHIND_AFTER),
300300
}
301301
}
302302

@@ -356,13 +356,9 @@ impl ExclusiveJob for Cleanup {
356356
let Some(behind) = behind else {
357357
return Ok(());
358358
};
359-
let overruns = if behind {
360-
self.overruns.fetch_add(1, Ordering::Relaxed) + 1
361-
} else {
362-
self.overruns.swap(0, Ordering::Relaxed);
363-
0
364-
};
365-
if (1..Self::BEHIND_AFTER).contains(&overruns) {
359+
if !behind {
360+
self.overruns.reset();
361+
} else if !self.overruns.extend() {
366362
return Ok(());
367363
}
368364
let mut tx = connection.begin().await?;
@@ -377,6 +373,62 @@ impl ExclusiveJob for Cleanup {
377373
}
378374
}
379375

376+
/// Runs in a row on this replica that ended one way, such as cleanup passes that
377+
/// ran out of time, which raise an alert once there are enough of them. A job's
378+
/// lock may move between replicas, so it counts this replica's runs only, and a
379+
/// count lasts until this replica's next run.
380+
pub(crate) struct Streak {
381+
/// Runs in the streak so far.
382+
runs: AtomicU32,
383+
/// Runs in a row that raise the alert.
384+
alert_after: u32,
385+
}
386+
387+
impl Streak {
388+
/// A streak that raises its alert after `alert_after` runs in a row.
389+
pub(crate) const fn new(alert_after: u32) -> Self {
390+
Self {
391+
runs: AtomicU32::new(0),
392+
alert_after,
393+
}
394+
}
395+
396+
/// Counts one more run, and says whether the streak is long enough to alert.
397+
pub(crate) fn extend(&self) -> bool {
398+
self.runs.fetch_add(1, Ordering::Relaxed) + 1 >= self.alert_after
399+
}
400+
401+
/// Ends the streak.
402+
pub(crate) fn reset(&self) {
403+
self.runs.store(0, Ordering::Relaxed);
404+
}
405+
406+
/// Counts a run of `job` that failed, and raises `alert` on `connection`
407+
/// once enough failed in a row. Raising may fail as the run did, such as
408+
/// while the database is down: that is logged, since the run returns its own
409+
/// failure.
410+
pub(crate) async fn failed(
411+
&self,
412+
connection: &mut ExclusiveConnection,
413+
job: JobName,
414+
alert: Alert,
415+
) {
416+
if !self.extend() {
417+
return;
418+
}
419+
let context = EventContext::system(job);
420+
let raised = async {
421+
let mut tx = connection.begin().await?;
422+
Alerts::new(&mut tx, &context).raise(alert).await?;
423+
tx.commit().await
424+
};
425+
if let Err(error) = raised.await {
426+
let error = ErrorChain(&error);
427+
tracing::error!(%error, ?job, "could not raise the alert of a failing job");
428+
}
429+
}
430+
}
431+
380432
/// A count the replica running a periodic job takes after each run, which its
381433
/// gauge reports. Every replica runs the job in turn, so each reports the count
382434
/// of its own latest run, at most one run older than the newest; one whose count

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ async fn cleanup_that_keeps_falling_behind_raises_its_alert() {
252252
// Out of time as soon as it deletes anything.
253253
let cleanup = Cleanup {
254254
budget: Duration::ZERO,
255-
overruns: AtomicU32::new(0),
255+
overruns: Streak::new(Cleanup::BEHIND_AFTER),
256256
};
257257
let current = async || {
258258
let mut tx = database.begin().await.expect("transaction");

‎crates/common/src/alerts.rs‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ crate::str_enum! {
2222
PurgesFailing = "purges_failing",
2323
/// See [`Alert::CleanupBehind`].
2424
CleanupBehind = "cleanup_behind",
25+
/// See [`Alert::VerificationFailing`].
26+
VerificationFailing = "verification_failing",
2527
}
2628
}
2729

@@ -45,6 +47,9 @@ pub enum Alert {
4547
/// Cleanup passes keep running out of time with expired state, personal
4648
/// data past retention or finished deliveries left to delete.
4749
CleanupBehind {},
50+
/// Auth's verifier keeps failing to verify the audit chain, finding it
51+
/// neither broken nor intact, so nothing checks the history meanwhile.
52+
VerificationFailing {},
4853
}
4954

5055
impl Alert {
@@ -59,20 +64,23 @@ impl Alert {
5964
Self::CheckpointRefused(_) => AlertKind::CheckpointRefused,
6065
Self::PurgesFailing {} => AlertKind::PurgesFailing,
6166
Self::CleanupBehind {} => AlertKind::CleanupBehind,
67+
Self::VerificationFailing {} => AlertKind::VerificationFailing,
6268
}
6369
}
6470

6571
/// Its payload version inside a recorded event. A new kind, or a new
6672
/// [`ChainProblem`], is one older releases cannot decode, so it fails to
6773
/// compile here until it is given the next version: [`Self::CheckpointRefused`]
6874
/// came in the second, [`Self::PurgesFailing`] in the third and
69-
/// [`Self::CleanupBehind`] in the fourth.
75+
/// [`Self::CleanupBehind`] in the fourth and [`Self::VerificationFailing`] in
76+
/// the fifth.
7077
#[must_use]
7178
pub const fn version(&self) -> i16 {
7279
match self {
7380
Self::CheckpointRefused(_) => 2,
7481
Self::PurgesFailing {} => 3,
7582
Self::CleanupBehind {} => 4,
83+
Self::VerificationFailing {} => 5,
7684
Self::AuditChainBroken(ChainBreak { problem, .. }) => match problem {
7785
ChainProblem::MissingEvent
7886
| ChainProblem::EventBeforeAnchor
@@ -94,6 +102,7 @@ impl Alert {
94102
Self::CheckpointRefused(_) => "The audit chain's checkpoints stopped",
95103
Self::PurgesFailing {} => "Accounts keep failing to be purged",
96104
Self::CleanupBehind {} => "Cleanup is falling behind",
105+
Self::VerificationFailing {} => "The audit chain can't be verified",
97106
}
98107
}
99108

@@ -126,6 +135,12 @@ impl Alert {
126135
piquel.auth.cleanup metrics show how much each pass deletes. It clears once \
127136
a pass deletes everything due."
128137
.to_owned(),
138+
Self::VerificationFailing {} => "Auth's verifier keeps failing to verify the audit \
139+
chain, without finding it broken or intact, so nothing checks the history \
140+
until it's fixed. Its logs say why, such as an event that can't be read, or \
141+
the database failing. auth-service audit verify shows the same error. It \
142+
clears once a verification is recorded."
143+
.to_owned(),
129144
}
130145
}
131146
}

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,9 @@ impl EventRow<'_> {
439439
Alert::AuditChainBroken(broken) | Alert::CheckpointRefused(broken) => description
440440
.with("position", broken.position)
441441
.with("problem", broken.problem),
442-
Alert::PurgesFailing {} | Alert::CleanupBehind {} => description,
442+
Alert::PurgesFailing {} | Alert::CleanupBehind {} | Alert::VerificationFailing {} => {
443+
description
444+
}
443445
}
444446
}
445447

‎docs/dev/architecture/database.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -589,4 +589,7 @@ changes neither.
589589
The sealer raises `checkpoint_refused` when it refuses to sign a checkpoint over
590590
events that no longer match, and clears it once they match again. The account
591591
purge raises `purges_failing` while accounts keep failing to be purged, and
592-
cleanup raises `cleanup_behind` once its passes keep running out of time.
592+
cleanup raises `cleanup_behind` once its passes keep running out of time. The
593+
verifier raises `verification_failing` once its runs keep failing, and a
594+
recorded verification clears it. The jobs count runs in a row with `Streak`,
595+
on each replica.

‎docs/dev/security/audit-history.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,9 @@ so an absent gauge does not mean intact. A verification that
219219
finds the chain broken raises the `audit_chain_broken` alert, which the
220220
dashboard's Alerts tab and `auth-service alerts list` show,
221221
and the next one that finds it intact clears it. One with keys given with
222-
`--key` changes neither. The admin dashboard's
222+
`--key` changes neither. When the verifier itself fails three runs in a row on
223+
one replica, finding the chain neither broken nor intact, it raises the
224+
`verification_failing` alert, and the next recorded verification clears it. The admin dashboard's
223225
Audit tab shows the newest one and when it was made, beside the chain as stored,
224226
so loading it costs the same however long the history. It recomputes nothing
225227
until an administrator presses **Verify now**, which runs the same

0 commit comments

Comments
 (0)