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. 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()) + } + }) +}