From 8c7170ef919ec75bb7dbe81bdf090efd0ca2e66d Mon Sep 17 00:00:00 2001 From: hsinatfootprintai <149764663+hsinatfootprintai@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:29:08 +0800 Subject: [PATCH 1/7] feat(audit): verify-anchor reports a recorded epoch break and checks its archive (#3772 slice 3a) FileSink.VerifyBreaks checks each break's archive is present, matches its recorded sha256 and ends at the recorded last anchor, following breaks inside archives. verify-anchor prints each break as a break and fails when an archive no longer backs it. Bucket and TSA checks across a break are not in this slice. Part of #3772 Co-Authored-By: Claude Sonnet 5.5 --- internal/audit/anchor_epoch.go | 79 +++++++++++ internal/audit/anchor_epoch_verify_test.go | 145 +++++++++++++++++++++ internal/cmd/audit.go | 26 +++- internal/cmd/audit_anchor.go | 30 +++++ internal/cmd/audit_anchor_breaks_test.go | 69 ++++++++++ 5 files changed, 345 insertions(+), 4 deletions(-) create mode 100644 internal/audit/anchor_epoch_verify_test.go create mode 100644 internal/cmd/audit_anchor_breaks_test.go diff --git a/internal/audit/anchor_epoch.go b/internal/audit/anchor_epoch.go index 4988551a2..8990c3ba5 100644 --- a/internal/audit/anchor_epoch.go +++ b/internal/audit/anchor_epoch.go @@ -225,3 +225,82 @@ func (f *FileSink) Breaks() ([]EpochBreak, error) { } return out, nil } + +// BreakCheck is one epoch break and whether the archive it names still backs +// it. An empty Problem means the archive is present, unchanged and ends at the +// anchor the break records. +type BreakCheck struct { + Break EpochBreak + Problem string +} + +// VerifyBreaks checks every break in the anchor file, and every break inside +// the archives those name. A break is evidence only while its archive is still +// there, byte for byte (sha256), and ends at the anchor the break records; a +// missing or changed archive is reported, not skipped, so deleting the old +// history after a break cannot pass as a clean one. +func (f *FileSink) VerifyBreaks() ([]BreakCheck, error) { + f.mu.Lock() + defer f.mu.Unlock() + data, err := os.ReadFile(f.path) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("audit: read anchor file: %w", err) + } + seen := map[string]bool{} + return checkBreaksIn(data, seen), nil +} + +// checkBreaksIn checks the breaks in one anchor file's bytes, following each +// into its archive. seen guards against an archive that names itself. +func checkBreaksIn(data []byte, seen map[string]bool) []BreakCheck { + var out []BreakCheck + for _, line := range strings.Split(string(data), "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + _, brk, ok := parseAnchorLine(line) + if !ok || brk == nil { + continue + } + c := BreakCheck{Break: *brk} + archive, err := os.ReadFile(brk.ArchivedTo) + switch { + case errors.Is(err, os.ErrNotExist): + c.Problem = fmt.Sprintf("the archive %s is missing", brk.ArchivedTo) + case err != nil: + c.Problem = fmt.Sprintf("the archive %s cannot be read: %v", brk.ArchivedTo, err) + default: + sum := sha256.Sum256(archive) + if hex.EncodeToString(sum[:]) != brk.ArchivedSHA256 { + c.Problem = fmt.Sprintf("the archive %s no longer matches its recorded sha256", brk.ArchivedTo) + } else if cp, root, found := lastAnchorIn(archive); !found || cp != brk.LastCheckpoint || root != brk.LastRoot { + c.Problem = fmt.Sprintf("the archive %s does not end at the last anchor the break records (checkpoint %d)", brk.ArchivedTo, brk.LastCheckpoint) + } + } + out = append(out, c) + if err == nil && !seen[brk.ArchivedTo] { + seen[brk.ArchivedTo] = true + out = append(out, checkBreaksIn(archive, seen)...) + } + } + return out +} + +// lastAnchorIn is lastPublishedLocked over bytes. +func lastAnchorIn(data []byte) (int64, string, bool) { + lines := strings.Split(string(data), "\n") + for i := len(lines) - 1; i >= 0; i-- { + line := strings.TrimSpace(lines[i]) + if line == "" { + continue + } + if rec, brk, ok := parseAnchorLine(line); ok && brk == nil { + return rec.Checkpoint, rec.Root, true + } + } + return 0, "", false +} diff --git a/internal/audit/anchor_epoch_verify_test.go b/internal/audit/anchor_epoch_verify_test.go new file mode 100644 index 000000000..64a2ce85f --- /dev/null +++ b/internal/audit/anchor_epoch_verify_test.go @@ -0,0 +1,145 @@ +package audit + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func problems(cs []BreakCheck) []string { + var out []string + for _, c := range cs { + out = append(out, c.Problem) + } + return out +} + +// #3772 slice 3: a recorded break is evidence only while the archive it names +// is still there, unchanged, and ends where the break says it did. +func TestVerifyBreaks_IntactArchiveIsVerified(t *testing.T) { + s, _ := newEpochSink(t, 10, 20) + b, err := s.NewEpoch(epochOpts()) + if err != nil { + t.Fatal(err) + } + cs, err := s.VerifyBreaks() + if err != nil { + t.Fatal(err) + } + if len(cs) != 1 || cs[0].Problem != "" || cs[0].Break.ArchivedSHA256 != b.ArchivedSHA256 { + t.Fatalf("checks = %+v", cs) + } +} + +func TestVerifyBreaks_NoBreaksIsNoChecks(t *testing.T) { + s, _ := newEpochSink(t, 10) + cs, err := s.VerifyBreaks() + if err != nil || len(cs) != 0 { + t.Fatalf("checks = %+v, err %v", cs, err) + } +} + +func TestVerifyBreaks_FlagsAMissingOrChangedArchive(t *testing.T) { + cases := []struct { + name string + mut func(archive string) error + want string + }{ + {"missing", func(a string) error { return os.Remove(a) }, "missing"}, + {"edited", func(a string) error { + f, err := os.OpenFile(a, os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + return err + } + defer f.Close() + _, err = f.WriteString("{\"checkpoint\":5,\"root\":\"x\"}\n") + return err + }, "sha256"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s, _ := newEpochSink(t, 10, 20) + b, err := s.NewEpoch(epochOpts()) + if err != nil { + t.Fatal(err) + } + if err := tc.mut(b.ArchivedTo); err != nil { + t.Fatal(err) + } + cs, err := s.VerifyBreaks() + if err != nil { + t.Fatal(err) + } + if len(cs) != 1 || !strings.Contains(cs[0].Problem, tc.want) { + t.Fatalf("problems = %q; want one mentioning %q", problems(cs), tc.want) + } + }) + } +} + +// A break whose recorded last anchor is not the archive's last anchor does not +// describe that archive, even when the sha256 matches. +func TestVerifyBreaks_FlagsAWrongLastCheckpoint(t *testing.T) { + dir := t.TempDir() + archive := filepath.Join(dir, "a.archived-x") + body := []byte("{\"checkpoint\":20,\"root\":\"r20\"}\n") + if err := os.WriteFile(archive, body, 0o600); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(body) + line, _ := json.Marshal(EpochBreak{Kind: anchorKindEpochBreak, At: epochTestNow.Format(time.RFC3339Nano), + Actor: "a", Reason: "r", ArchivedTo: archive, ArchivedSHA256: hex.EncodeToString(sum[:]), + LastCheckpoint: 999, LastRoot: "r999"}) + path := filepath.Join(dir, "a") + if err := os.WriteFile(path, append(line, '\n'), 0o600); err != nil { + t.Fatal(err) + } + s, err := NewFileSink(path) + if err != nil { + t.Fatal(err) + } + cs, err := s.VerifyBreaks() + if err != nil || len(cs) != 1 || !strings.Contains(cs[0].Problem, "last anchor") { + t.Fatalf("checks = %+v, err %v", cs, err) + } +} + +// Two epochs: the second archive holds the first break, so both are checked, +// and tampering with the oldest archive is still seen from the live file. +func TestVerifyBreaks_FollowsBreaksInsideArchives(t *testing.T) { + s, _ := newEpochSink(t, 10, 20) + first, err := s.NewEpoch(epochOpts()) + if err != nil { + t.Fatal(err) + } + if err := s.PublishRoot(context.Background(), 3, "r3"); err != nil { + t.Fatal(err) + } + later := epochOpts() + later.Now = func() time.Time { return epochTestNow.Add(time.Hour) } + if _, err := s.NewEpoch(later); err != nil { + t.Fatal(err) + } + cs, err := s.VerifyBreaks() + if err != nil || len(cs) != 2 { + t.Fatalf("checks = %+v, err %v; want 2", cs, err) + } + for _, c := range cs { + if c.Problem != "" { + t.Errorf("unexpected problem %q", c.Problem) + } + } + if err := os.Remove(first.ArchivedTo); err != nil { + t.Fatal(err) + } + cs, _ = s.VerifyBreaks() + if len(cs) != 2 || !strings.Contains(strings.Join(problems(cs), "|"), "missing") { + t.Fatalf("after deleting the oldest archive: %q", problems(cs)) + } +} diff --git a/internal/cmd/audit.go b/internal/cmd/audit.go index 52d62190c..0569661a4 100644 --- a/internal/cmd/audit.go +++ b/internal/cmd/audit.go @@ -397,13 +397,19 @@ func verifyStartID(from int64, base audit.ChainBase, purged bool) (int64, string } func runAuditVerifyAnchor(cmd *cobra.Command, args []string) error { - ctx := context.Background() - store, cleanup, err := openAuditStore(ctx) + // Epoch breaks (#3772) are read from the anchor file alone, so they are + // reported before, and regardless of, the database check below. + sink, err := audit.NewFileSink(resolveAnchorPath()) if err != nil { - return err + return fmt.Errorf("open anchor sink %q: %w", resolveAnchorPath(), err) } - defer cleanup() + breakErr := reportAnchorBreaks(sink, os.Stdout, os.Stderr) + return errors.Join(breakErr, verifyAnchorAgainstChain(cmd, args)) +} +// resolveAnchorPath is the anchor file this run checks: --anchor-path, else +// $CONTAINARIUM_AUDIT_ANCHOR_PATH, else the daemon's default. +func resolveAnchorPath() string { path := auditAnchorPath if path == "" { path = os.Getenv("CONTAINARIUM_AUDIT_ANCHOR_PATH") @@ -411,6 +417,18 @@ func runAuditVerifyAnchor(cmd *cobra.Command, args []string) error { if path == "" { path = defaultAuditAnchorPath } + return path +} + +func verifyAnchorAgainstChain(cmd *cobra.Command, args []string) error { + ctx := context.Background() + store, cleanup, err := openAuditStore(ctx) + if err != nil { + return err + } + defer cleanup() + + path := resolveAnchorPath() sink, err := audit.NewFileSink(path) if err != nil { return fmt.Errorf("open anchor sink %q: %w", path, err) diff --git a/internal/cmd/audit_anchor.go b/internal/cmd/audit_anchor.go index 9e8ad25d4..424d28e04 100644 --- a/internal/cmd/audit_anchor.go +++ b/internal/cmd/audit_anchor.go @@ -178,3 +178,33 @@ func runAuditAnchorNewEpoch(cmd *cobra.Command, _ []string) error { req.Logger = store return runAnchorNewEpoch(ctx, req, cmd.OutOrStdout()) } + +// reportAnchorBreaks prints every recorded epoch break in the anchor file, as a +// break and not as tampering, and fails when a break's archive is missing, +// changed, or does not end where the break says. A drop in the anchor with no +// break record is not touched here: the chain check still fails it. +func reportAnchorBreaks(sink *audit.FileSink, out, errOut io.Writer) error { + checks, err := sink.VerifyBreaks() + if err != nil { + return fmt.Errorf("check anchor epoch breaks: %w", err) + } + var bad int + for _, c := range checks { + b := c.Break + fmt.Fprintf(out, "\n ⚠ Anchor epoch break recorded %s by %s: %q\n", b.At, b.Actor, b.Reason) + fmt.Fprintf(out, " The earlier anchors (last: checkpoint %d) are archived at %s (sha256 %s).\n", b.LastCheckpoint, b.ArchivedTo, b.ArchivedSHA256) + if c.Problem != "" { + bad++ + fmt.Fprintf(errOut, " ✗ %s\n", c.Problem) + } else { + fmt.Fprintln(out, " Archive present and unchanged. This is a recorded break, not tampering.") + } + } + if len(checks) > 0 { + fmt.Fprintln(out) + } + if bad > 0 { + return fmt.Errorf("%d anchor epoch break(s) are not backed by their archive", bad) + } + return nil +} diff --git a/internal/cmd/audit_anchor_breaks_test.go b/internal/cmd/audit_anchor_breaks_test.go new file mode 100644 index 000000000..c8ec2c633 --- /dev/null +++ b/internal/cmd/audit_anchor_breaks_test.go @@ -0,0 +1,69 @@ +//go:build !containarium_client + +package cmd + +import ( + "bytes" + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/footprintai/containarium/internal/audit" +) + +func brokenSink(t *testing.T) (*audit.FileSink, audit.EpochBreak) { + t.Helper() + sink, err := audit.NewFileSink(filepath.Join(t.TempDir(), "anchors.jsonl")) + if err != nil { + t.Fatal(err) + } + if err := sink.PublishRoot(context.Background(), 42, "abc"); err != nil { + t.Fatal(err) + } + b, err := sink.NewEpoch(audit.EpochOptions{Actor: "alice", Reason: "database restored from backup"}) + if err != nil { + t.Fatal(err) + } + return sink, b +} + +// #3772 slice 3: a recorded break is reported as a break, with who/why and the +// archive's state, and does not fail the run while the archive backs it. +func TestReportAnchorBreaks_RecordedBreakIsReportedNotFailed(t *testing.T) { + sink, b := brokenSink(t) + var out, errOut bytes.Buffer + if err := reportAnchorBreaks(sink, &out, &errOut); err != nil { + t.Fatalf("err = %v; want nil for a break its archive backs", err) + } + for _, want := range []string{"epoch break", "alice", "database restored from backup", b.ArchivedTo, b.ArchivedSHA256[:12], "checkpoint 42"} { + if !strings.Contains(out.String(), want) { + t.Errorf("output lacks %q:\n%s", want, out.String()) + } + } +} + +func TestReportAnchorBreaks_NoBreakPrintsNothing(t *testing.T) { + sink, err := audit.NewFileSink(filepath.Join(t.TempDir(), "a.jsonl")) + if err != nil { + t.Fatal(err) + } + var out, errOut bytes.Buffer + if err := reportAnchorBreaks(sink, &out, &errOut); err != nil || out.Len()+errOut.Len() != 0 { + t.Fatalf("err %v, output %q %q", err, out.String(), errOut.String()) + } +} + +// Deleting the archive after a break must not pass as a clean break. +func TestReportAnchorBreaks_MissingArchiveFails(t *testing.T) { + sink, b := brokenSink(t) + if err := os.Remove(b.ArchivedTo); err != nil { + t.Fatal(err) + } + var out, errOut bytes.Buffer + err := reportAnchorBreaks(sink, &out, &errOut) + if err == nil || !strings.Contains(errOut.String(), "missing") { + t.Fatalf("err = %v, stderr %q; want a failure naming the missing archive", err, errOut.String()) + } +} From 4239adbbf67bd458b15a3cf3abbac4dae501cdd3 Mon Sep 17 00:00:00 2001 From: hsinatfootprintai <149764663+hsinatfootprintai@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:29:22 +0800 Subject: [PATCH 2/7] docs(changelog): fragment for verify-anchor epoch breaks (#3772) Part of #3772 Co-Authored-By: Claude Sonnet 5.5 --- changelog.d/3772.changed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/3772.changed.md diff --git a/changelog.d/3772.changed.md b/changelog.d/3772.changed.md new file mode 100644 index 000000000..1f8cb434f --- /dev/null +++ b/changelog.d/3772.changed.md @@ -0,0 +1 @@ +- **`audit verify-anchor` reports a recorded anchor epoch break** (#3772). A break made by `audit anchor new-epoch` is printed as a break (when, who, why, the archive and its sha256) instead of being invisible, and the run fails if the archive is missing, has changed, or does not end at the anchor the break records. A drop in the anchor with no break record still fails as before. The bucket and timestamp-token copies are not yet checked across a break. From 0245671263f3e5f725ae005fc3985b082753fa2c Mon Sep 17 00:00:00 2001 From: hsinatfootprintai <149764663+hsinatfootprintai@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:43:20 +0800 Subject: [PATCH 3/7] test(audit): check the Close error in the archive-edit helper (#3772) Part of #3772 Co-Authored-By: Claude Sonnet 5.5 --- internal/audit/anchor_epoch_verify_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/audit/anchor_epoch_verify_test.go b/internal/audit/anchor_epoch_verify_test.go index 64a2ce85f..c473b2c63 100644 --- a/internal/audit/anchor_epoch_verify_test.go +++ b/internal/audit/anchor_epoch_verify_test.go @@ -57,7 +57,7 @@ func TestVerifyBreaks_FlagsAMissingOrChangedArchive(t *testing.T) { if err != nil { return err } - defer f.Close() + defer func() { _ = f.Close() }() _, err = f.WriteString("{\"checkpoint\":5,\"root\":\"x\"}\n") return err }, "sha256"}, From ba946830e47ba15ca1ed2e8e6e771664111d3fde Mon Sep 17 00:00:00 2001 From: hsinatfootprintai <149764663+hsinatfootprintai@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:50:44 +0800 Subject: [PATCH 4/7] feat(audit): number anchor epochs; bucket and timestamp tokens follow them (#3772 slice 3b) Each break records the epoch it starts. The bucket sink and the timestamp-token directory key their objects by checkpoint alone, so epoch n>1 publishes under epoch-/ and .tsa/epoch-/ (epoch 1 keeps the original names). verify-anchor checks the current epoch there as before and each earlier epoch against its verified archive: an object or token the archive does not hold fails. Part of #3772 Co-Authored-By: Claude Sonnet 5.5 --- internal/audit/anchor_epoch.go | 68 +++++++ internal/audit/anchor_epoch_publish_test.go | 186 ++++++++++++++++++ internal/audit/anchor_epoch_seal.go | 188 ++++++++++++++++++ internal/audit/anchor_epoch_seal_test.go | 200 ++++++++++++++++++++ internal/audit/anchor_gcs.go | 65 ++++++- internal/audit/anchor_tsa.go | 49 ++++- internal/audit/anchor_tsa_verify.go | 6 +- internal/audit/anchor_verify.go | 12 +- internal/cmd/audit.go | 20 +- internal/cmd/audit_anchor.go | 24 +++ internal/cmd/audit_anchor_breaks_test.go | 31 +++ 11 files changed, 828 insertions(+), 21 deletions(-) create mode 100644 internal/audit/anchor_epoch_publish_test.go create mode 100644 internal/audit/anchor_epoch_seal.go create mode 100644 internal/audit/anchor_epoch_seal_test.go diff --git a/internal/audit/anchor_epoch.go b/internal/audit/anchor_epoch.go index 8990c3ba5..52de63646 100644 --- a/internal/audit/anchor_epoch.go +++ b/internal/audit/anchor_epoch.go @@ -51,6 +51,12 @@ type EpochBreak struct { // LastCheckpoint and LastRoot are the last anchor the archived file held. LastCheckpoint int64 `json:"last_checkpoint"` LastRoot string `json:"last_root"` + // Epoch is the number of the epoch this break starts: 2 for the first + // break. A file with no break is epoch 1. A break written before epochs were + // numbered has none (0) and counts as 2. The bucket and the timestamp-token + // directory key their objects by checkpoint alone, so each epoch publishes + // under its own prefix (epoch 1 keeps the original names). + Epoch int `json:"epoch,omitempty"` } // EpochOptions says who is breaking the anchor and why. Both are required: a @@ -122,9 +128,14 @@ func (f *FileSink) NewEpoch(opts EpochOptions) (EpochBreak, error) { return EpochBreak{}, errors.New("audit: the anchor file holds no anchor: nothing to start a new epoch from") } + epoch, err := f.currentEpochLocked() + if err != nil { + return EpochBreak{}, err + } at := now().UTC() sum := sha256.Sum256(old) b := EpochBreak{ + Epoch: epoch + 1, Kind: anchorKindEpochBreak, At: at.Format(time.RFC3339Nano), Actor: actor, @@ -232,6 +243,9 @@ func (f *FileSink) Breaks() ([]EpochBreak, error) { type BreakCheck struct { Break EpochBreak Problem string + // Anchors are the anchors the archive holds, set only when Problem is + // empty: it is then the verified record of the epoch before the break. + Anchors []AnchorCheckpoint } // VerifyBreaks checks every break in the anchor file, and every break inside @@ -281,6 +295,9 @@ func checkBreaksIn(data []byte, seen map[string]bool) []BreakCheck { c.Problem = fmt.Sprintf("the archive %s does not end at the last anchor the break records (checkpoint %d)", brk.ArchivedTo, brk.LastCheckpoint) } } + if err == nil && c.Problem == "" { + c.Anchors = anchorsIn(archive) + } out = append(out, c) if err == nil && !seen[brk.ArchivedTo] { seen[brk.ArchivedTo] = true @@ -304,3 +321,54 @@ func lastAnchorIn(data []byte) (int64, string, bool) { } return 0, "", false } + +// CurrentEpoch is the epoch the anchor file is in: 1 for a file with no break, +// else the number its last break records. +func (f *FileSink) CurrentEpoch() (int, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.currentEpochLocked() +} + +func (f *FileSink) currentEpochLocked() (int, error) { + data, err := os.ReadFile(f.path) + if errors.Is(err, os.ErrNotExist) { + return 1, nil + } + if err != nil { + return 0, fmt.Errorf("audit: read anchor file: %w", err) + } + epoch := 1 + for _, line := range strings.Split(string(data), "\n") { + if _, brk, ok := parseAnchorLine(strings.TrimSpace(line)); ok && brk != nil { + epoch = brk.epochNumber() + } + } + return epoch, nil +} + +// epochNumber is Epoch, with an unnumbered (older) break counted as epoch 2. +func (b EpochBreak) epochNumber() int { + if b.Epoch > 0 { + return b.Epoch + } + return 2 +} + +// epochDirName is the sub-path an epoch after the first publishes under. +func epochDirName(epoch int) string { return fmt.Sprintf("epoch-%d", epoch) } + +// anchorsIn lists every anchor in an anchor file's bytes, in file order. +func anchorsIn(data []byte) []AnchorCheckpoint { + var out []AnchorCheckpoint + for _, line := range strings.Split(string(data), "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + if rec, brk, ok := parseAnchorLine(line); ok && brk == nil { + out = append(out, AnchorCheckpoint{Checkpoint: rec.Checkpoint, Root: rec.Root}) + } + } + return out +} diff --git a/internal/audit/anchor_epoch_publish_test.go b/internal/audit/anchor_epoch_publish_test.go new file mode 100644 index 000000000..ad7e8f5f3 --- /dev/null +++ b/internal/audit/anchor_epoch_publish_test.go @@ -0,0 +1,186 @@ +package audit + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +const epochBucketURI = "gs://example-bucket/audit-anchors" + +func epochBucketSetup(t *testing.T, g *fakeGcloud, file *FileSink) (RootSink, *GCSAnchorSink) { + t.Helper() + sink, bucket, err := AnchorSinkFor(file, epochBucketURI, func(uri string) (*GCSAnchorSink, error) { return newGCSAnchorSink(uri, g.run) }) + if err != nil { + t.Fatal(err) + } + return sink, bucket +} + +// #3772 3b: epochs are numbered. Epoch 1 is a file with no break. +func TestNewEpoch_NumbersTheEpochs(t *testing.T) { + s, _ := newEpochSink(t, 10, 20) + if e, err := s.CurrentEpoch(); err != nil || e != 1 { + t.Fatalf("before any break: epoch %d, %v; want 1", e, err) + } + b, err := s.NewEpoch(epochOpts()) + if err != nil || b.Epoch != 2 { + t.Fatalf("first break: %+v, %v; want epoch 2", b, err) + } + if e, _ := s.CurrentEpoch(); e != 2 { + t.Fatalf("after the first break: epoch %d, want 2", e) + } + if err := s.PublishRoot(context.Background(), 3, "r3"); err != nil { + t.Fatal(err) + } + later := epochOpts() + later.Now = func() time.Time { return epochTestNow.Add(time.Hour) } + b, err = s.NewEpoch(later) + if err != nil || b.Epoch != 3 { + t.Fatalf("second break: %+v, %v; want epoch 3", b, err) + } + if e, _ := s.CurrentEpoch(); e != 3 { + t.Fatalf("after the second break: epoch %d, want 3", e) + } +} + +// A break written before epochs were numbered is the first break: epoch 2. +func TestCurrentEpoch_ABreakWithoutANumberIsEpoch2(t *testing.T) { + path := filepath.Join(t.TempDir(), "a") + line := `{"kind":"epoch_break","at":"2026-12-02T10:30:00Z","actor":"a","reason":"r","archived_to":"x","archived_sha256":"y","last_checkpoint":1,"last_root":"r"}` + "\n" + if err := os.WriteFile(path, []byte(line), 0o600); err != nil { + t.Fatal(err) + } + s, err := NewFileSink(path) + if err != nil { + t.Fatal(err) + } + if e, err := s.CurrentEpoch(); err != nil || e != 2 { + t.Fatalf("epoch %d, %v; want 2", e, err) + } +} + +// The reason for numbering: epoch 2 restarts at low checkpoints, and the +// bucket keys objects by checkpoint. It must publish under its own prefix, not +// collide with epoch 1's objects or inherit its "last published". +func TestBucket_PublishesANewEpochUnderItsOwnPrefix(t *testing.T) { + ctx := context.Background() + g := newFakeGcloud() + file := tempSink(t) + tee, bucket := epochBucketSetup(t, g, file) + for _, cp := range []int64{10, 20, 1036} { + if err := tee.PublishRoot(ctx, cp, "old-"+itoa(cp)); err != nil { + t.Fatal(err) + } + } + epoch1 := g.objectURIs() + if _, err := file.NewEpoch(epochOpts()); err != nil { + t.Fatal(err) + } + + if _, _, ok, err := bucket.LastPublished(ctx); err != nil || ok { + t.Fatalf("bucket LastPublished right after a break: ok %v, %v; want nothing anchored in the new epoch", ok, err) + } + // Checkpoint 10 again, with another root: a conflict in epoch 1's namespace. + if err := tee.PublishRoot(ctx, 10, "new-10"); err != nil { + t.Fatalf("publish in the new epoch: %v", err) + } + var added []string + have := map[string]bool{} + for _, u := range epoch1 { + have[u] = true + } + for _, u := range g.objectURIs() { + if !have[u] { + added = append(added, u) + } + } + want := "gs://example-bucket/audit-anchors/epoch-2/00000000000000000010.json" + if len(added) != 1 || added[0] != want { + t.Fatalf("new objects = %v, want exactly %s", added, want) + } + for _, u := range epoch1 { + if !strings.Contains(string(g.objects[u]), "old-") { + t.Errorf("epoch 1 object %s changed: %s", u, g.objects[u]) + } + } + if cp, root, ok, err := bucket.LastPublished(ctx); err != nil || !ok || cp != 10 || root != "new-10" { + t.Fatalf("LastPublished = %d %q %v %v", cp, root, ok, err) + } +} + +// Epoch 1's own listing must not read epoch 2's objects as its anchors, with +// either shape of `gcloud storage ls` (nested objects, or a directory line). +func TestBucket_AnEarlierEpochListsOnlyItsOwnObjects(t *testing.T) { + ctx := context.Background() + g := newFakeGcloud() + file := tempSink(t) + tee, bucket := epochBucketSetup(t, g, file) + if err := tee.PublishRoot(ctx, 1036, "old"); err != nil { + t.Fatal(err) + } + if _, err := file.NewEpoch(epochOpts()); err != nil { + t.Fatal(err) + } + if err := tee.PublishRoot(ctx, 7, "new"); err != nil { + t.Fatal(err) + } + run := func(c context.Context, in []byte, args ...string) (string, error) { + out, err := g.run(c, in, args...) + if err == nil && len(args) > 1 && args[1] == "ls" { + out += "gs://example-bucket/audit-anchors/epoch-2/\n" + } + return out, err + } + old, err := newGCSAnchorSink(epochBucketURI, run) + if err != nil { + t.Fatal(err) + } + cps, unrecognised, err := old.AtEpoch(1).ListCheckpoints(ctx) + if err != nil || len(cps) != 1 || cps[0].Checkpoint != 1036 || len(unrecognised) != 0 { + t.Fatalf("epoch 1: %+v, unrecognised %v, %v; want only checkpoint 1036", cps, unrecognised, err) + } + cps, unrecognised, err = bucket.AtEpoch(2).ListCheckpoints(ctx) + if err != nil || len(cps) != 1 || cps[0].Checkpoint != 7 || len(unrecognised) != 0 { + t.Fatalf("epoch 2: %+v, unrecognised %v, %v; want only checkpoint 7", cps, unrecognised, err) + } +} + +func TestTSA_AnEpochStoresItsTokensInItsOwnDirectory(t *testing.T) { + a := newValidTestTSA(t, "a") + file, sink, _ := newTSAFixture(t, a, a) + ctx := context.Background() + tee := NewTeeSink(file, sink) + if err := tee.PublishRoot(ctx, 10, "old-10"); err != nil { + t.Fatal(err) + } + if _, err := file.NewEpoch(epochOpts()); err != nil { + t.Fatal(err) + } + if _, _, ok, err := sink.LastPublished(ctx); err != nil || ok { + t.Fatalf("LastPublished right after a break: ok %v, %v; want nothing stamped yet", ok, err) + } + if err := tee.PublishRoot(ctx, 10, "new-10"); err != nil { + t.Fatalf("publish in the new epoch: %v", err) + } + base := TSATokenDir(file.path) + for _, p := range []string{ + filepath.Join(base, "00000000000000000010.tsr"), + filepath.Join(base, "epoch-2", "00000000000000000010.tsr"), + } { + if _, err := os.Stat(p); err != nil { + t.Errorf("expected token %s: %v", p, err) + } + } + if got, want := sink.TokenDir(), filepath.Join(base, "epoch-2"); got != want { + t.Errorf("TokenDir = %q, want %q", got, want) + } + // Epoch 1's directory lists its own token only. + cps, unrecognised, err := listTSATokens(base) + if err != nil || len(cps) != 1 || len(unrecognised) != 0 { + t.Fatalf("epoch 1 listing: %v, unrecognised %v, %v", cps, unrecognised, err) + } +} diff --git a/internal/audit/anchor_epoch_seal.go b/internal/audit/anchor_epoch_seal.go new file mode 100644 index 000000000..f9984579d --- /dev/null +++ b/internal/audit/anchor_epoch_seal.go @@ -0,0 +1,188 @@ +package audit + +import ( + "context" + "crypto/x509" + "errors" + "fmt" + "path/filepath" +) + +// #3772 3b: epochs before the current one are sealed history. Their database +// rows are gone (the database was recreated or restored), so they are not +// compared with it. What can be checked is that the external copies of an old +// epoch (its bucket prefix, its timestamp tokens) hold exactly what the epoch's +// archive holds, and the archive is itself pinned by the sha256 in the break +// record. A checkpoint in an old epoch's copy that the archive lacks is the +// unexplained kind and fails. + +// SealedEpochFinding is one failure or warning about an earlier epoch. +type SealedEpochFinding struct { + Epoch int + Checkpoint int64 + Detail string +} + +// SealedEpochReport is the result of checking the epochs before the current one. +type SealedEpochReport struct { + Failures []SealedEpochFinding + Warnings []SealedEpochFinding + // Epochs is how many sealed epochs were looked at. + Epochs int +} + +// OK reports whether there are no failures. +func (r SealedEpochReport) OK() bool { return len(r.Failures) == 0 } + +// sealedEpoch is one earlier epoch and what its archive says it held. +type sealedEpoch struct { + epoch int + problem string // non-empty: the archive cannot vouch for the epoch + roots map[int64][]string +} + +// sealedEpochs lists the epochs before the current one, newest first. The +// break at position i of VerifyBreaks started epoch current-i, and its archive +// is the file of epoch current-i-1. +func (f *FileSink) sealedEpochs() ([]sealedEpoch, error) { + cur, err := f.CurrentEpoch() + if err != nil { + return nil, err + } + checks, err := f.VerifyBreaks() + if err != nil { + return nil, err + } + var out []sealedEpoch + for k := cur - 1; k >= 1; k-- { + i := cur - 1 - k + se := sealedEpoch{epoch: k} + switch { + case i >= len(checks): + se.problem = fmt.Sprintf("the archive of epoch %d cannot be reached because a later archive is missing or unverified", k) + case checks[i].Problem != "": + se.problem = fmt.Sprintf("the archive of epoch %d is not verified: %s", k, checks[i].Problem) + default: + se.roots = map[int64][]string{} + for _, a := range checks[i].Anchors { + se.roots[a.Checkpoint] = append(se.roots[a.Checkpoint], a.Root) + } + } + out = append(out, se) + } + return out, nil +} + +func holds(roots []string, root string) bool { + for _, r := range roots { + if r == root { + return true + } + } + return false +} + +// VerifySealedEpochsAgainstBucket checks, for each earlier epoch, that the +// bucket prefix of that epoch holds only anchors the verified archive holds. +// An archive anchor missing from the bucket is a warning: the upload may never +// have happened. bucketAt returns the bucket view of one epoch. +func VerifySealedEpochsAgainstBucket(ctx context.Context, local *FileSink, bucketAt func(epoch int) AnchorBucket) (SealedEpochReport, error) { + var r SealedEpochReport + eps, err := local.sealedEpochs() + if err != nil { + return r, err + } + for _, se := range eps { + r.Epochs++ + if se.problem != "" { + r.Failures = append(r.Failures, SealedEpochFinding{Epoch: se.epoch, Detail: se.problem}) + continue + } + cps, _, err := bucketAt(se.epoch).ListCheckpoints(ctx) + if err != nil { + return r, err + } + inBucket := map[int64]bool{} + for _, b := range cps { + inBucket[b.Checkpoint] = true + switch { + case b.Problem != "": + r.Failures = append(r.Failures, SealedEpochFinding{Epoch: se.epoch, Checkpoint: b.Checkpoint, Detail: b.Problem}) + case len(se.roots[b.Checkpoint]) == 0: + r.Failures = append(r.Failures, SealedEpochFinding{Epoch: se.epoch, Checkpoint: b.Checkpoint, + Detail: "the bucket holds this checkpoint but the epoch's archive does not hold it"}) + case !holds(se.roots[b.Checkpoint], b.Root): + r.Failures = append(r.Failures, SealedEpochFinding{Epoch: se.epoch, Checkpoint: b.Checkpoint, + Detail: "the bucket records a different root than the epoch's archive"}) + } + } + if n := missingFrom(se.roots, inBucket); n > 0 { + r.Warnings = append(r.Warnings, SealedEpochFinding{Epoch: se.epoch, + Detail: fmt.Sprintf("%d checkpoint(s) of this epoch are in the archive but not in the bucket (an upload that never succeeded, or a different bucket prefix)", n)}) + } + } + return r, nil +} + +func missingFrom(roots map[int64][]string, have map[int64]bool) int { + n := 0 + for cp := range roots { + if !have[cp] { + n++ + } + } + return n +} + +// VerifySealedEpochsAgainstTSA checks, for each earlier epoch, that every +// timestamp token in its directory is signed by a trusted TSA over a record the +// verified archive holds. Archive anchors with no token are not reported: a +// token is optional per checkpoint. +func VerifySealedEpochsAgainstTSA(ctx context.Context, local *FileSink, trust *x509.CertPool) (SealedEpochReport, error) { + var r SealedEpochReport + eps, err := local.sealedEpochs() + if err != nil { + return r, err + } + for _, se := range eps { + r.Epochs++ + if se.problem != "" { + r.Failures = append(r.Failures, SealedEpochFinding{Epoch: se.epoch, Detail: se.problem}) + continue + } + dir := TSATokenDirForEpoch(local.path, se.epoch) + cps, _, err := listTSATokens(dir) + if err != nil { + return r, err + } + for _, cp := range cps { + roots := se.roots[cp] + if len(roots) == 0 { + r.Failures = append(r.Failures, SealedEpochFinding{Epoch: se.epoch, Checkpoint: cp, + Detail: "a timestamp token exists for this checkpoint but the epoch's archive does not hold it"}) + continue + } + token, err := readTokenFile(filepath.Join(dir, tsaTokenName(cp))) + if errors.Is(err, ErrTSATokenInvalid) { + r.Failures = append(r.Failures, SealedEpochFinding{Epoch: se.epoch, Checkpoint: cp, Detail: err.Error()}) + continue + } + if err != nil { + return r, fmt.Errorf("audit: read timestamp token for checkpoint %d of epoch %d: %w", cp, se.epoch, err) + } + info, err := verifyTSATokenSignature(token, trust) + if err != nil { + r.Failures = append(r.Failures, SealedEpochFinding{Epoch: se.epoch, Checkpoint: cp, Detail: err.Error()}) + continue + } + for _, root := range roots { + if string(AnchorRecordDigest(cp, root)) != string(info.Imprint) { + r.Failures = append(r.Failures, SealedEpochFinding{Epoch: se.epoch, Checkpoint: cp, + Detail: "the archived record differs from the one the TSA stamped: the line was edited after anchoring"}) + break + } + } + } + } + return r, nil +} diff --git a/internal/audit/anchor_epoch_seal_test.go b/internal/audit/anchor_epoch_seal_test.go new file mode 100644 index 000000000..68892130c --- /dev/null +++ b/internal/audit/anchor_epoch_seal_test.go @@ -0,0 +1,200 @@ +package audit + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// bucketAtEpoch is how the verifier reaches an earlier epoch's prefix. +func bucketAtEpoch(b *GCSAnchorSink) func(int) AnchorBucket { + return func(e int) AnchorBucket { return b.AtEpoch(e) } +} + +// An anchored epoch 1 (10, 20), then a break and one anchor in epoch 2. +func sealedFixture(t *testing.T) (*fakeGcloud, *FileSink, *GCSAnchorSink, EpochBreak) { + t.Helper() + ctx := context.Background() + g := newFakeGcloud() + file := tempSink(t) + tee, bucket := epochBucketSetup(t, g, file) + for _, cp := range []int64{10, 20} { + if err := tee.PublishRoot(ctx, cp, "old-"+itoa(cp)); err != nil { + t.Fatal(err) + } + } + b, err := file.NewEpoch(epochOpts()) + if err != nil { + t.Fatal(err) + } + if err := tee.PublishRoot(ctx, 3, "new-3"); err != nil { + t.Fatal(err) + } + return g, file, bucket, b +} + +const epoch1Prefix = "gs://example-bucket/audit-anchors/" + +func hasDetail(fs []SealedEpochFinding, sub string) bool { + for _, f := range fs { + if strings.Contains(f.Detail, sub) { + return true + } + } + return false +} + +// #3772 3b: an earlier epoch is sealed history. The bucket's copy of it must be +// what the verified archive holds; the database, which was reset, is not asked. +func TestSealedBucket_MatchingHistoryIsClean(t *testing.T) { + _, file, bucket, _ := sealedFixture(t) + r, err := VerifySealedEpochsAgainstBucket(context.Background(), file, bucketAtEpoch(bucket)) + if err != nil || len(r.Failures) != 0 || len(r.Warnings) != 0 || r.Epochs != 1 { + t.Fatalf("report %+v, err %v; want one clean sealed epoch", r, err) + } +} + +func TestSealedBucket_NoBreakIsNothingToCheck(t *testing.T) { + file := tempSink(t) + r, err := VerifySealedEpochsAgainstBucket(context.Background(), file, func(int) AnchorBucket { t.Fatal("no bucket read expected"); return nil }) + if err != nil || r.Epochs != 0 || len(r.Failures) != 0 { + t.Fatalf("report %+v, err %v", r, err) + } +} + +// A checkpoint in epoch 1's bucket that the archive does not hold is the +// unexplained kind: planted, or an anchor the archive lost. +func TestSealedBucket_AnObjectTheArchiveLacksFails(t *testing.T) { + g, file, bucket, _ := sealedFixture(t) + g.objects[epoch1Prefix+"00000000000000000999.json"] = []byte(`{"checkpoint":999,"root":"planted"}` + "\n") + r, err := VerifySealedEpochsAgainstBucket(context.Background(), file, bucketAtEpoch(bucket)) + if err != nil || !hasDetail(r.Failures, "archive does not hold") { + t.Fatalf("report %+v, err %v; want a failure naming the planted checkpoint", r, err) + } +} + +func TestSealedBucket_ADifferentRootFails(t *testing.T) { + g, file, bucket, _ := sealedFixture(t) + g.objects[epoch1Prefix+"00000000000000000020.json"] = []byte(`{"checkpoint":20,"root":"rewritten"}` + "\n") + r, _ := VerifySealedEpochsAgainstBucket(context.Background(), file, bucketAtEpoch(bucket)) + if !hasDetail(r.Failures, "different root") { + t.Fatalf("report %+v; want a different-root failure", r) + } +} + +func TestSealedBucket_AnArchiveAnchorMissingFromTheBucketIsOnlyAWarning(t *testing.T) { + g, file, bucket, _ := sealedFixture(t) + delete(g.objects, epoch1Prefix+"00000000000000000010.json") + r, _ := VerifySealedEpochsAgainstBucket(context.Background(), file, bucketAtEpoch(bucket)) + if len(r.Failures) != 0 || !hasDetail(r.Warnings, "not in the bucket") { + t.Fatalf("report %+v; want a warning only", r) + } +} + +// If the archive no longer matches its sha256 nothing it says can be trusted, +// so the epoch fails instead of being compared with it. +func TestSealedBucket_AnUnverifiedArchiveFails(t *testing.T) { + g, file, bucket, b := sealedFixture(t) + // An empty epoch 1 in the bucket: only the archive guard can fail it. + delete(g.objects, epoch1Prefix+"00000000000000000010.json") + delete(g.objects, epoch1Prefix+"00000000000000000020.json") + if err := os.Remove(b.ArchivedTo); err != nil { + t.Fatal(err) + } + r, _ := VerifySealedEpochsAgainstBucket(context.Background(), file, bucketAtEpoch(bucket)) + if !hasDetail(r.Failures, "not verified") { + t.Fatalf("report %+v; want a failure about the archive", r) + } +} + +func TestSealedBucket_FollowsEveryEarlierEpoch(t *testing.T) { + ctx := context.Background() + g, file, bucket, _ := sealedFixture(t) + tee, _ := epochBucketSetup(t, g, file) // a second view on the same file and fake bucket + later := epochOpts() + later.Now = func() time.Time { return epochTestNow.Add(time.Hour) } + if _, err := file.NewEpoch(later); err != nil { + t.Fatal(err) + } + if err := tee.PublishRoot(ctx, 1, "newer-1"); err != nil { + t.Fatal(err) + } + r, err := VerifySealedEpochsAgainstBucket(ctx, file, bucketAtEpoch(bucket)) + if err != nil || r.Epochs != 2 || len(r.Failures) != 0 { + t.Fatalf("report %+v, err %v; want 2 clean sealed epochs", r, err) + } + g.objects[epoch1Prefix+"epoch-2/00000000000000000777.json"] = []byte(`{"checkpoint":777,"root":"planted"}` + "\n") + r, _ = VerifySealedEpochsAgainstBucket(ctx, file, bucketAtEpoch(bucket)) + if len(r.Failures) != 1 || r.Failures[0].Epoch != 2 { + t.Fatalf("report %+v; want one failure in epoch 2", r) + } +} + +func sealedTSAFixture(t *testing.T) (*FileSink, *TSAAnchorSink, *testTSA) { + t.Helper() + a := newValidTestTSA(t, "a") + file, sink, _ := newTSAFixture(t, a, a) + tee := NewTeeSink(file, sink) + for _, cp := range []int64{10, 20} { + if err := tee.PublishRoot(context.Background(), cp, "old-"+itoa(cp)); err != nil { + t.Fatal(err) + } + } + if _, err := file.NewEpoch(epochOpts()); err != nil { + t.Fatal(err) + } + if err := tee.PublishRoot(context.Background(), 3, "new-3"); err != nil { + t.Fatal(err) + } + return file, sink, a +} + +func TestSealedTSA_MatchingHistoryIsClean(t *testing.T) { + file, _, a := sealedTSAFixture(t) + r, err := VerifySealedEpochsAgainstTSA(context.Background(), file, a.pool()) + if err != nil || len(r.Failures) != 0 || r.Epochs != 1 { + t.Fatalf("report %+v, err %v; want one clean sealed epoch", r, err) + } +} + +func TestSealedTSA_ATokenForARecordTheArchiveLacksFails(t *testing.T) { + file, sink, a := sealedTSAFixture(t) + dir := TSATokenDirForEpoch(file.path, 1) + tok := a.token(t, AnchorRecordDigest(30, "x"), time.Now()) + if err := writeTokenOnce(dir, filepath.Join(dir, tsaTokenName(30)), tok); err != nil { + t.Fatal(err) + } + _ = sink + r, err := VerifySealedEpochsAgainstTSA(context.Background(), file, a.pool()) + if err != nil || !hasDetail(r.Failures, "archive does not hold") { + t.Fatalf("report %+v, err %v", r, err) + } +} + +func TestSealedTSA_ATokenForAnotherRecordFails(t *testing.T) { + file, _, a := sealedTSAFixture(t) + dir := TSATokenDirForEpoch(file.path, 1) + p := filepath.Join(dir, tsaTokenName(10)) + if err := os.Remove(p); err != nil { + t.Fatal(err) + } + if err := writeTokenOnce(dir, p, a.token(t, AnchorRecordDigest(10, "other"), time.Now())); err != nil { + t.Fatal(err) + } + r, _ := VerifySealedEpochsAgainstTSA(context.Background(), file, a.pool()) + if !hasDetail(r.Failures, "differs") { + t.Fatalf("report %+v; want an imprint-mismatch failure", r) + } +} + +func TestSealedTSA_AnUntrustedSignerFails(t *testing.T) { + file, _, _ := sealedTSAFixture(t) + other := newValidTestTSA(t, "other") + r, _ := VerifySealedEpochsAgainstTSA(context.Background(), file, other.pool()) + if len(r.Failures) == 0 { + t.Fatalf("report %+v; want failures for tokens signed by a TSA outside the trust bundle", r) + } +} diff --git a/internal/audit/anchor_gcs.go b/internal/audit/anchor_gcs.go index 4910efc34..f6c25c2f5 100644 --- a/internal/audit/anchor_gcs.go +++ b/internal/audit/anchor_gcs.go @@ -50,6 +50,47 @@ type GCSAnchorSink struct { bucket string // bucket name, without gs:// prefix string // "gs:////", always ending in "/" run gcloudRunFunc + + // The objects of epoch n>1 live under epoch-/ (#3772); epoch 1 + // keeps the original names. epochs, when set, is the anchor file whose + // current epoch the sink follows (the daemon's, so a break made while it + // runs moves publishing at once); otherwise epoch is fixed, 0 meaning 1. + epochs *FileSink + epoch int +} + +// followEpochsOf makes the sink publish to the epoch the anchor file is in. +func (g *GCSAnchorSink) followEpochsOf(f *FileSink) { g.epochs = f } + +// FollowEpochsOf is followEpochsOf for the verify-anchor command, which builds +// its own sink: the live checks then read the current epoch's prefix. +func (g *GCSAnchorSink) FollowEpochsOf(f *FileSink) { g.epochs = f } + +// AtEpoch is a copy of the sink fixed on one epoch, for reading a sealed one. +func (g *GCSAnchorSink) AtEpoch(epoch int) *GCSAnchorSink { + c := *g + c.epochs, c.epoch = nil, epoch + return &c +} + +// livePrefix is the prefix of the epoch the sink is in now. A failure to read +// the anchor file falls back to epoch 1; the local file is written first, so +// that failure stops the publish before it gets here. +func (g *GCSAnchorSink) livePrefix() string { + epoch := g.epoch + if g.epochs != nil { + if e, err := g.epochs.CurrentEpoch(); err == nil { + epoch = e + } + } + return g.prefixOfEpoch(epoch) +} + +func (g *GCSAnchorSink) prefixOfEpoch(epoch int) string { + if epoch <= 1 { + return g.prefix + } + return g.prefix + epochDirName(epoch) + "/" } // NewGCSAnchorSink builds a sink for uri ("gs://" or @@ -112,12 +153,16 @@ func newGCSAnchorSink(uri string, run gcloudRunFunc) (*GCSAnchorSink, error) { } // URI is the sink's location, for log lines. -func (g *GCSAnchorSink) URI() string { return g.prefix } +func (g *GCSAnchorSink) URI() string { return g.livePrefix() } // objectURI zero-pads the checkpoint (int64 fits in 19 digits) so object // names sort in checkpoint order. func (g *GCSAnchorSink) objectURI(checkpoint int64) string { - return fmt.Sprintf("%s%020d.json", g.prefix, checkpoint) + return objectURIAt(g.livePrefix(), checkpoint) +} + +func objectURIAt(prefix string, checkpoint int64) string { + return fmt.Sprintf("%s%020d.json", prefix, checkpoint) } func (g *GCSAnchorSink) PublishRoot(ctx context.Context, checkpoint int64, root string) error { @@ -150,17 +195,18 @@ func (g *GCSAnchorSink) PublishRoot(ctx context.Context, checkpoint int64, root // An empty prefix is ok=false; any other gcloud failure is an error, never // "never anchored". func (g *GCSAnchorSink) LastPublished(ctx context.Context) (int64, string, bool, error) { - out, err := g.run(ctx, nil, "storage", "ls", g.prefix) + prefix := g.livePrefix() + out, err := g.run(ctx, nil, "storage", "ls", prefix) if err != nil { if isGcloudNoMatch(err) { return 0, "", false, nil } - return 0, "", false, fmt.Errorf("audit: list anchors under %s: %w", g.prefix, err) + return 0, "", false, fmt.Errorf("audit: list anchors under %s: %w", prefix, err) } var best int64 = -1 for _, line := range strings.Split(out, "\n") { line = strings.TrimSpace(line) - if !strings.HasPrefix(line, g.prefix) { + if !directChild(line, prefix) { continue } name, ok := strings.CutSuffix(path.Base(line), ".json") @@ -176,13 +222,19 @@ func (g *GCSAnchorSink) LastPublished(ctx context.Context) (int64, string, bool, if best < 0 { return 0, "", false, nil } - rec, err := g.readRecord(ctx, g.objectURI(best)) + rec, err := g.readRecord(ctx, objectURIAt(prefix, best)) if err != nil { return 0, "", false, err } return rec.Checkpoint, rec.Root, true, nil } +// directChild reports whether an `ls` line is an object directly under prefix, +// not one in a sub-prefix such as a later epoch's. +func directChild(line, prefix string) bool { + return strings.HasPrefix(line, prefix) && !strings.Contains(strings.TrimPrefix(line, prefix), "/") +} + func (g *GCSAnchorSink) readRecord(ctx context.Context, uri string) (anchorRecord, error) { rec, problem, err := g.fetchRecord(ctx, uri) if err != nil { @@ -314,6 +366,7 @@ func AnchorSinkFor(file *FileSink, bucketURI string, newBucket func(string) (*GC if err != nil { return file, nil, err } + bucket.followEpochsOf(file) return NewTeeSink(file, bucket), bucket, nil } diff --git a/internal/audit/anchor_tsa.go b/internal/audit/anchor_tsa.go index 6c919b12a..2e82d122d 100644 --- a/internal/audit/anchor_tsa.go +++ b/internal/audit/anchor_tsa.go @@ -163,6 +163,16 @@ func AnchorRecordDigest(checkpoint int64, root string) []byte { // TSATokenDir is where the tokens for the anchor file at anchorPath live. func TSATokenDir(anchorPath string) string { return anchorPath + ".tsa" } +// TSATokenDirForEpoch is where the tokens of one epoch live (#3772): epoch 1 +// keeps TSATokenDir, a later one has its own sub-directory, because tokens are +// named by checkpoint alone and a new epoch restarts at low checkpoints. +func TSATokenDirForEpoch(anchorPath string, epoch int) string { + if epoch <= 1 { + return TSATokenDir(anchorPath) + } + return filepath.Join(TSATokenDir(anchorPath), epochDirName(epoch)) +} + func tsaTokenName(checkpoint int64) string { return fmt.Sprintf("%020d.tsr", checkpoint) } // TSATokenInfo is what a verified token says. @@ -424,15 +434,27 @@ func newTSAAnchorSink(local *FileSink, tsaURL string, trust *x509.CertPool, post func (s *TSAAnchorSink) URI() string { return s.url } // TokenDir is where tokens are stored. -func (s *TSAAnchorSink) TokenDir() string { return s.dir } +func (s *TSAAnchorSink) TokenDir() string { return s.liveDir() } + +// liveDir is the token directory of the epoch the local file is in now. If the +// file cannot be read the sink keeps to epoch 1's directory; the local file is +// written first, so that failure stops the publish before it gets here. +func (s *TSAAnchorSink) liveDir() string { + e, err := s.local.CurrentEpoch() + if err != nil { + return s.dir + } + return TSATokenDirForEpoch(s.local.path, e) +} -func (s *TSAAnchorSink) tokenPath(checkpoint int64) string { - return filepath.Join(s.dir, tsaTokenName(checkpoint)) +func tokenPathIn(dir string, checkpoint int64) string { + return filepath.Join(dir, tsaTokenName(checkpoint)) } func (s *TSAAnchorSink) PublishRoot(ctx context.Context, checkpoint int64, root string) error { digest := AnchorRecordDigest(checkpoint, root) - path := s.tokenPath(checkpoint) + dir := s.liveDir() + path := tokenPathIn(dir, checkpoint) existing, err := readTokenFile(path) switch { case err == nil: @@ -445,7 +467,7 @@ func (s *TSAAnchorSink) PublishRoot(ctx context.Context, checkpoint int64, root if err != nil { return err } - if err := writeTokenOnce(s.dir, path, token); err != nil { + if err := writeTokenOnce(dir, path, token); err != nil { if errors.Is(err, os.ErrExist) { if existing, rerr := readTokenFile(path); rerr == nil { return s.checkExisting(existing, digest, checkpoint, path) @@ -560,7 +582,8 @@ func writeTokenOnce(dir, path string, token []byte) error { // local file's root for it. The token must verify against that root: a token // the local record does not match is an error, never "not anchored". func (s *TSAAnchorSink) LastPublished(ctx context.Context) (int64, string, bool, error) { - cps, _, err := listTSATokens(s.dir) + dir := s.liveDir() + cps, _, err := listTSATokens(dir) if err != nil { return 0, "", false, err } @@ -581,7 +604,7 @@ func (s *TSAAnchorSink) LastPublished(ctx context.Context) (int64, string, bool, if !found { return 0, "", false, fmt.Errorf("audit: timestamp token for checkpoint %d has no record in the local anchor file", cp) } - token, err := readTokenFile(s.tokenPath(cp)) + token, err := readTokenFile(tokenPathIn(dir, cp)) if err != nil { return 0, "", false, fmt.Errorf("audit: read timestamp token: %w", err) } @@ -591,6 +614,15 @@ func (s *TSAAnchorSink) LastPublished(ctx context.Context) (int64, string, bool, return cp, root, true, nil } +func isEpochDirName(name string) bool { + rest, ok := strings.CutPrefix(name, "epoch-") + if !ok { + return false + } + n, err := strconv.Atoi(rest) + return err == nil && n > 1 && epochDirName(n) == name +} + // listTSATokens returns the checkpoints with a token file in dir, ascending, // and the names of other entries. A missing directory is no tokens. func listTSATokens(dir string) (cps []int64, unrecognised []string, err error) { @@ -606,6 +638,9 @@ func listTSATokens(dir string) (cps []int64, unrecognised []string, err error) { if strings.HasPrefix(name, ".tmp-") { continue // a write interrupted before the link } + if e.IsDir() && isEpochDirName(name) { + continue // a later epoch's tokens (#3772), listed from its own directory + } base, ok := strings.CutSuffix(name, ".tsr") cp, perr := strconv.ParseInt(base, 10, 64) if !ok || !e.Type().IsRegular() || perr != nil || cp < 0 || tsaTokenName(cp) != name { diff --git a/internal/audit/anchor_tsa_verify.go b/internal/audit/anchor_tsa_verify.go index 3d0e93e32..c58866e59 100644 --- a/internal/audit/anchor_tsa_verify.go +++ b/internal/audit/anchor_tsa_verify.go @@ -117,7 +117,11 @@ func (r TSAAnchorReport) OK() bool { return len(r.Failures) == 0 } // means neither the file nor the token directory holds anything. func VerifyAnchorsAgainstTSA(ctx context.Context, chain ChainStore, local *FileSink, trust *x509.CertPool) (TSAAnchorReport, error) { var r TSAAnchorReport - dir := TSATokenDir(local.path) + epoch, err := local.CurrentEpoch() + if err != nil { + return r, err + } + dir := TSATokenDirForEpoch(local.path, epoch) tokenCPs, unrecognised, err := listTSATokens(dir) if err != nil { return r, err diff --git a/internal/audit/anchor_verify.go b/internal/audit/anchor_verify.go index 253d3bd7e..9eca0414b 100644 --- a/internal/audit/anchor_verify.go +++ b/internal/audit/anchor_verify.go @@ -73,18 +73,22 @@ type BucketCheckpoint struct { // unrecognised. Any gcloud failure, a 403 on the listing included, is an // error: only gcloud's "matched no objects" means an empty bucket. func (g *GCSAnchorSink) ListCheckpoints(ctx context.Context) (cps []BucketCheckpoint, unrecognised []string, err error) { - out, err := g.run(ctx, nil, "storage", "ls", g.prefix) + prefix := g.livePrefix() + out, err := g.run(ctx, nil, "storage", "ls", prefix) if err != nil { if isGcloudNoMatch(err) { return nil, nil, nil } - return nil, nil, fmt.Errorf("audit: list anchors under %s: %w", g.prefix, err) + return nil, nil, fmt.Errorf("audit: list anchors under %s: %w", prefix, err) } for _, line := range strings.Split(out, "\n") { line = strings.TrimSpace(line) - if !strings.HasPrefix(line, g.prefix) { + if !strings.HasPrefix(line, prefix) { continue } + if !directChild(line, prefix) { + continue // a later epoch's prefix (#3772), not an object of this one + } name, ok := strings.CutSuffix(path.Base(line), ".json") if !ok || len(name) != 20 { unrecognised = append(unrecognised, line) @@ -97,7 +101,7 @@ func (g *GCSAnchorSink) ListCheckpoints(ctx context.Context) (cps []BucketCheckp unrecognised = append(unrecognised, line) continue } - rec, problem, err := g.fetchRecord(ctx, g.objectURI(cp)) + rec, problem, err := g.fetchRecord(ctx, objectURIAt(prefix, cp)) if err != nil { return nil, nil, err } diff --git a/internal/cmd/audit.go b/internal/cmd/audit.go index 0569661a4..9e353f959 100644 --- a/internal/cmd/audit.go +++ b/internal/cmd/audit.go @@ -528,7 +528,15 @@ func runAuditVerifyAnchorBucket(ctx context.Context, chain anchorChain, local *a if err != nil { return fmt.Errorf("open anchor bucket %q: %w", uri, err) } - return verifyAnchorBucket(ctx, chain, local, localPath, bucket, os.Stdout, os.Stderr) + // The live check reads the bucket prefix of the epoch the anchor file is + // in (#3772); the epochs before it are checked against their archives. + bucket.FollowEpochsOf(local) + live := verifyAnchorBucket(ctx, chain, local, localPath, bucket, os.Stdout, os.Stderr) + sealed, err := audit.VerifySealedEpochsAgainstBucket(ctx, local, func(e int) audit.AnchorBucket { return bucket.AtEpoch(e) }) + if err != nil { + return errors.Join(live, fmt.Errorf("verify earlier epochs against the anchor bucket: %w", err)) + } + return errors.Join(live, printSealedEpochReport(os.Stdout, os.Stderr, "bucket", sealed)) } func verifyAnchorBucket(ctx context.Context, chain anchorChain, local *audit.FileSink, localPath string, bucket audit.AnchorBucket, out, errOut io.Writer) error { @@ -559,11 +567,17 @@ func runAuditVerifyAnchorTSA(ctx context.Context, chain anchorChain, local *audi if err != nil { return err } - return verifyAnchorTSA(ctx, chain, local, localPath, trust, os.Stdout, os.Stderr) + live := verifyAnchorTSA(ctx, chain, local, localPath, trust, os.Stdout, os.Stderr) + sealed, err := audit.VerifySealedEpochsAgainstTSA(ctx, local, trust) + if err != nil { + return errors.Join(live, fmt.Errorf("verify earlier epochs against timestamp tokens: %w", err)) + } + return errors.Join(live, printSealedEpochReport(os.Stdout, os.Stderr, "timestamp token", sealed)) } func verifyAnchorTSA(ctx context.Context, chain anchorChain, local *audit.FileSink, localPath string, trust *x509.CertPool, out, errOut io.Writer) error { - dir := audit.TSATokenDir(localPath) + epoch, _ := local.CurrentEpoch() + dir := audit.TSATokenDirForEpoch(localPath, epoch) report, err := audit.VerifyAnchorsAgainstTSA(ctx, chain, local, trust) if err != nil { if errors.Is(err, audit.ErrNoAnchor) { diff --git a/internal/cmd/audit_anchor.go b/internal/cmd/audit_anchor.go index 424d28e04..fe5b43e1f 100644 --- a/internal/cmd/audit_anchor.go +++ b/internal/cmd/audit_anchor.go @@ -208,3 +208,27 @@ func reportAnchorBreaks(sink *audit.FileSink, out, errOut io.Writer) error { } return nil } + +// printSealedEpochReport prints the check of the epochs before the current one +// against one external copy (kind is "bucket" or "timestamp token"). Failures +// fail the run; warnings do not. +func printSealedEpochReport(out, errOut io.Writer, kind string, r audit.SealedEpochReport) error { + if r.Epochs == 0 { + return nil + } + for _, w := range r.Warnings { + fmt.Fprintf(out, " ⚠ %s copy, epoch %d: %s\n", kind, w.Epoch, w.Detail) + } + if r.OK() { + fmt.Fprintf(out, " ✓ %d earlier epoch(s) match their archives in the %s copy (not compared with the database, which was reset)\n\n", r.Epochs, kind) + return nil + } + for _, f := range r.Failures { + if f.Checkpoint != 0 { + fmt.Fprintf(errOut, " ✗ %s copy, epoch %d, checkpoint %d: %s\n", kind, f.Epoch, f.Checkpoint, f.Detail) + } else { + fmt.Fprintf(errOut, " ✗ %s copy, epoch %d: %s\n", kind, f.Epoch, f.Detail) + } + } + return fmt.Errorf("%d earlier-epoch finding(s) in the %s copy", len(r.Failures), kind) +} diff --git a/internal/cmd/audit_anchor_breaks_test.go b/internal/cmd/audit_anchor_breaks_test.go index c8ec2c633..012fd38d7 100644 --- a/internal/cmd/audit_anchor_breaks_test.go +++ b/internal/cmd/audit_anchor_breaks_test.go @@ -67,3 +67,34 @@ func TestReportAnchorBreaks_MissingArchiveFails(t *testing.T) { t.Fatalf("err = %v, stderr %q; want a failure naming the missing archive", err, errOut.String()) } } + +func TestPrintSealedEpochReport(t *testing.T) { + t.Run("nothing sealed prints nothing", func(t *testing.T) { + var out, errOut bytes.Buffer + if err := printSealedEpochReport(&out, &errOut, "bucket", audit.SealedEpochReport{}); err != nil || out.Len()+errOut.Len() != 0 { + t.Fatalf("err %v, out %q %q", err, out.String(), errOut.String()) + } + }) + t.Run("clean", func(t *testing.T) { + var out, errOut bytes.Buffer + err := printSealedEpochReport(&out, &errOut, "bucket", audit.SealedEpochReport{Epochs: 2}) + if err != nil || !strings.Contains(out.String(), "2 earlier epoch") || errOut.Len() != 0 { + t.Fatalf("err %v, out %q, err out %q", err, out.String(), errOut.String()) + } + }) + t.Run("failure fails the run and names the epoch and checkpoint", func(t *testing.T) { + var out, errOut bytes.Buffer + r := audit.SealedEpochReport{Epochs: 1, Failures: []audit.SealedEpochFinding{{Epoch: 1, Checkpoint: 999, Detail: "planted"}}} + err := printSealedEpochReport(&out, &errOut, "bucket", r) + if err == nil || !strings.Contains(errOut.String(), "epoch 1") || !strings.Contains(errOut.String(), "999") || !strings.Contains(errOut.String(), "planted") { + t.Fatalf("err %v, stderr %q", err, errOut.String()) + } + }) + t.Run("a warning does not fail", func(t *testing.T) { + var out, errOut bytes.Buffer + r := audit.SealedEpochReport{Epochs: 1, Warnings: []audit.SealedEpochFinding{{Epoch: 1, Detail: "1 checkpoint(s) not in the bucket"}}} + if err := printSealedEpochReport(&out, &errOut, "bucket", r); err != nil || !strings.Contains(out.String(), "not in the bucket") { + t.Fatalf("err %v, out %q", err, out.String()) + } + }) +} From 9f3930a618f1886ec289f7a6678701963b0ba326 Mon Sep 17 00:00:00 2001 From: hsinatfootprintai <149764663+hsinatfootprintai@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:50:56 +0800 Subject: [PATCH 5/7] docs(changelog): fragment for epoch numbering (#3772) Part of #3772 Co-Authored-By: Claude Sonnet 5.5 --- changelog.d/3893.changed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/3893.changed.md diff --git a/changelog.d/3893.changed.md b/changelog.d/3893.changed.md new file mode 100644 index 000000000..e1a406aba --- /dev/null +++ b/changelog.d/3893.changed.md @@ -0,0 +1 @@ +- **Anchor epochs are numbered, and the bucket and timestamp-token copies follow them** (#3772). After `audit anchor new-epoch`, an external copy used to refuse or collide because objects are keyed by checkpoint alone. Epoch 2 and later now publish under `epoch-/` in the bucket and `.tsa/epoch-/` for tokens (epoch 1 keeps its names, so nothing existing moves), and `audit verify-anchor` checks each earlier epoch against its verified archive: a bucket object or token the archive does not hold fails. From 609b222f417542fded6bb25cac37406d5ac8564a Mon Sep 17 00:00:00 2001 From: hsinatfootprintai <149764663+hsinatfootprintai@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:51:34 +0800 Subject: [PATCH 6/7] docs(runbook): the audit database was recreated or restored (#3772 slice 5) Part of #3772 Co-Authored-By: Claude Sonnet 5.5 --- docs/security/OPERATOR-SECURITY-RUNBOOK.md | 114 +++++++++++++++++++-- 1 file changed, 103 insertions(+), 11 deletions(-) diff --git a/docs/security/OPERATOR-SECURITY-RUNBOOK.md b/docs/security/OPERATOR-SECURITY-RUNBOOK.md index 416353647..3cb0ad116 100644 --- a/docs/security/OPERATOR-SECURITY-RUNBOOK.md +++ b/docs/security/OPERATOR-SECURITY-RUNBOOK.md @@ -1525,17 +1525,109 @@ acting on it: history, and editing it is exactly what the refusal guards against. Anchoring resumes on its own once the chain passes the last anchored -checkpoint. A recorded recovery that starts a new anchor epoch, so that -`verify-anchor` treats the break as a documented break and not as -tampering, is tracked in #3549. The state is held in memory, so after a -daemon restart the signals above reappear at the first refused tick, within -one anchor interval (`CONTAINARIUM_AUDIT_ANCHOR_INTERVAL`, 15 minutes by -default), not at startup. A conflict (a checkpoint already anchored with a -different root) that persists across ticks is not the "database recreated" -case: run `containarium audit verify-anchor` and treat a mismatch as a -possible rewrite. A single conflict that clears on the next tick can happen -when a recreated chain lands exactly on the last anchored checkpoint while -it climbs past it. +checkpoint. If the database was recreated or restored on purpose, do not +wait for that: record the break with the steps in +[The audit database was recreated or restored](#the-audit-database-was-recreated-or-restored). + +A chain that is already behind the anchor when the daemon starts is +reported at startup (`DEGRADED (found at startup)` in the daemon log, and +the readiness entry goes NOT_SERVING at once), not after the first anchor +interval (`CONTAINARIUM_AUDIT_ANCHOR_INTERVAL`, 15 minutes by default). The +state is held in memory, so a restart reports it again. A conflict (a +checkpoint already anchored with a different root) that persists across +ticks is not the "database recreated" case: run +`containarium audit verify-anchor` and treat a mismatch as a possible +rewrite. A single conflict that clears on the next tick can happen when a +recreated chain lands exactly on the last anchored checkpoint while it +climbs past it. + +### The audit database was recreated or restored + +Use this when the platform Postgres was recreated, or restored from an older +copy, you have confirmed that is what happened (see the checks above), and the +daemon refuses to anchor the new chain. `new-epoch` does not reset the anchor. +It ends the old anchor history on the record and starts a new one, and +`verify-anchor` shows the break. + +1. **Stop anchoring.** Stop the daemon, or run the command while it is + refusing. A publish that lands while the command works makes it abort and + change nothing. + +2. **Start the new epoch**, as root, with a reason and the confirmation flag: + + ```bash + sudo containarium audit anchor new-epoch \ + --reason "audit database restored from the backup" \ + --confirm-new-epoch + ``` + + `--anchor-path` defaults to `CONTAINARIUM_AUDIT_ANCHOR_PATH`, then the + daemon's default. The command refuses, before it touches the file or the + database, when `--confirm-new-epoch` or `--reason` is missing or the caller + is not root. The actor is the user behind `sudo` (`$SUDO_USER`), else the + current user. + +3. **What it did.** It prints the archive path, the archive's sha256 and the + last anchor the old file held, and: + - copied the old anchor file, whole, to `.archived-` + (mode 0600, never over an existing file). The old file is archived, never + deleted: keep the archive, with the rest of your evidence, for as long as + you keep the audit log; + - replaced the anchor file, atomically, with a new one whose first line is + a break record: when, who, why, the archive and its sha256, the last + checkpoint and root, and the epoch number (the first break starts epoch + 2); + - recorded the same in the audit chain, as action + `audit_anchor_new_epoch` (`containarium audit query --action + audit_anchor_new_epoch`). If the database write fails the command says the + file was changed, names the archive and sha256, and the break record in the + file still names the actor. + +4. **Start the daemon.** The next tick publishes at the chain's current + checkpoint and anchoring resumes. Rollback protection applies again from + there. + +With `CONTAINARIUM_AUDIT_ANCHOR_BUCKET` or a timestamp authority configured, +the objects are keyed by checkpoint, and a new epoch restarts at low +checkpoints. Epoch 1 keeps its original names. Epoch *n* after it publishes +under `epoch-/` in the bucket and under +`.tsa/epoch-/` for tokens, so nothing already written moves or +is overwritten. The daemon follows the anchor file's epoch, so a break made +while it runs takes effect on the next publish. + +#### What `verify-anchor` shows afterwards + +`containarium audit verify-anchor` prints each recorded break as a break (when, +who, why, the archive and its sha256) and says the archive is present and +unchanged. This is not a failure. It checks, for every break including those +recorded inside archives: + +| Result | Meaning | Exit | +| --- | --- | --- | +| ⚠ | A recorded break. The archive is present, matches its recorded sha256 and ends at the last anchor the break records. | 0 | +| ✗ | The archive is missing, has changed, or does not end at the anchor the break records. Deleting the old history after a break does not pass as a clean break. | non-zero | +| ✗ | With `--anchor-bucket`: an earlier epoch's bucket prefix holds an object the epoch's archive does not hold, or one with a different root. | non-zero | +| ✗ | With `--anchor-tsa-trust-bundle`: an earlier epoch's token is for a record the archive does not hold, is stamped over a different record, or is not signed by a trusted TSA. | non-zero | +| ⚠ | An earlier epoch's archive holds checkpoints the bucket does not (an upload that never succeeded, or a different prefix). | 0 | +| ✗ | A drop in the anchor with **no** break record. This is the unexplained case and still fails, exactly as before. | non-zero | + +The current epoch is checked against the database as always. Earlier epochs +are not: their rows are gone with the old database, so they are compared with +their archive, and the archive with the sha256 in the break record. + +#### What this does not protect against + +- The break record is written by whoever runs the command as root. It makes + the break visible and attributable; it does not prove the reason is true. + Review `audit_anchor_new_epoch` entries, and the archive, when you audit. +- A host-root attacker can still stop the daemon, run `new-epoch`, and start a + new history. What they cannot do is make it unrecorded: the break record, + the archive with its sha256, the audit entry, and any bucket or timestamp + copy of the earlier epoch remain. Keep an off-host copy of the anchor file + and the archives; the bucket copy of the earlier epochs is what a host-root + attacker cannot edit. +- A rollback is not a recovery. If the database was *not* recreated or + restored, do not run this: verify first (`containarium audit verify-anchor`). ### Anchoring to a bucket From ab723044cb050732912d97ed4b7243cbee9b282f Mon Sep 17 00:00:00 2001 From: hsinatfootprintai <149764663+hsinatfootprintai@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:51:49 +0800 Subject: [PATCH 7/7] docs(changelog): fragment for the anchor recovery runbook (#3772) Part of #3772 Co-Authored-By: Claude Sonnet 5.5 --- changelog.d/3894.documentation.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/3894.documentation.md diff --git a/changelog.d/3894.documentation.md b/changelog.d/3894.documentation.md new file mode 100644 index 000000000..bf8f88f1f --- /dev/null +++ b/changelog.d/3894.documentation.md @@ -0,0 +1 @@ +- **Runbook: "The audit database was recreated or restored"** (#3772). Step by step recovery with `containarium audit anchor new-epoch`, what it writes, what `audit verify-anchor` shows afterwards, and what the recovery does not protect against. The "daemon refuses to anchor" section now describes startup detection.