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. 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..c473b2c63 --- /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 func() { _ = 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()) + } +}