From ae315c7b7423681d75a350688e6997f0433be0fa Mon Sep 17 00:00:00 2001 From: hsinatfootprintai <149764663+hsinatfootprintai@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:42:45 +0800 Subject: [PATCH 1/2] feat(audit): report a reset audit chain once, at daemon startup (#3772 slice 4a) The anchor manager now checks, as it starts, whether the chain is behind the anchor file's last checkpoint (database recreated empty or restored from an older copy) and reports it through the same state, readiness entry and log line as a refused tick, with the new-epoch command in the message. The ticks that follow do not repeat it, and the refusal counter still counts only refused publishes. Part of #3772 Co-Authored-By: Claude Sonnet 5.5 --- internal/audit/anchor.go | 42 ++++++++- internal/audit/anchor_startup_test.go | 122 ++++++++++++++++++++++++++ internal/policyreadiness/readiness.go | 2 +- 3 files changed, 161 insertions(+), 5 deletions(-) create mode 100644 internal/audit/anchor_startup_test.go diff --git a/internal/audit/anchor.go b/internal/audit/anchor.go index a3b919c45..fb1215652 100644 --- a/internal/audit/anchor.go +++ b/internal/audit/anchor.go @@ -302,6 +302,7 @@ func (m *AnchorManager) Stop() { func (m *AnchorManager) run(ctx context.Context) { defer close(m.done) + m.checkAtStartup(ctx) t := time.NewTicker(m.interval) defer t.Stop() for { @@ -316,6 +317,25 @@ func (m *AnchorManager) run(ctx context.Context) { } } +// checkAtStartup looks, once, at whether the chain is already behind the +// anchor when the daemon starts (#3772): the database was recreated empty or +// restored from an older copy. Without it the first report waits a whole +// interval for the first tick. It reports through the same state, readiness +// callback and log line as a refused tick, and the ticks that follow do not +// repeat the explanation. It is not a refused publish, so it is not counted as +// one. A read failure here is left to the ticks, which log it. +func (m *AnchorManager) checkAtStartup(ctx context.Context) { + last, _, ok, err := m.sink.LastPublished(ctx) + if err != nil || !ok { + return + } + id, err := m.store.MaxRowID(ctx) + if err != nil || id >= last { + return + } + m.markRefused(id, last, false, true) +} + // tick publishes a new anchor at the chain's current tail, if the tail has // advanced since the last successful publish. Every failure is logged // loud and the loop continues — per #1706's "anchor failures are loud," @@ -362,23 +382,37 @@ func (m *AnchorManager) tick(ctx context.Context) { // The first refusal after a success also says, once, what the state means; // the per-tick ERROR line above repeats only the checkpoints. func (m *AnchorManager) recordRefusal(checkpoint, lastAnchored int64) { + m.markRefused(checkpoint, lastAnchored, true, false) +} + +// markRefused is recordRefusal; counted says whether this is a refused publish +// (it is not for the startup check) and atStartup that the daemon found it +// before any tick. +func (m *AnchorManager) markRefused(checkpoint, lastAnchored int64, counted, atStartup bool) { m.stateMu.Lock() was := m.state.Refused m.state.Refused = true m.state.Checkpoint = checkpoint m.state.LastAnchored = lastAnchored - m.state.Refusals++ + if counted { + m.state.Refusals++ + } st := m.state m.stateMu.Unlock() if was { return } if lastAnchored > 0 { - log.Printf("[audit-anchor] DEGRADED: the audit chain is at checkpoint %d, behind the anchor's last checkpoint %d, so every tick refuses to anchor it. "+ + found := "" + if atStartup { + found = " (found at startup)" + } + log.Printf("[audit-anchor] DEGRADED%s: the audit chain is at checkpoint %d, behind the anchor's last checkpoint %d, so every tick refuses to anchor it. "+ "Either the audit database was recreated or restored from an older copy, or its rows were rewritten; the daemon cannot tell which. "+ - "Anchoring resumes on its own once the chain passes checkpoint %d. Keep the anchor file: it is the only record of the anchored history. "+ + "If it was recreated or restored on purpose, record that with `sudo containarium audit anchor new-epoch --reason --confirm-new-epoch`: it archives the anchor file, never deletes it. "+ + "Otherwise anchoring resumes on its own once the chain passes checkpoint %d. Keep the anchor file: it is the only record of the anchored history. "+ "/health reports degraded and `containarium doctor` lists it; see \"The daemon refuses to anchor the audit chain\" in docs/security/OPERATOR-SECURITY-RUNBOOK.md", - checkpoint, lastAnchored, lastAnchored) + found, checkpoint, lastAnchored, lastAnchored) } else { log.Printf("[audit-anchor] DEGRADED: checkpoint %d is already anchored with a different root, so every tick refuses to anchor it: "+ "the audit chain no longer matches what was anchored, or an anchor was planted. Run `containarium audit verify-anchor`. "+ diff --git a/internal/audit/anchor_startup_test.go b/internal/audit/anchor_startup_test.go new file mode 100644 index 000000000..c07268ca1 --- /dev/null +++ b/internal/audit/anchor_startup_test.go @@ -0,0 +1,122 @@ +package audit + +import ( + "context" + "strings" + "testing" + "time" +) + +// #3772: a chain that is already behind the anchor when the daemon starts is +// reported once, at startup, with the way out, instead of after the first tick +// (15 minutes later by default) and then once per tick. +func TestAnchorManager_DetectsAResetChainAtStartup(t *testing.T) { + logs := captureLog(t) + ctx := context.Background() + sink := tempSink(t) + if err := sink.PublishRoot(ctx, 1036, "hash-at-1036"); err != nil { + t.Fatal(err) + } + store := &fakeChainStore{maxID: 106, hashes: map[int64]string{106: "root-106"}} + var changes []AnchorState + m := NewAnchorManager(store, sink, AnchorOptions{OnStateChange: func(st AnchorState) { changes = append(changes, st) }}) + + m.checkAtStartup(ctx) + + st := m.State() + if !st.Refused || st.Checkpoint != 106 || st.LastAnchored != 1036 { + t.Fatalf("state = %+v, want refused at 106 behind 1036", st) + } + if st.Refusals != 0 { + t.Errorf("Refusals = %d; a startup detection is not a refused publish", st.Refusals) + } + if len(changes) != 1 || !changes[0].Refused { + t.Fatalf("state changes = %+v, want exactly one, to refused", changes) + } + out := logs.String() + for _, want := range []string{"at startup", "checkpoint 106", "last checkpoint 1036", "audit anchor new-epoch", "OPERATOR-SECURITY-RUNBOOK.md"} { + if !strings.Contains(out, want) { + t.Errorf("startup message lacks %q:\n%s", want, out) + } + } + + // The ticks that follow must not say it again. + for range 3 { + m.tick(ctx) + } + if n := strings.Count(logs.String(), "DEGRADED"); n != 1 { + t.Errorf("DEGRADED logged %d times across startup and 3 ticks, want once:\n%s", n, logs.String()) + } + if len(changes) != 1 { + t.Errorf("state changes = %d after the ticks, want still 1", len(changes)) + } + if got := m.State().Refusals; got != 3 { + t.Errorf("Refusals = %d after 3 refused ticks, want 3", got) + } +} + +// A database recreated empty has no rows at all, which is the same reset. +func TestAnchorManager_DetectsAnEmptyChainAtStartup(t *testing.T) { + captureLog(t) + ctx := context.Background() + sink := tempSink(t) + if err := sink.PublishRoot(ctx, 50, "r50"); err != nil { + t.Fatal(err) + } + m := NewAnchorManager(&fakeChainStore{maxID: 0}, sink, AnchorOptions{}) + m.checkAtStartup(ctx) + if st := m.State(); !st.Refused || st.Checkpoint != 0 || st.LastAnchored != 50 { + t.Fatalf("state = %+v, want refused: empty chain behind anchor 50", st) + } +} + +func TestAnchorManager_StartupCheckLeavesAHealthyChainAlone(t *testing.T) { + cases := []struct { + name string + anchor int64 + maxID int64 + }{ + {"nothing anchored yet", 0, 10}, + {"chain at the anchor", 50, 50}, + {"chain ahead of the anchor", 50, 80}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + logs := captureLog(t) + ctx := context.Background() + sink := tempSink(t) + if tc.anchor > 0 { + if err := sink.PublishRoot(ctx, tc.anchor, "r"); err != nil { + t.Fatal(err) + } + } + var changes int + m := NewAnchorManager(&fakeChainStore{maxID: tc.maxID}, sink, AnchorOptions{OnStateChange: func(AnchorState) { changes++ }}) + m.checkAtStartup(ctx) + if st := m.State(); st.Refused || changes != 0 || strings.Contains(logs.String(), "DEGRADED") { + t.Errorf("state %+v, %d changes, log %q: want nothing reported", st, changes, logs.String()) + } + }) + } +} + +// Start runs the check right away, not after the first interval. +func TestAnchorManager_StartRunsTheStartupCheck(t *testing.T) { + captureLog(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + sink := tempSink(t) + if err := sink.PublishRoot(ctx, 1036, "r"); err != nil { + t.Fatal(err) + } + m := NewAnchorManager(&fakeChainStore{maxID: 106}, sink, AnchorOptions{Interval: time.Hour}) + m.Start(ctx) + defer m.Stop() + deadline := time.Now().Add(2 * time.Second) + for !m.State().Refused { + if time.Now().After(deadline) { + t.Fatal("no refusal reported within 2s of Start with an hour-long interval") + } + time.Sleep(5 * time.Millisecond) + } +} diff --git a/internal/policyreadiness/readiness.go b/internal/policyreadiness/readiness.go index cd31b1337..abf3ec7c7 100644 --- a/internal/policyreadiness/readiness.go +++ b/internal/policyreadiness/readiness.go @@ -136,7 +136,7 @@ func (r Result) Detail() string { case r.Status == healthpb.HealthCheckResponse_NOT_SERVING && r.Service == OTelCollectorAuthService: return "unavailable (DEGRADED): CONTAINARIUM_OTEL_REQUIRE_AUTH is set but the OTel bearer could not be loaded or minted, so the collector was NOT started (app-emitted telemetry is off); fix the bearer source (CONTAINARIUM_OTEL_BEARER, CONTAINARIUM_OTEL_BEARER_FILE or /etc/containarium/otel.bearer) and restart the daemon" case r.Status == healthpb.HealthCheckResponse_NOT_SERVING && r.Service == AuditAnchorService: - return "unavailable (DEGRADED): every anchoring tick refuses the audit chain's current checkpoint, because the chain is behind the anchor file's last checkpoint (the audit database was recreated or restored from an older copy, or its rows were rewritten) or a checkpoint is anchored with a different root, so tamper-evidence against a privileged rewrite is degraded; the daemon log names the checkpoints, keep the anchor file, and see \"The daemon refuses to anchor the audit chain\" in docs/security/OPERATOR-SECURITY-RUNBOOK.md" + return "unavailable (DEGRADED): every anchoring tick refuses the audit chain's current checkpoint, because the chain is behind the anchor file's last checkpoint (the audit database was recreated or restored from an older copy, or its rows were rewritten) or a checkpoint is anchored with a different root, so tamper-evidence against a privileged rewrite is degraded; the daemon log names the checkpoints; keep the anchor file; if the database was recreated or restored on purpose, record it with `containarium audit anchor new-epoch`; see \"The daemon refuses to anchor the audit chain\" in docs/security/OPERATOR-SECURITY-RUNBOOK.md" case r.Status == healthpb.HealthCheckResponse_NOT_SERVING: return "unavailable: Postgres is configured but the store is not installed; its APIs fail closed (or answer UNAVAILABLE) and its background work (such as the credential-expiry watch) does not run until the daemon's in-process retry reaches the database; a family refused by configuration (the daemon log names it) needs a config fix and a restart instead" case r.Status == healthpb.HealthCheckResponse_SERVICE_UNKNOWN: From 5771997ef5f7652b563cebfdb62060f709908268 Mon Sep 17 00:00:00 2001 From: hsinatfootprintai <149764663+hsinatfootprintai@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:42:57 +0800 Subject: [PATCH 2/2] docs(changelog): fragment for startup detection (#3772) Part of #3772 Co-Authored-By: Claude Sonnet 5.5 --- changelog.d/3892.changed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/3892.changed.md diff --git a/changelog.d/3892.changed.md b/changelog.d/3892.changed.md new file mode 100644 index 000000000..48e666593 --- /dev/null +++ b/changelog.d/3892.changed.md @@ -0,0 +1 @@ +- **A reset audit chain is reported at daemon startup** (#3772). When the audit database was recreated or restored and its chain is behind the anchor file's last checkpoint, the daemon now says so once, when it starts, instead of after the first anchoring interval. The message and `containarium doctor` point at `containarium audit anchor new-epoch` for a deliberate reset. Readiness and `/health` report the state from startup; the refused-publish counter is unchanged.