claim-empty-cohort-done fix round 1: done re-lists the records around its write; the migration repairs its floor directories before the first floor read
F1 (Astra, MEDIUM): Backfill.Done listed the records once, before the reports, so a record created during report retrieval could end outside a done plan. It now lists them again immediately before the If-Match write (refusing with ErrDoneRecords, nothing written) and a third time after the readback (ErrDoneRecordsChanged, wrapping ErrDoneRecords, so claims run shows the existing records refusal). No new human-facing string. The trial closes the remaining window by stopping the dev console from 8.1b to 8.2b. F2 (Astra, MEDIUM): a floor directory an earlier attempt left 0700 was refused by guardReady's floor read before the repair in ready could run. rootMigration.run now calls a required prepareFloors hook under its lock and quiesce, before guardReady; production wires it to prepareRootFloorDirs, which repairs guard/moves and guard/seeds to 0755 only when each is a real root:root directory reached with no symlink, and refuses anything else untouched. Tests: hostops and claimactivation interleaving tests (record during report retrieval, record after the write), the floor-directory repair and refusals, the run ordering; the step 8 root-runner scaffold makes guard-arm's floor explicitly at umask 022 and four rerun witnesses (moves 0700, seeds 0700, interrupted mkdir, carlos-owned seeds) pass on the root runner. Census: overlay plan14-root-reads-claim-empty-cohort-fix1.tsv (PROPOSED) and the 9B8 re-pin of Backfill.Done.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
16 files changed,
+711
−68
docs/superpowers/notes/census-proposal-claim-step8-readiness.md+20 −0internal/claimactivation/backfill_test.go+69 −0internal/host/claimstep8_ruling6_test.go+2 −0internal/host/claimstep8_witness_rootrunner_linux_test.go+158 −3internal/host/plan14_root_migration_test.go+1 −1internal/host/rootmigration.go+8 −1internal/host/rootmigration_floordirs_linux_test.go+175 −25internal/host/rootmigration_production_linux.go+68 −9internal/host/rootmigration_reboot_root_linux_test.go+1 −1internal/hostops/backfill_done_test.go+90 −0internal/hostops/backfill_publish.go+64 −25internal/hostops/operations_test.go+12 −2internal/provision/claim_empty_cohort_fix1_census_test.go+25 −0internal/provision/plan14_root_reads_test.go+9 −0internal/provision/plan9_b8_census_test.go+1 −1internal/provision/testdata/plan14-root-reads-claim-empty-cohort-fix1.tsv+8 −0
diff --git a/docs/superpowers/notes/census-proposal-claim-step8-readiness.md b/docs/superpowers/notes/census-proposal-claim-step8-readiness.md| index 26f3dbf4e..16b958a25 100644 |
| --- a/docs/superpowers/notes/census-proposal-claim-step8-readiness.md |
| +++ b/docs/superpowers/notes/census-proposal-claim-step8-readiness.md |
| @@ -62,3 +62,23 @@ Ruling 6: the phase is reached only from `claims run` on the trusted signer. `Te |
| Envelopes re-pinned: `internal/claimactivation`, `internal/hostops`. New helpers with no read site of their own (`Runner.backfillDone`, `verifyCensusReport`) are envelope only. `internal/host` changes are tests only. |
| 9B8: `internal/hostops/backfill_publish.go` `Backfill.Done`, nonrecord (new). Its one Put is the backfill manifest rewritten as done under the collecting etag, through the runner's checkedStore; it reads records, claims, admissions and census reports and writes none of them. |
| + |
| +## Fix round 1 |
| + |
| +Status: PROPOSED. The ruling is owed. Astra's review of `claim-empty-cohort-done` blocked the merge on two findings, and platform-1e ruled the fixes. The re-pins are in a new overlay, `internal/provision/testdata/plan14-root-reads-claim-empty-cohort-fix1.tsv`, loaded last and marked `rev3=PROPOSED-claim-empty-cohort-fix1`. The 9B8 re-pin is in `internal/provision/claim_empty_cohort_fix1_census_test.go`. No accepted-legacy row is added, so the seal stands. |
| + |
| +- **F1: `Backfill.Done` could finish with a record it never listed.** Done now lists the records a second time, immediately before its If-Match write, after every report has been fetched and verified. If that listing is not `p.Hosts`, it refuses with `ErrDoneRecords` and writes nothing. After the write and the readback it lists them a third time. A change there returns `ErrDoneRecordsChanged`, which wraps `ErrDoneRecords`, so `claims run` puts the existing records refusal in front of it. No new human-facing string. All three listings use the new `doneRecords` (`Apps`, then `Records` per app, the comparison collect uses). The If-Match covers only the plan, so this narrows the window but cannot close it. The trial closes it by stopping the dev console (`console.service`, owned by platform-d8) from 8.1b to 8.2b, which stops its record writes. |
| +- **F2: the umask repair could not be reached on a rerun.** `rootMigration.run` now calls a required `prepareFloors` hook under its lock and quiesce, before `guardReady`. That is before the first floor read. Production wires the hook to `prepareRootFloorDirs`. A missing directory is made with `mkdirAllExact`. An existing `guard/moves` or `guard/seeds` is repaired to 0755 only when it is a real directory owned by root:root, reached from `/` with `O_NOFOLLOW` at every component. A symlink, a file or another owner refuses and is left as it was. `ready` still calls it before opening the floors. |
| + |
| +Ruling 6: `prepareRootFloorDirs` is still called only from `migrateRootClaimAuthority`. `TestStep8CensusChangesReachOnlyClaimMode` also pins `prepareRootFloorDirsOwned` to `prepareRootFloorDirs` and `repairRootFloorDir` to `prepareRootFloorDirsOwned`. `Backfill.Done`'s callers are unchanged. A claims-off or no-census box sees no change. |
| + |
| +| Unit | Change | Class | Executing identity | |
| +|---|---|---|---| |
| +| `internal/hostops/backfill_publish.go` `Backfill.Done` | re-pinned: the second and third record listings | authority F,G,J4 (unchanged) | `carlos system claims run backfill-done`, explicit operator CLI, uid 0 on the trusted signing host | |
| +| `internal/host/rootmigration.go` `rootMigration.run` | re-pinned: the required `prepareFloors` hook, before `guardReady` | authority G,J4 (unchanged) | `carlos system journal-migrate`, offline uid 0 | |
| +| `internal/host/rootmigration_production_linux.go` `migrateRootClaimAuthority` | re-pinned: `prepareFloors` wired to `prepareRootFloorDirs` | authority G,J4,E3 (unchanged) | offline root migration, uid 0 | |
| +| `internal/host/rootmigration_production_linux.go` `repairRootFloorDir` | new: Lstat, then an `O_NOFOLLOW` walk from `/`, Fstat, and Fchmod to 0755 only for a root:root directory | authority G,J4 | `carlos system journal-migrate`, offline uid 0 | |
| + |
| +Envelopes re-pinned: `internal/host`, `internal/hostops`. The new `doneRecords` and `prepareRootFloorDirsOwned` have no read site of their own, so they are envelope only. |
| + |
| +9B8: `internal/hostops/backfill_publish.go` `Backfill.Done`, still nonrecord (re-reviewed). The new listings only read. Its one Put, of the backfill manifest under the collecting etag, is unchanged. |
diff --git a/internal/claimactivation/backfill_test.go b/internal/claimactivation/backfill_test.go| index 3eafede34..bc17c24e4 100644 |
| --- a/internal/claimactivation/backfill_test.go |
| +++ b/internal/claimactivation/backfill_test.go |
| @@ -423,3 +423,72 @@ func TestBackfillCollectRefusesARecordThatMoved(t *testing.T) { |
| t.Fatalf("collect over a moving record = %v", err) |
| } |
| } |
| + |
| +// windowStore runs afterGet once on the first Get of getKey and afterPut |
| +// once after the first Put of putKey: a console record writer racing the |
| +// claims run's backfill-done. |
| +type windowStore struct { |
| + release.Store |
| + getKey, putKey string |
| + afterGet, afterPut func() |
| +} |
| + |
| +func (s *windowStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + b, tag, err := s.Store.Get(ctx, key) |
| + if err == nil && key == s.getKey && s.afterGet != nil { |
| + f := s.afterGet |
| + s.afterGet = nil |
| + f() |
| + } |
| + return b, tag, err |
| +} |
| + |
| +func (s *windowStore) Put(ctx context.Context, key string, b []byte, tag string) (string, error) { |
| + got, err := s.Store.Put(ctx, key, b, tag) |
| + if err == nil && key == s.putKey && s.afterPut != nil { |
| + f := s.afterPut |
| + s.afterPut = nil |
| + f() |
| + } |
| + return got, err |
| +} |
| + |
| +// A record created during the window reaches the operator as the records |
| +// refusal: while leo's report is read, done refuses before writing and the |
| +// plan stays collecting; after done's write, the refusal carries |
| +// ErrDoneRecordsChanged and the plan is done. |
| +func TestBackfillDoneRecordCreatedDuringTheWindow(t *testing.T) { |
| + for _, after := range []bool{false, true} { |
| + name := map[bool]string{false: "during report retrieval", true: "after the write"}[after] |
| + t.Run(name, func(t *testing.T) { |
| + ctx := t.Context() |
| + b := newBackfillDeployment(t, false) |
| + if _, err := b.r.Run(ctx, b.plan(t, "backfill-collect"), false); err != nil { |
| + t.Fatal(err) |
| + } |
| + b.report(t, "leo-climbing") |
| + fired := false |
| + create := func() { |
| + fired = true |
| + b.record(t, provision.Record{Schema: 1, Account: "bab", App: "late", Host: "late.example.com", Slug: "late", Channel: "edge", Acquisition: "acq-late"}) |
| + } |
| + s := &windowStore{Store: b.r.Directory.Store} |
| + if after { |
| + s.putKey, s.afterPut = hostops.BackfillKey, create |
| + } else { |
| + s.getKey, s.afterGet = "control/host-census/cohort1-20261021/leo-climbing.json", create |
| + } |
| + b.r.Directory.Store = s |
| + _, err := b.r.Run(ctx, b.plan(t, "backfill-done"), false) |
| + if !fired { |
| + t.Fatal("the window's hook never ran") |
| + } |
| + if !errors.Is(err, ErrBackfillRecords) || errors.Is(err, hostops.ErrDoneRecordsChanged) != after { |
| + t.Fatalf("done = %v", err) |
| + } |
| + if want := map[bool]string{false: "collecting", true: "done"}[after]; readPlan(t, b.r).Phase != want { |
| + t.Fatalf("plan phase = %s; want %s", readPlan(t, b.r).Phase, want) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/host/claimstep8_ruling6_test.go b/internal/host/claimstep8_ruling6_test.go| index 1669cbca9..52112f9a1 100644 |
| --- a/internal/host/claimstep8_ruling6_test.go |
| +++ b/internal/host/claimstep8_ruling6_test.go |
| @@ -68,6 +68,8 @@ func TestStep8CensusChangesReachOnlyClaimMode(t *testing.T) { |
| "verifyMigrationWindow": {"migrateRootClaimAuthority", "verifyJournalMigrateWindow"}, |
| "verifyJournalMigrateWindow": {"RunSystemJournalMigrate"}, |
| "prepareRootFloorDirs": {"migrateRootClaimAuthority"}, |
| + "prepareRootFloorDirsOwned": {"prepareRootFloorDirs"}, |
| + "repairRootFloorDir": {"prepareRootFloorDirsOwned"}, |
| "claimBoxDataCensus": {"claimDataCensus"}, |
| "claimDataCensus": {"claimGlobalSharedPaths"}, |
| "claimGlobalSharedPaths": {"OpenProductionClaimAssembly", "claimMigrationSharedPaths", "recoverRootInventoryStartup"}, |
diff --git a/internal/host/claimstep8_witness_rootrunner_linux_test.go b/internal/host/claimstep8_witness_rootrunner_linux_test.go| index 37c3c9e44..70ac5e4d2 100644 |
| --- a/internal/host/claimstep8_witness_rootrunner_linux_test.go |
| +++ b/internal/host/claimstep8_witness_rootrunner_linux_test.go |
| @@ -106,12 +106,47 @@ func TestRootStep8WindowWitnessEmptyLeoTwoHosts(t *testing.T) { |
| rootStep8Witness(t, step8Shape{empty: true, keep: []string{leoRollcheck, leoWakecheck}}) |
| } |
| +// The rerun witnesses (fix round 1, F2): the empty-leo zero-host flow, with |
| +// a public floor directory left behind by an earlier journal-migrate |
| +// attempt in the window's umask 077 shell. The rerun, also under umask |
| +// 077, repairs it under the migration's lock before the first floor read, |
| +// completes, and leaves guard/moves and guard/seeds 0755 root:root: |
| +// |
| +// - Moves0700: guard/moves (guard-arm's floor history) left 0700; |
| +// - Seeds0700: guard/seeds left 0700; |
| +// - Interrupted: guard/seeds made by mkdirAllExact's mkdir under umask |
| +// 077, its chmod never reached (0700, empty); |
| +// - Foreign: guard/seeds left 0700 but owned by the carlos user. The |
| +// migration refuses it and leaves it as it was; once it is root's again |
| +// the rerun repairs it and completes. |
| +// |
| +// The earlier attempt's leftover is the only scaffold write these add, made |
| +// after step 3's refused attempt and checked before the rerun. |
| +func TestRootStep8WindowWitnessRerunMoves0700(t *testing.T) { |
| + rootStep8Witness(t, step8Shape{empty: true, floorDirs: "moves"}) |
| +} |
| + |
| +func TestRootStep8WindowWitnessRerunSeeds0700(t *testing.T) { |
| + rootStep8Witness(t, step8Shape{empty: true, floorDirs: "seeds"}) |
| +} |
| + |
| +func TestRootStep8WindowWitnessRerunInterrupted(t *testing.T) { |
| + rootStep8Witness(t, step8Shape{empty: true, floorDirs: "interrupted"}) |
| +} |
| + |
| +func TestRootStep8WindowWitnessRerunForeign(t *testing.T) { |
| + rootStep8Witness(t, step8Shape{empty: true, floorDirs: "foreign"}) |
| +} |
| + |
| type step8Shape struct { |
| // sophieReports gives sophie a census key and a stand-in report. |
| sophieReports bool |
| // empty is Option B: B1 and B2 done, and keep the records B1 left. |
| empty bool |
| keep []string |
| + // floorDirs is the floor directory an earlier attempt left behind |
| + // ("" for none; see the rerun witnesses). |
| + floorDirs string |
| } |
| const ( |
| @@ -306,15 +341,30 @@ systemctl show "${UNITS[@]}" -p Id -p LoadState -p ActiveState |
| t.Setenv("CARLOS_HOST_CLAIM_ORIGINS", "1") |
| t.Setenv("CARLOS_POOLS", "cohort1") |
| t.Setenv("TMPDIR", scratch) |
| + // guard-arm (step 6) leaves guard/ and guard/moves 0755 root:root. Make |
| + // them so explicitly, under umask 022, rather than at whatever umask the |
| + // runner's shell has, and check it: the migration below must find either |
| + // that or the leftover a rerun shape makes after step 3, never a state |
| + // the scaffold produced by accident. |
| floorID := rootFloorIdentity{Deployment: step8Bucket, Box: actor.Box, Enrollment: actor.Enrollment} |
| + scaffoldUmask := syscall.Umask(0o022) |
| floors, err := openRootMovesFloors(opt, floorID, true) |
| if err != nil { |
| + syscall.Umask(scaffoldUmask) |
| t.Fatal(err) |
| } |
| - if err := floors.reconstruct(ctx, rootFloorReconstruction{Identity: floorID, Floor: &moves.Floor{Min: 1, MinRelease: "v2.0.0"}, Source: "enrolled root history", Digest: floorTestDigest, Authorization: floorTestAuthorization(t, floors)}); err != nil { |
| + err = floors.reconstruct(ctx, rootFloorReconstruction{Identity: floorID, Floor: &moves.Floor{Min: 1, MinRelease: "v2.0.0"}, Source: "enrolled root history", Digest: floorTestDigest, Authorization: floorTestAuthorization(t, floors)}) |
| + floors.close() |
| + syscall.Umask(scaffoldUmask) |
| + if err != nil { |
| t.Fatal(err) |
| } |
| - floors.close() |
| + for _, dir := range []string{systemGuardDir(opt), rootFloorDir(opt)} { |
| + st, err := os.Lstat(dir) |
| + if err != nil || !st.IsDir() || st.Mode().Perm() != 0o755 || st.Sys().(*syscall.Stat_t).Uid != 0 || st.Sys().(*syscall.Stat_t).Gid != 0 { |
| + t.Fatalf("scaffold: %s is not guard-arm's 0755 root:root directory: %v %v", dir, st.Mode(), err) |
| + } |
| + } |
| rootFloorRunnerBinary(t, opt, systemBinaryPath(opt), "v2.0.0", key) |
| rootFloorRunnerBinary(t, opt, filepath.Join(systemGuardDir(opt), "carlos"), "v2.0.0", key) |
| if _, err := os.Lstat(rootSeedsFloorDir(opt)); !errors.Is(err, os.ErrNotExist) { |
| @@ -353,6 +403,15 @@ systemctl show "${UNITS[@]}" -p Id -p LoadState -p ActiveState |
| t.Fatalf("journal-migrate without --window = %v, want the census to refuse a mask", err) |
| } |
| t.Logf("journal-migrate without --window refused: %v", err) |
| + // The floor directories are prepared under the migration's lock before |
| + // its first floor read, so even this refused attempt made guard/seeds, |
| + // 0755 root:root, and left guard/moves so. |
| + for _, dir := range []string{rootFloorDir(opt), rootSeedsFloorDir(opt)} { |
| + st, err := os.Lstat(dir) |
| + if err != nil || !st.IsDir() || st.Mode().Perm() != 0o755 || st.Sys().(*syscall.Stat_t).Uid != 0 || st.Sys().(*syscall.Stat_t).Gid != 0 { |
| + t.Fatalf("after the refused attempt: %s %v %v", dir, st.Mode(), err) |
| + } |
| + } |
| // 4. journal-migrate --window, as the window's root shell runs it, but |
| // under umask 077 (R3). |
| r.MigrationWindow = step8Window |
| @@ -360,9 +419,48 @@ systemctl show "${UNITS[@]}" -p Id -p LoadState -p ActiveState |
| if err != nil || len(masked) != len(claimWindowUnits) { |
| t.Fatalf("--window: %v %v", masked, err) |
| } |
| + step8EarlierAttempt(t, opt, shape.floorDirs, uid, gid) |
| + // Step 3's refused attempt got as far as the census in ready, so its |
| + // migration.json is there; a refused rerun must leave it as it is. |
| + migrationRecord := func() []byte { |
| + state, err := rootstate.Open(rootMigrationDir, false, false) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer state.Close() |
| + raw, err := state.Read("migration.json") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return raw |
| + } |
| + var before []byte |
| + if shape.floorDirs == "foreign" { |
| + before = migrationRecord() |
| + } |
| old := syscall.Umask(0o077) |
| err = migrateClaimJournalsWith(ctx, store, r, owners, true) |
| syscall.Umask(old) |
| + if shape.floorDirs == "foreign" { |
| + // Not root's: refused before any floor read, and left as it was. |
| + if !errors.Is(err, os.ErrPermission) { |
| + t.Fatalf("journal-migrate --window over a carlos-owned guard/seeds = %v, want a refusal", err) |
| + } |
| + st, serr := os.Lstat(rootSeedsFloorDir(opt)) |
| + if serr != nil || st.Mode().Perm() != 0o700 || st.Sys().(*syscall.Stat_t).Uid != uint32(uid) { |
| + t.Fatalf("the refused guard/seeds changed: %v %v", st.Mode(), serr) |
| + } |
| + if !bytes.Equal(migrationRecord(), before) { |
| + t.Fatal("the refused rerun changed migration.json") |
| + } |
| + t.Logf("journal-migrate --window refused a carlos-owned guard/seeds and left it 0700: %v", err) |
| + if err := os.Lchown(rootSeedsFloorDir(opt), 0, 0); err != nil { |
| + t.Fatal(err) |
| + } |
| + old = syscall.Umask(0o077) |
| + err = migrateClaimJournalsWith(ctx, store, r, owners, true) |
| + syscall.Umask(old) |
| + } |
| if err != nil { |
| t.Fatal("journal-migrate --window", err) |
| } |
| @@ -378,10 +476,13 @@ systemctl show "${UNITS[@]}" -p Id -p LoadState -p ActiveState |
| } |
| for path, want := range map[string]os.FileMode{"/var/lib/carlos-claims": 0o700, rootFloorDir(opt): 0o755, rootSeedsFloorDir(opt): 0o755, systemGuardDir(opt): 0o755} { |
| st, err := os.Stat(path) |
| - if err != nil || st.Mode().Perm() != want || st.Sys().(*syscall.Stat_t).Uid != 0 { |
| + if err != nil || !st.IsDir() || st.Mode().Perm() != want || st.Sys().(*syscall.Stat_t).Uid != 0 || st.Sys().(*syscall.Stat_t).Gid != 0 { |
| t.Fatalf("mode check after journal-migrate: %s %v %v", path, st.Mode(), err) |
| } |
| } |
| + if shape.floorDirs != "" { |
| + t.Logf("rerun over %s: complete; guard/moves and guard/seeds are 0755 root:root", shape.floorDirs) |
| + } |
| reportRaw, _, err := store.Get(ctx, "control/host-census/"+step8ID+"/"+step8Leo+".json") |
| if err != nil { |
| t.Fatal(err) |
| @@ -490,6 +591,60 @@ systemctl show "${UNITS[@]}" -p Id -p LoadState -p ActiveState |
| t.Logf("STOP S4: root refuses the adopted legacy host before any seed admission: %v", err) |
| } |
| +// step8EarlierAttempt leaves the public floor directory an earlier |
| +// journal-migrate attempt in the window's umask 077 shell would have, and |
| +// checks it is there: the rerun witnesses' only extra scaffold write. |
| +func step8EarlierAttempt(t *testing.T, opt, shape string, uid, gid int) { |
| + t.Helper() |
| + dir := rootSeedsFloorDir(opt) |
| + owner := uint32(0) |
| + if shape == "" { |
| + return |
| + } |
| + if shape != "moves" { |
| + // Step 3's refused attempt made guard/seeds, empty; the earlier |
| + // attempt this shape stands for left it differently. |
| + if err := os.Remove(dir); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + switch shape { |
| + case "moves": |
| + dir = rootFloorDir(opt) |
| + if err := os.Chmod(dir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "seeds": |
| + if err := os.Mkdir(dir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "interrupted": |
| + // mkdirAllExact's first half, os.MkdirAll(dir, 0755), under the |
| + // window shell's umask; the process died before its chmod. |
| + old := syscall.Umask(0o077) |
| + err := os.MkdirAll(dir, 0o755) |
| + syscall.Umask(old) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + case "foreign": |
| + if err := os.Mkdir(dir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Lchown(dir, uid, gid); err != nil { |
| + t.Fatal(err) |
| + } |
| + owner = uint32(uid) |
| + default: |
| + t.Fatalf("unknown floor-directory shape %q", shape) |
| + } |
| + st, err := os.Lstat(dir) |
| + if err != nil || !st.IsDir() || st.Mode().Perm() != 0o700 || st.Sys().(*syscall.Stat_t).Uid != owner { |
| + t.Fatalf("earlier attempt: %s is %v (%v), want 0700 owned by %d", dir, st.Mode(), err, owner) |
| + } |
| + t.Logf("earlier attempt left %s 0700 (owner %d)", dir, owner) |
| +} |
| + |
| // rootStep8Done is the empty-leo flow's step 5: backfill-done, dry run then |
| // apply, through the production runner, then the console's own readers. |
| func rootStep8Done(t *testing.T, store release.Store, directory hostactors.Directory, runner claimactivation.Runner, shape step8Shape) { |
diff --git a/internal/host/plan14_root_migration_test.go b/internal/host/plan14_root_migration_test.go| index b750524bd..def510bd8 100644 |
| --- a/internal/host/plan14_root_migration_test.go |
| +++ b/internal/host/plan14_root_migration_test.go |
| @@ -22,7 +22,7 @@ func migrationFixture(t *testing.T) (rootMigration, *rootMigrationSnapshot, *int |
| exec := &rollbackDisk{dir: t.TempDir()} |
| writes := 0 |
| snapshot := &rootMigrationSnapshot{Complete: true, DirectoryRevision: 7, Exclusion: "signed collecting reservation", Report: hostops.CensusReport{Box: "box", Enrollment: "en", BootID: "boot", Reservation: "offline", DirectoryRevision: 7, CapturedAt: time.Now(), Complete: true, Installations: []hostops.CensusInstallation{}, Seeds: &hostops.CensusSeeds{Journaled: []string{}, Gated: []string{}}}, Items: []rootMigrationItem{}} |
| - m := rootMigration{guardReady: func(context.Context) error { return nil }, state: state, execution: exec, identity: rootMigrationIdentity{Deployment: "deploy", Box: "box", Enrollment: "en", Generation: 1}, quiesce: func(context.Context) (func(), error) { return func() {}, nil }, observe: func(context.Context) (rootMigrationSnapshot, error) { return *snapshot, nil }, deny: func(context.Context, rootMigrationItem) error { writes++; return nil }, recover: func(context.Context, rootMigrationItem) error { writes++; return nil }, ready: func(context.Context, rootMigrationSnapshot) error { return nil }, publish: func(context.Context, hostops.CensusReport) error { writes++; return nil }} |
| + m := rootMigration{prepareFloors: func(context.Context) error { return nil }, guardReady: func(context.Context) error { return nil }, state: state, execution: exec, identity: rootMigrationIdentity{Deployment: "deploy", Box: "box", Enrollment: "en", Generation: 1}, quiesce: func(context.Context) (func(), error) { return func() {}, nil }, observe: func(context.Context) (rootMigrationSnapshot, error) { return *snapshot, nil }, deny: func(context.Context, rootMigrationItem) error { writes++; return nil }, recover: func(context.Context, rootMigrationItem) error { writes++; return nil }, ready: func(context.Context, rootMigrationSnapshot) error { return nil }, publish: func(context.Context, hostops.CensusReport) error { writes++; return nil }} |
| return m, snapshot, &writes |
| } |
diff --git a/internal/host/rootmigration.go b/internal/host/rootmigration.go| index 99d944ebd..24dc12c6a 100644 |
| --- a/internal/host/rootmigration.go |
| +++ b/internal/host/rootmigration.go |
| @@ -44,6 +44,7 @@ type rootMigrationRecord struct { |
| } |
| type rootMigration struct { |
| prepareRecovery func(context.Context) error |
| + prepareFloors func(context.Context) error |
| guardReady func(context.Context) error |
| state, execution rootstate.Store |
| identity rootMigrationIdentity |
| @@ -137,9 +138,15 @@ func (m rootMigration) run(ctx context.Context) error { |
| if exists && saved.Phase == "complete" { |
| return (rootparticipation.Ledger{State: m.execution}).MigrationCensus(ctx, rootparticipation.Census{Box: m.identity.Box, Enrollment: m.identity.Enrollment, Migration: m.identity.Generation}, true) |
| } |
| - if m.guardReady == nil { |
| + if m.prepareFloors == nil || m.guardReady == nil { |
| return errRootMigrationBusy |
| } |
| + // The floor directories are repaired under the lock and quiesce, before |
| + // guardReady's first floor read: a directory an earlier attempt left |
| + // 0700 would otherwise refuse that read on every rerun. |
| + if err := m.prepareFloors(ctx); err != nil { |
| + return err |
| + } |
| if err := m.guardReady(ctx); err != nil { |
| return err |
| } |
diff --git a/internal/host/rootmigration_floordirs_linux_test.go b/internal/host/rootmigration_floordirs_linux_test.go| index 97122b7c3..0608798bd 100644 |
| --- a/internal/host/rootmigration_floordirs_linux_test.go |
| +++ b/internal/host/rootmigration_floordirs_linux_test.go |
| @@ -3,46 +3,196 @@ |
| package host |
| import ( |
| + "context" |
| + "errors" |
| "os" |
| "path/filepath" |
| + "slices" |
| "syscall" |
| "testing" |
| ) |
| -// journal-migrate runs from the window's umask 077 root shell. Its ready |
| -// step's public floor directories must still come out 0755, and a pair an |
| -// earlier run left 0700 is repaired rather than refused forever. |
| +// floorDirsOpt is an opt directory with system/ and system/guard at 0755, |
| +// as guard-arm leaves them, reached with no symlink on the way. |
| +func floorDirsOpt(t *testing.T) string { |
| + t.Helper() |
| + opt, err := filepath.EvalSymlinks(t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + guard := systemGuardDir(opt) |
| + if err := os.MkdirAll(guard, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, dir := range []string{filepath.Join(opt, "system"), guard} { |
| + if err := os.Chmod(dir, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + return opt |
| +} |
| + |
| +func floorDirMode(t *testing.T, dir string) os.FileMode { |
| + t.Helper() |
| + st, err := os.Lstat(dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return st.Mode() |
| +} |
| + |
| +// journal-migrate runs from the window's umask 077 root shell. Both public |
| +// floor directories come out 0755, whether they are missing, left 0700 by |
| +// an earlier attempt, or left by an interrupted mkdirAllExact (mkdir done |
| +// under the umask, chmod never reached). |
| func TestRootFloorDirsIgnoreUmask(t *testing.T) { |
| old := syscall.Umask(0o077) |
| defer syscall.Umask(old) |
| - for _, earlier := range []bool{false, true} { |
| - opt := t.TempDir() |
| - guard := filepath.Join(opt, "system", "guard") |
| - if err := os.MkdirAll(guard, 0o755); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.Chmod(filepath.Join(opt, "system"), 0o755); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.Chmod(guard, 0o755); err != nil { |
| - t.Fatal(err) |
| - } |
| - if earlier { |
| + uid, gid := uint32(os.Getuid()), uint32(os.Getgid()) |
| + for name, earlier := range map[string]func(opt string) error{ |
| + "missing": func(string) error { return nil }, |
| + "moves 0700": func(opt string) error { return os.Mkdir(rootFloorDir(opt), 0o700) }, |
| + "seeds 0700": func(opt string) error { return os.Mkdir(rootSeedsFloorDir(opt), 0o700) }, |
| + "interrupted": func(opt string) error { return os.MkdirAll(rootSeedsFloorDir(opt), 0o755) }, // mkdirAllExact's mkdir, under 077 |
| + "both 0700": func(opt string) error { |
| + return errors.Join(os.Mkdir(rootFloorDir(opt), 0o700), os.Mkdir(rootSeedsFloorDir(opt), 0o700)) |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + opt := floorDirsOpt(t) |
| + if err := earlier(opt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := prepareRootFloorDirsOwned(opt, uid, gid); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, dir := range []string{rootFloorDir(opt), rootSeedsFloorDir(opt), systemGuardDir(opt)} { |
| + if m := floorDirMode(t, dir); !m.IsDir() || m.Perm() != 0o755 { |
| + t.Fatalf("%s is %v, want a 0755 directory", dir, m) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The repair touches only a real directory with the expected owner: a |
| +// symlink (at the directory or on its way), a file, or another owner is |
| +// refused and left as it was. |
| +func TestRootFloorDirsRefuseWhatTheyDoNotOwn(t *testing.T) { |
| + uid, gid := uint32(os.Getuid()), uint32(os.Getgid()) |
| + for name, c := range map[string]struct { |
| + setup func(t *testing.T, opt string) string // returns the path whose mode must not change |
| + uid, gid uint32 |
| + }{ |
| + "symlink": {setup: func(t *testing.T, opt string) string { |
| + target := filepath.Join(opt, "elsewhere") |
| + if err := os.Mkdir(target, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(target, rootFloorDir(opt)); err != nil { |
| + t.Fatal(err) |
| + } |
| + return target |
| + }, uid: uid, gid: gid}, |
| + "symlink on the way": {setup: func(t *testing.T, opt string) string { |
| + real := filepath.Join(opt, "realguard") |
| + if err := os.Rename(systemGuardDir(opt), real); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Mkdir(filepath.Join(real, "moves"), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(real, systemGuardDir(opt)); err != nil { |
| + t.Fatal(err) |
| + } |
| + return filepath.Join(real, "moves") |
| + }, uid: uid, gid: gid}, |
| + "file": {setup: func(t *testing.T, opt string) string { |
| + if err := os.WriteFile(rootFloorDir(opt), nil, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + return rootFloorDir(opt) |
| + }, uid: uid, gid: gid}, |
| + "other owner": {setup: func(t *testing.T, opt string) string { |
| if err := os.Mkdir(rootFloorDir(opt), 0o700); err != nil { |
| t.Fatal(err) |
| } |
| - } |
| - if err := prepareRootFloorDirs(opt); err != nil { |
| - t.Fatal(err) |
| - } |
| - for _, dir := range []string{rootFloorDir(opt), rootSeedsFloorDir(opt), guard} { |
| - st, err := os.Stat(dir) |
| - if err != nil { |
| + return rootFloorDir(opt) |
| + }, uid: uid + 1, gid: gid}, |
| + "other group": {setup: func(t *testing.T, opt string) string { |
| + if err := os.Mkdir(rootFloorDir(opt), 0o700); err != nil { |
| t.Fatal(err) |
| } |
| - if st.Mode().Perm() != 0o755 { |
| - t.Fatalf("earlier=%v: %s is %o, want 755", earlier, dir, st.Mode().Perm()) |
| + return rootFloorDir(opt) |
| + }, uid: uid, gid: gid + 1}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + opt := floorDirsOpt(t) |
| + left := c.setup(t, opt) |
| + before := floorDirMode(t, left) |
| + if err := prepareRootFloorDirsOwned(opt, c.uid, c.gid); err == nil { |
| + t.Fatal("repair accepted it") |
| + } |
| + if after := floorDirMode(t, left); after != before { |
| + t.Fatalf("%s changed from %v to %v", left, before, after) |
| } |
| + }) |
| + } |
| + // Production's owner is root: unprivileged, the test's own directories |
| + // are another owner's, so prepareRootFloorDirs refuses them untouched. |
| + if os.Geteuid() != 0 { |
| + opt := floorDirsOpt(t) |
| + if err := os.Mkdir(rootFloorDir(opt), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := prepareRootFloorDirs(opt); !errors.Is(err, os.ErrPermission) { |
| + t.Fatalf("prepareRootFloorDirs over a non-root directory = %v", err) |
| } |
| + if m := floorDirMode(t, rootFloorDir(opt)); m.Perm() != 0o700 { |
| + t.Fatalf("refused directory is now %v", m) |
| + } |
| + } |
| +} |
| + |
| +// The migration repairs the floor directories under its lock and quiesce, |
| +// before guardReady's first floor read; a refused repair stops it there, |
| +// with no census and no record written. |
| +func TestRootMigrationPreparesFloorsBeforeGuardReady(t *testing.T) { |
| + m, _, _ := migrationFixture(t) |
| + var order []string |
| + quiesce := m.quiesce |
| + m.quiesce = func(ctx context.Context) (func(), error) { order = append(order, "quiesce"); return quiesce(ctx) } |
| + m.prepareFloors = func(context.Context) error { order = append(order, "prepareFloors"); return nil } |
| + m.guardReady = func(context.Context) error { order = append(order, "guardReady"); return nil } |
| + observe := m.observe |
| + m.observe = func(ctx context.Context) (rootMigrationSnapshot, error) { |
| + order = append(order, "observe") |
| + return observe(ctx) |
| + } |
| + if err := m.run(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(order) < 4 || !slices.Equal(order[:4], []string{"quiesce", "prepareFloors", "guardReady", "observe"}) { |
| + t.Fatalf("order = %v", order) |
| + } |
| + |
| + m, _, _ = migrationFixture(t) |
| + guarded := false |
| + m.prepareFloors = func(context.Context) error { return os.ErrPermission } |
| + m.guardReady = func(context.Context) error { guarded = true; return nil } |
| + if err := m.run(t.Context()); !errors.Is(err, os.ErrPermission) || guarded { |
| + t.Fatalf("refused repair: run = %v, guardReady ran = %v", err, guarded) |
| + } |
| + if _, err := m.execution.Read("census.json"); !os.IsNotExist(err) { |
| + t.Fatal("census before the floor repair", err) |
| + } |
| + if _, err := m.state.Read("migration.json"); !os.IsNotExist(err) { |
| + t.Fatal("migration record before the floor repair", err) |
| + } |
| + |
| + m, _, _ = migrationFixture(t) |
| + m.prepareFloors = nil |
| + if err := m.run(t.Context()); !errors.Is(err, errRootMigrationBusy) { |
| + t.Fatalf("no floor repair wired: run = %v", err) |
| } |
| } |
diff --git a/internal/host/rootmigration_production_linux.go b/internal/host/rootmigration_production_linux.go| index 61d4d4736..4fc5c439e 100644 |
| --- a/internal/host/rootmigration_production_linux.go |
| +++ b/internal/host/rootmigration_production_linux.go |
| @@ -85,7 +85,9 @@ func migrateRootClaimAuthority(ctx context.Context, store release.Store, r Claim |
| return timers.adopt(ctx, item, target, canonical) |
| } |
| coordinator := ClaimStopCoordinator{Guard: guard, Claims: hostguard.StoreReader{Store: store}, Inventory: inventory, Kernel: newProductionStopKernel(launches, roots), Evidence: store, EvidenceSigner: owners.EvidenceKey, RequestLimit: hostbox.RequestLimit, Now: time.Now, NewID: func() string { return "migration-" + randomMigrationID() }} |
| - m := rootMigration{guardReady: func(context.Context) error { |
| + m := rootMigration{prepareFloors: func(context.Context) error { |
| + return prepareRootFloorDirs(r.OptDir) |
| + }, guardReady: func(context.Context) error { |
| return verifyRootMigrationFloors(r.OptDir, rootFloorIdentity{Deployment: id.Deployment, Box: id.Box, Enrollment: id.Enrollment}) |
| }, state: state, execution: execution, identity: id, quiesce: rootMigrationQuiesce, observe: collector.collect, deny: func(ctx context.Context, item rootMigrationItem) error { |
| return root.RetainMigrationDeny(ctx, item.Installation, item.Session) |
| @@ -197,18 +199,75 @@ func migrateRootClaimAuthority(ctx context.Context, store release.Store, r Claim |
| }) |
| } |
| -// prepareRootFloorDirs makes the two public floor directories the |
| -// migration's ready step opens, whatever the operator shell's umask (#317's |
| -// class): rootstate creates a public directory with Mkdirat(0755) and never |
| -// chmods, so under umask 077 it would come out 0700, rootstate would refuse |
| -// it, and every rerun would refuse it again. The carlos agent reads the |
| -// floor projections there, so both must be 0755. mkdirAllExact also repairs |
| -// a directory an earlier run left 0700. |
| -func prepareRootFloorDirs(opt string) error { |
| +// prepareRootFloorDirs makes the two public floor directories, guard/moves |
| +// and guard/seeds, 0755 root:root whatever the operator shell's umask |
| +// (#317's class). rootstate creates a public directory with Mkdirat(0755) |
| +// and never chmods, so under umask 077 it comes out 0700 and rootstate's |
| +// public open refuses it; an interrupted mkdirAllExact (mkdir done, chmod |
| +// not) leaves the same. The migration runs this under its lock and |
| +// quiesce, before guardReady's first floor read, so a rerun repairs what an |
| +// earlier attempt left instead of refusing it forever; ready runs it again |
| +// before it opens the floors. |
| +// |
| +// A missing directory is made with mkdirAllExact. An existing one is |
| +// repaired only when it is a real directory (not a symlink, no symlink on |
| +// the way) owned by root:root; anything else refuses and is left alone. |
| +func prepareRootFloorDirs(opt string) error { return prepareRootFloorDirsOwned(opt, 0, 0) } |
| + |
| +// prepareRootFloorDirsOwned is prepareRootFloorDirs with the owner the |
| +// directories must have; production passes root. Tests pass their own. |
| +func prepareRootFloorDirsOwned(opt string, uid, gid uint32) error { |
| for _, dir := range []string{rootFloorDir(opt), rootSeedsFloorDir(opt)} { |
| + if err := repairRootFloorDir(dir, uid, gid); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +func repairRootFloorDir(dir string, uid, gid uint32) error { |
| + if !filepath.IsAbs(dir) || filepath.Clean(dir) != dir || dir == "/" { |
| + return &os.PathError{Op: "repair", Path: dir, Err: os.ErrPermission} |
| + } |
| + if _, err := os.Lstat(dir); errors.Is(err, os.ErrNotExist) { |
| if err := mkdirAllExact(dir, 0755); err != nil { |
| return err |
| } |
| + } else if err != nil { |
| + return err |
| + } |
| + // Open it component by component with O_NOFOLLOW, so the descriptor |
| + // checked and chmodded is the directory itself, reached with no symlink. |
| + fd, err := unix.Open("/", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + return err |
| + } |
| + for _, name := range strings.Split(strings.TrimPrefix(dir, "/"), "/") { |
| + next, err := unix.Openat(fd, name, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| + unix.Close(fd) |
| + if err != nil { |
| + return &os.PathError{Op: "repair", Path: dir, Err: err} |
| + } |
| + fd = next |
| + } |
| + defer unix.Close(fd) |
| + var st unix.Stat_t |
| + if err := unix.Fstat(fd, &st); err != nil { |
| + return err |
| + } |
| + if st.Mode&unix.S_IFMT != unix.S_IFDIR || st.Uid != uid || st.Gid != gid { |
| + return &os.PathError{Op: "repair", Path: dir, Err: os.ErrPermission} |
| + } |
| + if st.Mode&07777 != 0755 { |
| + if err := unix.Fchmod(fd, 0755); err != nil { |
| + return &os.PathError{Op: "repair", Path: dir, Err: err} |
| + } |
| + } |
| + if err := unix.Fstat(fd, &st); err != nil { |
| + return err |
| + } |
| + if st.Mode&07777 != 0755 { |
| + return &os.PathError{Op: "repair", Path: dir, Err: os.ErrPermission} |
| } |
| return nil |
| } |
diff --git a/internal/host/rootmigration_reboot_root_linux_test.go b/internal/host/rootmigration_reboot_root_linux_test.go| index 8448a330c..735876d36 100644 |
| --- a/internal/host/rootmigration_reboot_root_linux_test.go |
| +++ b/internal/host/rootmigration_reboot_root_linux_test.go |
| @@ -32,7 +32,7 @@ func rebootMigration(t *testing.T) (rootMigration, *hostguard.RootAuthority) { |
| } |
| state, execution, fences := open("migration"), open("execution"), open("fences") |
| root := hostguard.NewRootAuthority(fences) |
| - m := rootMigration{guardReady: func(context.Context) error { return nil }, state: state, execution: execution, identity: rootMigrationIdentity{"deploy", "box", "en", 1}, quiesce: func(context.Context) (func(), error) { return func() {}, nil }} |
| + m := rootMigration{prepareFloors: func(context.Context) error { return nil }, guardReady: func(context.Context) error { return nil }, state: state, execution: execution, identity: rootMigrationIdentity{"deploy", "box", "en", 1}, quiesce: func(context.Context) (func(), error) { return func() {}, nil }} |
| m.observe = func(context.Context) (rootMigrationSnapshot, error) { |
| raw, e := state.Read("snapshot.json") |
| var s rootMigrationSnapshot |
diff --git a/internal/hostops/backfill_done_test.go b/internal/hostops/backfill_done_test.go| index 17b48a3d6..0dee11096 100644 |
| --- a/internal/hostops/backfill_done_test.go |
| +++ b/internal/hostops/backfill_done_test.go |
| @@ -468,3 +468,93 @@ func TestDoneVerifiesReportsAsTheCensusDoes(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// doneCohort is the done tests' empty cohort: hosts records (zero or two), |
| +// box-b keyless, box-a's empty report published, the collecting plan's etag |
| +// returned. |
| +func doneCohort(t *testing.T, hosts int) (*activation, string) { |
| + t.Helper() |
| + a := newActivation(t) |
| + for _, host := range []string{doneOne, doneTwo}[:hosts] { |
| + a.record(host, nil) |
| + } |
| + a.keyless("box-b") |
| + tag := a.collecting(a.sg, nil) |
| + if err := PublishCensusReport(a.ctx, a.f.store, a.d, a.emptyReport("box-a"), a.boxKeys["box-a"]); err != nil { |
| + t.Fatal(err) |
| + } |
| + return a, tag |
| +} |
| + |
| +// A record created while Done reads the reports (the first listing has |
| +// already passed) is caught by the second listing, immediately before the |
| +// write: Done refuses and writes nothing. |
| +func TestBackfillDoneRefusesARecordCreatedDuringReportRetrieval(t *testing.T) { |
| + for _, hosts := range []int{0, 2} { |
| + t.Run(fmt.Sprintf("%d hosts", hosts), func(t *testing.T) { |
| + a, tag := doneCohort(t, hosts) |
| + reportAt, err := reportKey("backfill", "box-a") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fired := false |
| + a.f.store.afterGet = func(key string) { |
| + if key != reportAt { |
| + return |
| + } |
| + a.f.store.afterGet = nil |
| + fired = true |
| + a.record("three.shop.example.com", nil) |
| + } |
| + before, beforeTag, err := a.f.store.Get(a.ctx, BackfillKey) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err = (&Backfill{Store: a.f.store, Directory: a.d}).Done(a.ctx, a.sg, tag) |
| + if !fired { |
| + t.Fatal("the report was never read") |
| + } |
| + if !errors.Is(err, ErrDoneRecords) || errors.Is(err, ErrDoneRecordsChanged) { |
| + t.Fatalf("Done = %v; want the records refusal before the write", err) |
| + } |
| + after, afterTag, err := a.f.store.Get(a.ctx, BackfillKey) |
| + if err != nil || !bytes.Equal(before, after) || beforeTag != afterTag { |
| + t.Fatalf("a refused Done changed the plan (%v)", err) |
| + } |
| + if err := CheckCreateFreeze(a.ctx, a.f.store, a.d.PublicKey); !errors.Is(err, ErrPending) { |
| + t.Fatalf("freeze after a refused Done = %v", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A record created after Done's write, before its third listing, is not in |
| +// the done plan. Done has written done and cannot take it back; it says |
| +// so with ErrDoneRecordsChanged (which the claims run reports under the |
| +// records refusal). |
| +func TestBackfillDoneReportsARecordCreatedAfterTheWrite(t *testing.T) { |
| + for _, hosts := range []int{0, 2} { |
| + t.Run(fmt.Sprintf("%d hosts", hosts), func(t *testing.T) { |
| + a, tag := doneCohort(t, hosts) |
| + fired := false |
| + a.f.store.afterPut = func(key string) { |
| + if key != BackfillKey { |
| + return |
| + } |
| + a.f.store.afterPut = nil |
| + fired = true |
| + a.record("three.shop.example.com", nil) |
| + } |
| + _, err := (&Backfill{Store: a.f.store, Directory: a.d}).Done(a.ctx, a.sg, tag) |
| + if !fired { |
| + t.Fatal("Done never wrote the plan") |
| + } |
| + if !errors.Is(err, ErrDoneRecordsChanged) || !errors.Is(err, ErrDoneRecords) { |
| + t.Fatalf("Done = %v; want ErrDoneRecordsChanged", err) |
| + } |
| + if p := a.plan(); p.Phase != "done" || len(p.Hosts) != hosts { |
| + t.Fatalf("plan = %+v; want done over the %d frozen hosts", p, hosts) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/hostops/backfill_publish.go b/internal/hostops/backfill_publish.go| index ada309d0e..1dfbe854c 100644 |
| --- a/internal/hostops/backfill_publish.go |
| +++ b/internal/hostops/backfill_publish.go |
| @@ -117,6 +117,11 @@ var ( |
| ErrDoneReport = fmt.Errorf("%w: backfill done: a keyed box's census report does not verify", ErrIdentity) |
| ErrDoneStale = fmt.Errorf("%w: backfill done: a census report was captured before the plan", ErrIdentity) |
| ErrDoneInstallations = fmt.Errorf("%w: backfill done: a census report lists installations", ErrIdentity) |
| + // ErrDoneRecordsChanged is Done's third listing failing after the write: |
| + // done is written, over a record set that is no longer the plan's. It |
| + // wraps ErrDoneRecords, so the claims run puts the records refusal in |
| + // front of it. |
| + ErrDoneRecordsChanged = fmt.Errorf("%w: done was written over a changed record set", ErrDoneRecords) |
| ) |
| // Done closes an empty cohort's collecting plan straight to done (claim |
| @@ -129,7 +134,8 @@ var ( |
| // - its root envelope verifies; |
| // - it is collecting; |
| // - the live record listing (Apps, Records) is the plan's hosts, by key, |
| -// etag and acquisition; |
| +// etag and acquisition, both before the reports are read and again |
| +// immediately before the write; |
| // - control/hosts/ lists nothing; |
| // - no app has an admission.json; |
| // - every roster box with a census key has a report for the reservation |
| @@ -138,7 +144,9 @@ var ( |
| // |
| // Boxes with no census key are skipped and returned as unreported. The plan |
| // is then written as done under If-Match, with the reporting boxes' digests, |
| -// read back, and CheckCreateFreeze must accept it. |
| +// read back, and CheckCreateFreeze must accept it. The records are listed a |
| +// third time after that; a change there is ErrDoneRecordsChanged, with done |
| +// already written. |
| func (b *Backfill) Done(ctx context.Context, signer release.Signer, collectingETag string) ([]string, error) { |
| raw, tag, err := b.Store.Get(ctx, BackfillKey) |
| if err != nil { |
| @@ -163,32 +171,10 @@ func (b *Backfill) Done(ctx context.Context, signer release.Signer, collectingET |
| } |
| // The live record listing, as the census and collect list it. |
| - apps, err := Apps(ctx, b.Store) |
| + apps, records, err := b.doneRecords(ctx, p.Hosts) |
| if err != nil { |
| return nil, err |
| } |
| - records := map[string]Record{} |
| - for _, app := range apps { |
| - rs, err := Records(ctx, b.Store, app.Account, app.Name) |
| - if err != nil { |
| - return nil, err |
| - } |
| - for _, r := range rs { |
| - if _, dup := records[r.Holder.Host]; dup { |
| - return nil, ErrDoneRecords |
| - } |
| - records[r.Holder.Host] = r |
| - } |
| - } |
| - if len(records) != len(p.Hosts) { |
| - return nil, ErrDoneRecords |
| - } |
| - for host, r := range records { |
| - frozen, ok := p.Hosts[host] |
| - if !ok || frozen.Key != r.Holder.Key || frozen.ETag != r.ETag || frozen.Acquisition == "" || frozen.Acquisition != r.Holder.Acquisition { |
| - return nil, ErrDoneRecords |
| - } |
| - } |
| // No host claim, under the prefix the migration census lists. |
| claims, err := b.Store.List(ctx, "control/hosts/") |
| @@ -264,6 +250,14 @@ func (b *Backfill) Done(ctx context.Context, signer release.Signer, collectingET |
| if err != nil { |
| return nil, err |
| } |
| + // The second listing, after every report was fetched and verified and |
| + // immediately before the write: a record created while the reports were |
| + // read is refused here, and nothing is written. The plan's If-Match |
| + // covers only the plan, so this narrows the window; the trial closes it |
| + // by stopping the console's record writes for the window. |
| + if _, _, err := b.doneRecords(ctx, p.Hosts); err != nil { |
| + return nil, err |
| + } |
| if _, err = b.Store.Put(ctx, BackfillKey, body, tag); err != nil { |
| return nil, err |
| } |
| @@ -277,9 +271,54 @@ func (b *Backfill) Done(ctx context.Context, signer release.Signer, collectingET |
| if err := CheckCreateFreeze(ctx, b.Store, b.Directory.PublicKey); err != nil { |
| return nil, err |
| } |
| + // The third listing, after the write and its readback: a record that |
| + // appeared between the second listing and now is not in the done plan, |
| + // so done was written over a changed record set. Say so; the write |
| + // cannot be taken back here. |
| + if _, _, err := b.doneRecords(ctx, p.Hosts); err != nil { |
| + if errors.Is(err, ErrDoneRecords) { |
| + return nil, ErrDoneRecordsChanged |
| + } |
| + return nil, err |
| + } |
| return unreported, nil |
| } |
| +// doneRecords lists the live records as collect and the census list them |
| +// (Apps, then Records per app) and refuses, with ErrDoneRecords, unless |
| +// they are hosts by key, etag and acquisition, no more and no fewer. Done |
| +// runs it before the reports, again immediately before its write and once |
| +// more after it. |
| +func (b *Backfill) doneRecords(ctx context.Context, hosts map[string]BackfillHost) ([]App, map[string]Record, error) { |
| + apps, err := Apps(ctx, b.Store) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + records := map[string]Record{} |
| + for _, app := range apps { |
| + rs, err := Records(ctx, b.Store, app.Account, app.Name) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + for _, r := range rs { |
| + if _, dup := records[r.Holder.Host]; dup { |
| + return nil, nil, ErrDoneRecords |
| + } |
| + records[r.Holder.Host] = r |
| + } |
| + } |
| + if len(records) != len(hosts) { |
| + return nil, nil, ErrDoneRecords |
| + } |
| + for host, r := range records { |
| + frozen, ok := hosts[host] |
| + if !ok || frozen.Key != r.Holder.Key || frozen.ETag != r.ETag || frozen.Acquisition == "" || frozen.Acquisition != r.Holder.Acquisition { |
| + return nil, nil, ErrDoneRecords |
| + } |
| + } |
| + return apps, records, nil |
| +} |
| + |
| // verifyCensusReport is the census's acceptance of one roster box's report |
| // for the reservation, for Backfill.Done: the envelope verifies under the |
| // box's enrolled census key, the report is complete and names this box, |
diff --git a/internal/hostops/operations_test.go b/internal/hostops/operations_test.go| index 9cfeb5fa1..ab3778dab 100644 |
| --- a/internal/hostops/operations_test.go |
| +++ b/internal/hostops/operations_test.go |
| @@ -58,6 +58,8 @@ type faultStore struct { |
| failGet string |
| afterList func(string, []string) error |
| beforePut func(string) error |
| + afterGet func(string) |
| + afterPut func(string) |
| beforeDelete func(string, string) error |
| bareDeletes int |
| } |
| @@ -74,7 +76,11 @@ func (s *faultStore) Get(ctx context.Context, key string) ([]byte, string, error |
| if key == s.failGet { |
| return nil, "", errors.New("read failed") |
| } |
| - return s.Store.Get(ctx, key) |
| + b, tag, err := s.Store.Get(ctx, key) |
| + if err == nil && s.afterGet != nil { |
| + s.afterGet(key) |
| + } |
| + return b, tag, err |
| } |
| func (s *faultStore) Put(ctx context.Context, key string, b []byte, e string) (string, error) { |
| if s.beforePut != nil { |
| @@ -82,7 +88,11 @@ func (s *faultStore) Put(ctx context.Context, key string, b []byte, e string) (s |
| return "", err |
| } |
| } |
| - return s.Store.Put(ctx, key, b, e) |
| + tag, err := s.Store.Put(ctx, key, b, e) |
| + if err == nil && s.afterPut != nil { |
| + s.afterPut(key) |
| + } |
| + return tag, err |
| } |
| func (s *faultStore) Delete(context.Context, string) error { |
| s.bareDeletes++ |
diff --git a/internal/provision/claim_empty_cohort_fix1_census_test.go b/internal/provision/claim_empty_cohort_fix1_census_test.go| new file mode 100644 |
| index 000000000..4c1817503 |
| --- /dev/null |
| +++ b/internal/provision/claim_empty_cohort_fix1_census_test.go |
| @@ -0,0 +1,25 @@ |
| +package provision |
| + |
| +// plan14ClaimEmptyCohortFix1WriteCensusInventory is the record-write |
| +// inventory for claim-empty-cohort-done's fix round 1, PROPOSED (the ruling |
| +// is owed; docs/superpowers/notes/census-proposal-claim-step8-readiness.md, |
| +// "Fix round 1"). |
| +// |
| +// - Backfill.Done, re-reviewed: it lists the records again (through |
| +// doneRecords: hostops.Apps and hostops.Records, reads only) immediately |
| +// before its one Put and once more after the readback. The Put, its key |
| +// (the backfill manifest) and its If-Match on the collecting etag are |
| +// unchanged, and it writes no record. Still nonrecord. |
| +func plan14ClaimEmptyCohortFix1WriteCensusInventory() []censusEntry { |
| + entries := plan14ClaimStep8ReadinessWriteCensusInventory() |
| + kept := make([]censusEntry, 0, len(entries)+1) |
| + for _, e := range entries { |
| + if e.File == "internal/hostops/backfill_publish.go" && e.Unit == "Backfill.Done" { |
| + continue |
| + } |
| + kept = append(kept, e) |
| + } |
| + return append(kept, |
| + censusEntry{"internal/hostops/backfill_publish.go", "Backfill.Done", "nonrecord", "sel:Put", "c8b9e7f6ab7245c3d26fe472bf12ed11da40acb4113aec9567b99280b5a1a219"}, |
| + ) |
| +} |
diff --git a/internal/provision/plan14_root_reads_test.go b/internal/provision/plan14_root_reads_test.go| index c228fbd55..f7e47331e 100644 |
| --- a/internal/provision/plan14_root_reads_test.go |
| +++ b/internal/provision/plan14_root_reads_test.go |
| @@ -944,6 +944,15 @@ func TestPlan14RootReadCensus(t *testing.T) { |
| if err = loadRootReadInventory(filepath.Join(root, "internal/provision/testdata/plan14-root-reads-claim-step8-readiness.tsv"), &inv, true); err != nil { |
| t.Fatal(err) |
| } |
| + // Census overlay claim-empty-cohort-fix1 (fix round 1 for |
| + // claim-empty-cohort-done: Backfill.Done lists the records again before |
| + // and after its write; the root migration repairs its floor directories |
| + // before the first floor read), loaded last. PROPOSED: the ruling is |
| + // owed (docs/superpowers/notes/census-proposal-claim-step8-readiness.md, |
| + // "Fix round 1"). It adds no accepted-legacy row, so the seal stands. |
| + if err = loadRootReadInventory(filepath.Join(root, "internal/provision/testdata/plan14-root-reads-claim-empty-cohort-fix1.tsv"), &inv, true); err != nil { |
| + t.Fatal(err) |
| + } |
| errs := append(compareRootReads(got, inv), checkRootReadLegacy(inv, seal)...) |
| errs = append(errs, checkRootReadDeclarations(got, inv)...) |
| if len(errs) > 0 { |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index bb9c60dfa..1dbfd4563 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := plan14ClaimStep8ReadinessWriteCensusInventory() |
| + inventory := plan14ClaimEmptyCohortFix1WriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
diff --git a/internal/provision/testdata/plan14-root-reads-claim-empty-cohort-fix1.tsv b/internal/provision/testdata/plan14-root-reads-claim-empty-cohort-fix1.tsv| new file mode 100644 |
| index 000000000..ca03aa6ca |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-claim-empty-cohort-fix1.tsv |
| @@ -0,0 +1,8 @@ |
| +# Census overlay claim-empty-cohort-fix1 (fix round 1 for claim-empty-cohort-done: Astra's F1 and F2 as ruled by platform-1e), loaded LAST, after claim-step8-readiness. PROPOSED: the ruling is owed; the proposal is docs/superpowers/notes/census-proposal-claim-step8-readiness.md, section "Fix round 1". |
| +# Existing units keep their class and task exactly; their bases add what changed. F1: Backfill.Done lists the records again immediately before its If-Match write and a third time after the readback (through the new doneRecords, which has no root read site of its own). F2: rootMigration.run calls the new prepareFloors hook under its lock and quiesce, before guardReady; migrateRootClaimAuthority wires it to prepareRootFloorDirs; repairRootFloorDir is new. It adds no accepted-legacy row, so the seal stands. |
| +@coverage internal/host bc2a8da7c5f677b99b65312d4fd062fc865dcfdfff0245be62a316f4e364924f |
| +@coverage internal/hostops c37d041f6adf34458e5123fc32e506c610eb2e96b5b575c0ba6062cf960e5290 |
| +internal/hostops/backfill_publish.go Backfill.Done authority F,G,J4 rev3=PROPOSED-claim-empty-cohort-fix1;identity=explicit operator CLI uid 0 on the trusted signing host (carlos system claims run backfill-done, the only caller);basis=as ruled under census-ruling-claim-step8-readiness: reads the signed collecting plan, the roster, the record listing, control/hosts/, each app's admission and each keyed box's signed census report, refusing unless the listing is the plan's, no claim or admission exists and every keyed report verifies as the census verifies it and lists no installation; its one write is the plan as done under the collecting etag (If-Match), read back and checked by CheckCreateFreeze; it adopts and installs nothing. Fix round 1 (F1): the record listing (Apps, Records, the same comparison) is taken again immediately before the write, refusing with nothing written if it is no longer the plan's, and a third time after the readback, reporting ErrDoneRecordsChanged if a record changed after the write; the trial closes the remaining window by stopping the dev console's record writes from 8.1b to 8.2b file:Read@2516,file:Read@544 c8b9e7f6ab7245c3d26fe472bf12ed11da40acb4113aec9567b99280b5a1a219 |
| +internal/host/rootmigration.go rootMigration.run authority G,J4 rev3=PROPOSED-claim-empty-cohort-fix1;identity=carlos system journal-migrate offline uid 0;basis=offline guarded migration reobserves changed claims, retains union of session tuples, publishes only durable completion and verifies completed replay without rewriting census. Fix round 1 (F2): under its migration lock and quiesce it now calls the required prepareFloors hook before guardReady, so the floor directories are repaired before the first floor read; a refused repair stops the run before any census or record write file:Read@508 a59b29f1ec5f91d134ad104a4692fa3ee7366e42f552cbbebf1136da15026e1b |
| +internal/host/rootmigration_production_linux.go migrateRootClaimAuthority authority G,J4,E3 rev3=PROPOSED-claim-empty-cohort-fix1;run=15;identity=offline root migration uid 0;basis=requires masked inactive root mutator units and no running legacy root command under mandatory release exclusion; ordinary nonparticipants acquire no migration lock; the census classifies with claimMigrationSharedPaths after verifyMigrationWindow, and the public floor directories are made 0755 whatever the operator's umask. Fix round 1 (F2): prepareFloors is wired to prepareRootFloorDirs, which repairs guard/moves and guard/seeds to 0755 only when each is a real root:root directory, before guardReady; ready still calls it before opening the floors file:Open@1814,file:Open@374,file:Open@615,file:Open@7378,file:Open@739,file:Read@2766,file:ReadFile@1571,whole:Route@3079 e04533d6e85df45a302c134827870ca6e0f147a2e0569b3fb414897dbf77ec3d |
| +internal/host/rootmigration_production_linux.go repairRootFloorDir authority G,J4 rev3=PROPOSED-claim-empty-cohort-fix1;identity=carlos system journal-migrate, offline operator CLI, uid 0;basis=new: Lstat of one of the two fixed floor directories (guard/moves, guard/seeds) to decide whether mkdirAllExact makes it; then the path opened component by component from / with O_NOFOLLOW and O_DIRECTORY, Fstat of the directory itself, and Fchmod to 0755 only when it is a directory owned by root:root; a symlink anywhere on the path, a file or another owner refuses with nothing changed; no file content is read file:Fstat@1327,file:Fstat@974,file:Lstat@220,file:Open@534,file:Openat@720 4716e8029568ea5efdc6464fc91abf30a85ce033290db75e4eee65f10328c7b7 |