Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/3893.changed.md
Original file line number Diff line number Diff line change
@@ -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 `<prefix>epoch-<n>/` in the bucket and `<anchor-path>.tsa/epoch-<n>/` 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.
68 changes: 68 additions & 0 deletions internal/audit/anchor_epoch.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
}
186 changes: 186 additions & 0 deletions internal/audit/anchor_epoch_publish_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading