carlos / platform Public

durability 3a: one account lock for instance create and fleet key replacement

Refuse replacing a fleet's secrets key while a placed app has instance
records, including malformed records, before writing either key record.
Take the account lock unconditionally at instance create and allocation
recovery so their records cannot race the key's membership check.

Pin the production creator calls and add deterministic lock witnesses
with plans disabled, conservative store-error coverage, and purge coverage.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 3c67bc6411b435f32c8367558305c84b565a0704 parent 83b2153
8 files changed, +616 −20
  • internal/console/apiinstances.go +4 −3
  • internal/console/fleetsecrets_race_test.go +207 −0
  • internal/console/fleetsecretskey.go +44 −0
  • internal/console/fleetsecretskey_test.go +206 −0
  • internal/console/lifetimes_audit_test.go +3 −0
  • internal/console/lifetimes_create_test.go +5 −17
  • internal/console/lifetimes_recovery.go +4 −0
  • internal/console/recordcreators_guard_test.go +143 −0

Intent

Human

<task-notification> <task-id>a687a4341ffd05b6a</task-id> <tool-use-id>toolu_01P8QCoVjt8H2BQ8dqBiHXk2</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/953e7524-2e06-4308-b9ce-fd1b38579971/tasks/a687a4341ffd05b6a.output</output-file> <status>completed</status> <summary>Agent "Implement Task 5: parked-path refusals" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE. All three of Astra's P2s are fixed; nothing is pushed. The `internal/host` run is not clean: 21 claim-assembly tests fail, but the same 20 of them fail at the pre-Task-5 commit too (details under Concerns). Commits: 83b2153a (parent 14f582d0). Tests: - **Detector:** a raw revision is now reported exactly once, even when seen out of order or by 16 goroutines at once. A restore that fails still reports, with no extra GET. Both new tests failed against the old code and pass now, under `-race`. - **Skips:** before, 263 tests were skipped whole. Now 65 run in full (two renamed), 68 skip only their refused subtests, 45 run their earlier checks and then skip, and 85 still skip whole. Those 85 install the refused prepared manifest in their own setup. Every test Astra named runs again, the lease-loss checks included. The report lists every test by outcome. - **One fix beyond the review:** `RefuseSecretsAt` asked the classifier again for every directory above each path, so a tree past the length cap took over 20 s to refuse. It now judges each entry once; that case takes 0.4 s, with a new test. - **Packages:** `hostfiles` and the census tests pass, and so do the darwin and windows builds. I appended census claims for `restoreFilesClean` and `Restore` and re-ran `census-propose`. Concerns: - **21 `internal/host` failures, run with TMPDIR=/tmp/g:** all 21 stop at `instance-control start: hostwrite: lifecycle provider unavailable`. 20 of them fail the same way at 14f582d0 and at 1ead41b1, both checked in temporary worktrees, even though they passed here around 13:35Z. Something on the machine changed this afternoon. The 21st is `TestClaimServingAssemblyWithoutMoves`, which I un-skipped; it fails the same way, and at the base commit too when run alone. I did not find the cause. - **Activator:** two tests failed in the full run. One is known flake #460, the other failed under load. Both pass with `-count=3` here and at HEAD. - **The 85 whole skips stay:** removing them would mean reworking the shared moves and claim test harnesses, which the earlier ruling ruled out. - **The census verdict on #280 is still owed.** Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/durability-3a/.superpowers/sdd/2026-10-30-durability-step3-escrow-fence-restore/task-5-report.md</result> <usage><subagent_tokens>524448</subagent_tokens><tool_uses>122</tool_uses><duration_ms>3628578</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bcz7ljeie</task-id> <tool-use-id>toolu_01VtCQADvWtTjEmw2gteRvjj</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/953e7524-2e06-4308-b9ce-fd1b38579971/tasks/bcz7ljeie.output</output-file> <status>completed</status> <summary>Background command "Check the Astra implementer log is growing" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>ac0ab151121ec0821</task-id> <tool-use-id>toolu_01Hjb9BgV2p3GnsNJs5Y8yc2</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/953e7524-2e06-4308-b9ce-fd1b38579971/tasks/ac0ab151121ec0821.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 5 fix round 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Finding Verdicts - **P2: report each raw revision once.** ADDRESSED. `internal/activator/hafiles.go:72-123` (the diff hunk at `@@ -58,65 +58,90 @@`) now splits the book into two maps. `last` is only an inspection cache (`inspected` and `look`). `reported`, a per-host set of revisions, alone decides whether a report is made. `claim` checks and sets it under `mu`, so R โ†’ R+1 โ†’ R cannot report R twice. Neither can concurrent observers: several of them can get past `inspected` at once, but `claim` is still atomic. `noteRawBaseline` uses only `inspected` as a hint, so it can skip a decode but never causes a second report. The witness `TestEachRawRevisionIsReportedOnce` (`internal/activator/rawsecret_test.go`, added after line 184) covers R, R+1, R and 16 concurrent observers of R+2. The fix report shows the red run against 14f582d0 (`[4 5 4]`) and a green run under `-race`. - **P2: detect a manifest even when restoration fails.** ADDRESSED. `internal/hostfiles/restore.go` (the `restore` hunk at `@@ -98,49 +98,62 @@`) adds a `checked` callback that runs right after `checkManifest(m, origins)`. That is before the tombstones, `open`, any fetch or any write. `RestoreRootBaselineObserved` threads it through. `Restore` and `RestoreRootBaselineShadowed` pass nil, so they behave as before. `internal/activator/hawake.go:637` passes `noteRawSecrets(host, m)`, and the old post-success call is gone. No request is added. The witness `TestARawItemIsReportedWhenTheRestoreFails` deletes an app object, gets a failed restore and still sees one report at the raw revision. The counting store sees 2 GETs and 0 PUTs. The report shows the red run against 14f582d0. - **P2: preserve checks outside refused flows.** ADDRESSED for every named item. - `TestConfiguredRendersUnderTheHeldConfigSelection`: the whole-test skip is gone and the landing sub-case uses the new `sourceEnvAbsent()` (`movesheldclaim_test.go` hunks at 226 and 321; option at `movesphase1_harness_test.go:409`). - `TestPagingIsRateLimited`: the whole skip is gone. A name-matched `skipParkedSecretSubtests` skips 4 of the 15 subtests and 11 run. The names match `t.Name()`'s underscore spelling (`movespaging_test.go`). - `TestPreparedBuildBoundsEveryRead`: runs with `wantEnv=false`. The version count is now 3, for the two objects and the manifest (`movesfiles_test.go` hunk at 516). - The two lease-loss tests: every lease-loss assertion now runs, and the skip sits only before `h.freshTarget(); h.land; h.installed` (`movesland_test.go:1948, 2051`). - The replay tests: they run through a `preparedFixture` that commits the pre-3a shape (raw env item) directly through `hostfiles.NewPrepared`. So `establishedOver` is exercised: it drops the env at seq 1, and an env entry or a fabricated seq on replay is refused (`movesfiles_test.go` hunks at 728 and 1735). - The four flush safety tests: the fixture no longer places an env, and the four tests have no skip. The env-plant cases write an env first and expect the safe-ground error, or `ErrSecretPath` for an oversized regular file (`relocationflush_saferead_linux_test.go` hunks at 182 and 220). - Checked by grep: none of `movesfiles_test.go`, `relocationflush_saferead_linux_test.go`, `movesheldclaim_test.go` or `movespaging_test.go` has a `skipParkedSecretFlow(t` left. I spot-checked tests still skipped whole: `TestSourceParkWaitsUnarmedInProduction`, `TestTargetRollbackUnarmedInProduction`, `TestMoveLocalRetirementsAreFindableByOp` and `TestReleaseTimeArchiveRefusalGoesStuck`. Each builds its harness with `newFinalHarness` or `newRollbackHarness`, which flips, lands and calls `installed` during setup (`movesrollback_test.go:56-65`), so the refused flow is in their setup. That matches the report's reason. ### New Breakage in the Fix Diff - Minor: `internal/hostfiles/refuse.go`, `refuseBeneath`. It checks `withinTreeCap` before `judge` on every entry, whereas `walkDir` checks the cap only after its skip. So a secret-named entry past the cap is refused with `ErrTooDeep` rather than `ErrSecretPath`. It is still refused and nothing is published. I mention it only because the doc comment says "naming the first path whose class ... is not App". Everything else matches `walkDir`'s primitives: `look` without following links, `openDir` with O_NOFOLLOW, the `betweenLookAndOpen` seam, ENOENT and not-a-directory skipped. `pubclass.Of` ignores `isDir` (`pubclass.go:121`), so judging a directory that is later swapped for a file changes no verdict. - Minor: in `TestEachRawRevisionIsReportedOnce`, the 16 goroutines' race is mostly absorbed by the `inspected` cache, so the concurrent part does not reliably drive `claim` under contention. The code is correct by inspection, because `claim` is under `mu`. ### Out-of-Scope Observations - `TestClaimServingAssemblyWithoutMoves` is listed as "run in full", but the fix report says it fails at HEAD with `hostwrite: lifecycle provider unavailable` (`internal/hostwrite/write.go:9`). Twenty other claim-assembly tests fail the same way, and the report says they fail the same way at the base commits too. Until that environment failure is resolved, this test does not show it has kept its checks. The controller should ledger it with the 20 for the final review. - 85 tests remain skipped whole because their harness setup lands a move whose archive carries `&lt;host&gt;.env`. Un-skipping them needs a change to the shared `installed` and env-carrying harness. Ledger this for the final review, not this task. ### Verdict **Fix round:** All findings addressed, no new Critical/Important breakage.</result> <usage><subagent_tokens>125575</subagent_tokens><tool_uses>24</tool_uses><duration_ms>235928</duration_ms></usage> </task-notification>

Attributed to this commit: 130 g CO₂e (4,950,713 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on durability-3a-escrow, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index c0c79ece3..2c4549b53 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -2251,9 +2251,10 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
jsonError(w, ref.Status, ref.Msg)
return
}
- // Plans 3a: an instance is a running thing. Checked once here, so plain,
- // seeded and imported creates all meet the cap, under the account lock.
- defer s.planLock(acct)()
+ // Plain, seeded and imported creates hold the account lock even without
+ // plans: fleet key replacement checks their records under the same lock.
+ // With plans on, the running-things count and write also share this hold.
+ defer s.lockAccount(acct.Sqid)()
if err := s.checkRunningThings(r.Context(), acct, 1); err != nil {
if isPlanCap(err) {
writeJSON(w, http.StatusConflict, map[string]any{"error": err.Error(), "code": "cap"})
diff --git a/internal/console/fleetsecrets_race_test.go b/internal/console/fleetsecrets_race_test.go
new file mode 100644
index 000000000..6a33a9a26
--- /dev/null
+++ b/internal/console/fleetsecrets_race_test.go
@@ -0,0 +1,207 @@
+package console
+
+import (
+ "context"
+ "net/http"
+ "sync"
+ "sync/atomic"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+// These witnesses keep plans off: the account lock must protect the key
+// even on deployments where there is no cap to enforce.
+func fskCreateFixture(t *testing.T) (*consoleFixture, string) {
+ t.Helper()
+ fx, token, _ := fskFixture(t, "code-fsk-create-race")
+ fskPlaceShop(t, fx, token, "home")
+ enableInstances(t, fx, "shop", provision.Manifest{Schema: 1, App: "shop", Domain: "shop.example.com", Channel: "stable"})
+ if fx.srv.cfg.PlanCatalog != nil {
+ t.Fatal("witness requires plans off")
+ }
+ pub, _ := fskKey(t)
+ fskRegister(t, fx, token, pub)
+ return fx, token
+}
+
+type fskResponse struct {
+ status int
+ body string
+}
+
+func fskAsyncCreate(t *testing.T, fx *consoleFixture, token string) <-chan fskResponse {
+ t.Helper()
+ done := make(chan fskResponse, 1)
+ go func() {
+ status, _, body := rawReq(t, http.MethodPost, instancesURL(fx, fx.sqid, "shop"), token, `{"host":"`+ltOne+`"}`)
+ done <- fskResponse{status, body}
+ }()
+ return done
+}
+
+func fskAsyncReplace(t *testing.T, fx *consoleFixture, token, pub string) <-chan fskResponse {
+ t.Helper()
+ done := make(chan fskResponse, 1)
+ go func() {
+ status, _, body := rawReq(t, http.MethodPut, fskURL(fx, fx.sqid, "home"), token, `{"pubkey":"`+pub+`"}`)
+ done <- fskResponse{status, body}
+ }()
+ return done
+}
+
+func parkFleetKey(t *testing.T) *pauseGate {
+ t.Helper()
+ p := newPauseGate()
+ var once sync.Once
+ h := func(stage string) {
+ if stage == "after-membership-check" {
+ once.Do(func() {
+ close(p.entered)
+ <-p.release
+ })
+ }
+ }
+ fleetKeyHook.Store(&h)
+ t.Cleanup(func() {
+ fleetKeyHook.Store(nil)
+ p.open()
+ })
+ return p
+}
+
+func TestCreateParkedAfterItsRecordWriteBlocksReplacement(t *testing.T) {
+ fx, token := fskCreateFixture(t)
+ held, resume := parkCreate(t, instanceCreateAfterRecordWrite, ltOne)
+ create := fskAsyncCreate(t, fx, token)
+ await(t, held, "create's record write")
+ pubB, _ := fskKey(t)
+ replace := fskAsyncReplace(t, fx, token, pubB)
+ waitForWaiter(t, &fx.srv.acctLocks, fx.sqid)
+ close(resume)
+ if got := await(t, create, "create response"); got.status != http.StatusCreated {
+ t.Fatalf("create = %+v", got)
+ }
+ if got := await(t, replace, "replacement refusal"); got.status != http.StatusConflict || ltErr(got.body) != fskInstanceRefusal("shop") {
+ t.Fatalf("replacement = %+v, want 409 naming shop", got)
+ }
+}
+
+func TestReplacementParkedAfterItsCheckBlocksCreate(t *testing.T) {
+ fx, token := fskCreateFixture(t)
+ pubB, fpB := fskKey(t)
+ p := parkFleetKey(t)
+ replace := fskAsyncReplace(t, fx, token, pubB)
+ await(t, p.entered, "replacement's membership check")
+ var recordWritten atomic.Bool
+ var keyAtWrite atomic.Value
+ h := func(stage, host string) {
+ if stage == instanceCreateAfterRecordWrite && host == ltOne {
+ keyAtWrite.Store(fskFleetRow(t, fx, "home").SecretsKeyFP)
+ recordWritten.Store(true)
+ }
+ }
+ instanceCreateHook.Store(&h)
+ t.Cleanup(func() { instanceCreateHook.Store(nil) })
+ create := fskAsyncCreate(t, fx, token)
+ waitForWaiter(t, &fx.srv.acctLocks, fx.sqid)
+ if recordWritten.Load() {
+ t.Fatal("create reached its record write while replacement was parked")
+ }
+ if raw, _ := rawOf(t, fx.rel, "shop", ltOne); raw != nil {
+ t.Fatal("record exists while replacement is parked")
+ }
+ p.open()
+ if got := await(t, replace, "replacement commit"); got.status != http.StatusOK {
+ t.Fatalf("replacement = %+v", got)
+ }
+ if got := await(t, create, "create after replacement"); got.status != http.StatusCreated {
+ t.Fatalf("create = %+v", got)
+ }
+ if !recordWritten.Load() || keyAtWrite.Load() != fpB {
+ t.Fatalf("key at record write = %v, want B (%s)", keyAtWrite.Load(), fpB)
+ }
+}
+
+func TestReplacementParkedAfterItsCheckBlocksRecovery(t *testing.T) {
+ l := newLtOn(t)
+ fx := l.fx
+ fx.srv.cfg.SecretsPub, _ = mustTestSecretsKey()
+ if fx.srv.cfg.PlanCatalog != nil {
+ t.Fatal("witness requires plans off")
+ }
+ if status, body := postJSON(t, fleetsURL(fx, fx.sqid)+"/new", map[string]string{"name": "home", "bucket": "home-data"}, l.operator); status != http.StatusOK {
+ t.Fatalf("create fleet = %d %v", status, body)
+ }
+ if status, body := postJSON(t, placeURL(fx, "shop"), map[string]string{"target": "fleet/home"}, l.operator); status != http.StatusOK {
+ t.Fatalf("place shop = %d %v", status, body)
+ }
+ pubA, _ := fskKey(t)
+ pubB, fpB := fskKey(t)
+ fskRegister(t, fx, l.operator, pubA)
+ a := l.pendingCreate(t, ltOne, "record")
+ if raw, _ := rawOf(t, fx.rel, "shop", ltOne); raw != nil {
+ t.Fatal("pending allocation already has a record")
+ }
+ p := parkFleetKey(t)
+ replace := fskAsyncReplace(t, fx, l.operator, pubB)
+ await(t, p.entered, "replacement's membership check")
+ var keyAtWrite atomic.Value
+ l.bucket.setAfter(func(op, key string, err error) {
+ if op == "put" && key == recKey("shop", ltOne) && err == nil {
+ keyAtWrite.Store(fskFleetRow(t, fx, "home").SecretsKeyFP)
+ }
+ })
+ done := make(chan error, 1)
+ go func() { done <- fx.srv.recoverLifetimes(context.Background()) }()
+ waitForWaiter(t, &fx.srv.acctLocks, fx.sqid)
+ if raw, _ := rawOf(t, fx.rel, "shop", ltOne); raw != nil {
+ t.Fatal("recovery wrote a record while replacement was parked")
+ }
+ p.open()
+ if got := await(t, replace, "replacement commit"); got.status != http.StatusOK {
+ t.Fatalf("replacement = %+v", got)
+ }
+ if err := await(t, done, "allocation recovery"); err != nil {
+ t.Fatal(err)
+ }
+ oneAlloc(t, fx.st, ltOne, lifetimeCommitted)
+ requireServing(t, fx.rel, "shop", ltOne, 1, a.OpID)
+ if keyAtWrite.Load() != fpB {
+ t.Fatalf("key at recovery's record write = %v, want B (%s)", keyAtWrite.Load(), fpB)
+ }
+}
+
+func TestPurgeRecoveryWritesNoRecord(t *testing.T) {
+ for _, step := range []string{"slot", "record"} {
+ t.Run(step, func(t *testing.T) {
+ l := newLtOn(t)
+ l.pendingCreate(t, ltOne, step)
+ trashShop(t, l)
+ allocs, err := l.fx.st.PendingLifetimesForApp(l.fx.sqid, "shop")
+ if err != nil || len(allocs) != 1 {
+ t.Fatalf("pending allocations = %+v, %v", allocs, err)
+ }
+ var recordPuts atomic.Int32
+ l.bucket.setHook(func(op, key string) error {
+ if op == "put" && key == recKey("shop", ltOne) {
+ recordPuts.Add(1)
+ }
+ return nil
+ })
+ ctx := onCtx(t, l.fx.srv)
+ if err := l.fx.srv.withAppHost(l.fx.sqid, "shop", ltOne, func() error {
+ return l.fx.srv.purgeHostLocked(ctx, l.fx.sqid, "shop", ltOne, allocs, nil)
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if recordPuts.Load() != 0 {
+ t.Fatalf("purge recovery attempted %d record writes", recordPuts.Load())
+ }
+ if raw, _ := rawOf(t, l.fx.rel, "shop", ltOne); raw != nil {
+ t.Fatal("purge recovery left a record")
+ }
+ oneAlloc(t, l.fx.st, ltOne, lifetimeVoid)
+ })
+ }
+}
diff --git a/internal/console/fleetsecretskey.go b/internal/console/fleetsecretskey.go
index 548f47942..23ba0b018 100644
--- a/internal/console/fleetsecretskey.go
+++ b/internal/console/fleetsecretskey.go
@@ -28,14 +28,17 @@ import (
"errors"
"fmt"
"log"
+ "math"
"net/http"
"sort"
"strings"
+ "sync/atomic"
"time"
"github.com/carlosframework/platform/internal/appconfig"
"github.com/carlosframework/platform/internal/mail"
"github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
)
@@ -43,6 +46,9 @@ import (
// reads of every app on the fleet, and the owner record write.
const fleetSecretsKeyTimeout = 30 * time.Second
+// fleetKeyHook is called at after-membership-check with the account lock held.
+var fleetKeyHook atomic.Pointer[func(stage string)]
+
// staleApp is one app's line of the key door's stale report: the sealed
// vars, across every bundle, not sealed to the fleet's key. Minted holds the
// ones the console minted (store, mail, relay credentials), Vars the rest.
@@ -131,6 +137,19 @@ func (s *Server) handleAPIFleetSecretsKey(w http.ResponseWriter, r *http.Request
jsonError(w, http.StatusConflict, fmt.Sprintf("%s already has a different secrets key, and these apps hold sealed values: %s. replacing the key would leave them unreadable. unset each app's secrets with carlos secrets unset --app <app> <var>, then run this again", row.Name, strings.Join(apps, ", ")))
return
}
+ apps, err = s.fleetHasInstances(ctx, acct, row.Name)
+ if err != nil {
+ log.Printf("console: fleet secrets key %s/%s: instances: %v", acct.Sqid, row.Name, err)
+ notRecorded(http.StatusBadGateway)
+ return
+ }
+ if len(apps) > 0 {
+ jsonError(w, http.StatusConflict, fmt.Sprintf("%s already has a different secrets key, and these apps have instances on it: %s. their sealed copies open only with the current key, so it cannot be replaced while they exist. keep the current key, or delete those instances first", row.Name, strings.Join(apps, ", ")))
+ return
+ }
+ }
+ if h := fleetKeyHook.Load(); h != nil {
+ (*h)("after-membership-check")
}
if err := s.recordFleetKeyFP(ctx, *row, fp); err != nil {
log.Printf("console: fleet secrets key %s/%s: owner record: %v", acct.Sqid, row.Name, err)
@@ -163,6 +182,31 @@ func (s *Server) handleAPIFleetSecretsKey(w http.ResponseWriter, r *http.Request
writeJSON(w, http.StatusOK, answer)
}
+// fleetHasInstances lists, sorted, the fleet's placed apps that have any
+// instance record, or any record that cannot be read: their instances'
+// escrows are sealed to the current key. Conservative: it does not look
+// for the escrows themselves. Called under the account lock.
+func (s *Server) fleetHasInstances(ctx context.Context, acct *Account, fleet string) ([]string, error) {
+ apps, err := s.fleetPlacedApps(acct, fleet)
+ if err != nil {
+ return nil, err
+ }
+ if s.cfg.Releases == nil {
+ return nil, errors.New("fleet instances: no deployment store")
+ }
+ var out []string
+ for _, app := range apps {
+ recs, unreadable, err := provision.ListRecordsStrict(ctx, s.cfg.Releases, acct.Sqid, app, math.MaxInt)
+ if err != nil {
+ return nil, err
+ }
+ if len(recs) > 0 || len(unreadable) > 0 {
+ out = append(out, app)
+ }
+ }
+ return out, nil
+}
+
// fleetHasSealedValues lists, sorted, the apps placed on fleet that hold any
// sealed var in any bundle, whatever key it says it is sealed to (ยง5.6: a
// value with no sealed_to may still be sealed to the current key).
diff --git a/internal/console/fleetsecretskey_test.go b/internal/console/fleetsecretskey_test.go
index 847ac0912..858ebb985 100644
--- a/internal/console/fleetsecretskey_test.go
+++ b/internal/console/fleetsecretskey_test.go
@@ -12,13 +12,18 @@ package console
import (
"context"
"encoding/json"
+ "fmt"
"net/http"
+ "os"
"strings"
"testing"
"time"
"github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/hostfiles"
"github.com/carlosframework/platform/internal/hostops"
+ "github.com/carlosframework/platform/internal/layout/pubclass"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
)
@@ -425,6 +430,207 @@ func TestFleetSecretsKeyReplacementRefusedWhileSealed(t *testing.T) {
}
}
+func fskRegister(t *testing.T, fx *consoleFixture, token, pub string) {
+ t.Helper()
+ if status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pub}, token); status != http.StatusOK {
+ t.Fatalf("register key = %d %v", status, body)
+ }
+}
+
+func fskInstanceRefusal(apps string) string {
+ return fmt.Sprintf("home already has a different secrets key, and these apps have instances on it: %s. their sealed copies open only with the current key, so it cannot be replaced while they exist. keep the current key, or delete those instances first", apps)
+}
+
+func fskEscrow(t *testing.T, fx *consoleFixture, privateKey string) {
+ t.Helper()
+ ctx := context.Background()
+ priv, err := appconfig.ParsePrivateKey(privateKey, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ seal, err := hostfiles.NewItemSealer(priv, appconfig.Binding{Account: fx.sqid, App: "shop"}, ltOne)
+ if err != nil {
+ t.Fatal(err)
+ }
+ prefix := ltOne + "/files/0/"
+ p, err := hostfiles.Open(ctx, fx.rel, prefix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rel, ok := pubclass.SealedPath(pubclass.Nested, ltOne, ltOne+"/instance.key")
+ if !ok {
+ t.Fatal("instance.key was not classified as sealed")
+ }
+ if err := p.StageSealed(ctx, rel, []byte("instance-secret"), seal); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := p.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ m, found, err := hostfiles.Load(ctx, fx.rel, prefix)
+ if err != nil || !found {
+ t.Fatalf("escrow manifest: found %v, %v", found, err)
+ }
+ if plain, err := hostfiles.ReadSealed(ctx, fx.rel, prefix, m, "instance.key.sealed", nil, seal); err != nil || string(plain) != "instance-secret" {
+ t.Fatalf("escrow = %q, %v", plain, err)
+ }
+}
+
+func TestFleetKeyReplacementRefusedWhileAnInstanceIsPlaced(t *testing.T) {
+ for _, escrow := range []bool{true, false} {
+ t.Run(fmt.Sprintf("escrow=%v", escrow), func(t *testing.T) {
+ fx, token, spy := fskFixture(t, "code-fsk-instance")
+ fskPlaceShop(t, fx, token, "home")
+ privA, pubA, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ pubB, _ := fskKey(t)
+ fskRegister(t, fx, token, pubA)
+ legacyRecord(t, fx.rel, ltOne, "stable")
+ if escrow {
+ fskEscrow(t, fx, privA)
+ }
+ row := fskFleetRow(t, fx, "home")
+ ownerKey := release.FleetOwnerKey(fx.sqid, "home")
+ before, _, err := fx.rel.Get(context.Background(), ownerKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ spy.reset()
+ status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pubB}, token)
+ if status != http.StatusConflict || body["error"] != fskInstanceRefusal("shop") {
+ t.Errorf("replacement = %d %v, want 409 naming shop", status, body)
+ }
+ if after := fskFleetRow(t, fx, "home"); after != row {
+ t.Errorf("refusal changed fleet row: before %+v, after %+v", row, after)
+ }
+ after, _, err := fx.rel.Get(context.Background(), ownerKey)
+ if err != nil || string(after) != string(before) {
+ t.Errorf("refusal changed owner record: %s, %v", after, err)
+ }
+ if _, puts := spy.counts(); puts != 0 {
+ t.Errorf("refusal made %d owner record writes", puts)
+ }
+ })
+ }
+}
+
+func TestFleetKeyReplacementNamesEveryPlacedAppSorted(t *testing.T) {
+ fx, token, _ := fskFixture(t, "code-fsk-sorted-instances")
+ pubA, _ := fskKey(t)
+ pubB, _ := fskKey(t)
+ fskRegister(t, fx, token, pubA)
+ for _, app := range []string{"zebra", "shop", "alpha"} {
+ if _, err := fx.st.CreateAppIn(OpsAccountID, app, "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if status, body := postJSON(t, placeURL(fx, app), map[string]string{"target": "fleet/home"}, token); status != http.StatusOK {
+ t.Fatalf("place %s = %d %v", app, status, body)
+ }
+ if err := provision.CreateRecord(context.Background(), fx.rel, provision.Record{Schema: 1, Account: fx.sqid, App: app, Host: "one." + app + ".example.com", Channel: "stable", CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pubB}, token); status != http.StatusConflict || body["error"] != fskInstanceRefusal("alpha, shop, zebra") {
+ t.Fatalf("replacement = %d %v, want sorted app names", status, body)
+ }
+}
+
+func TestFleetKeyReplacementAllowedWithNoInstances(t *testing.T) {
+ fx, token, _ := fskFixture(t, "code-fsk-no-instance")
+ fskPlaceShop(t, fx, token, "home")
+ pubA, fpA := fskKey(t)
+ pubB, fpB := fskKey(t)
+ fskRegister(t, fx, token, pubA)
+ // Other apps' records do not block this fleet's key replacement.
+ if err := provision.CreateRecord(context.Background(), fx.rel, provision.Record{Schema: 1, Account: fx.sqid, App: "kass", Host: "one.kass.example.com", Channel: "stable", CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
+ fskRegister(t, fx, token, pubB)
+ if row := fskFleetRow(t, fx, "home"); row.SecretsKeyFP != fpB || row.SecretsPub != pubB {
+ t.Fatalf("row = %+v, want key B", row)
+ }
+ if fps := fskOwnerFPs(t, fx); strings.Join(fps, ",") != fpA+","+fpB {
+ t.Fatalf("owner fingerprints = %v, want A then B", fps)
+ }
+}
+
+func TestFleetKeyReplacementRefusedWhenARecordCannotBeRead(t *testing.T) {
+ fx, token, _ := fskFixture(t, "code-fsk-corrupt-instance")
+ fskPlaceShop(t, fx, token, "home")
+ pubA, fpA := fskKey(t)
+ pubB, _ := fskKey(t)
+ fskRegister(t, fx, token, pubA)
+ if _, err := fx.rel.Put(context.Background(), provision.RecordKey(fx.sqid, "shop", ltOne), []byte("not a record"), ""); err != nil {
+ t.Fatal(err)
+ }
+ status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pubB}, token)
+ if status != http.StatusConflict || body["error"] != fskInstanceRefusal("shop") {
+ t.Fatalf("replacement with malformed record = %d %v, want 409 naming shop", status, body)
+ }
+ if row := fskFleetRow(t, fx, "home"); row.SecretsKeyFP != fpA {
+ t.Fatalf("refusal changed key: %+v", row)
+ }
+}
+
+type fskRecordsFailStore struct {
+ release.Store
+ prefix string
+}
+
+func (s fskRecordsFailStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if prefix == s.prefix {
+ return nil, os.ErrPermission
+ }
+ return s.Store.List(ctx, prefix)
+}
+
+func TestFleetKeyReplacementFailsClosedOnRecordStoreError(t *testing.T) {
+ for _, failure := range []string{"list", "get"} {
+ t.Run(failure, func(t *testing.T) {
+ fx, token, spy := fskFixture(t, "code-fsk-instance-error")
+ fskPlaceShop(t, fx, token, "home")
+ pubA, _ := fskKey(t)
+ pubB, _ := fskKey(t)
+ fskRegister(t, fx, token, pubA)
+ legacyRecord(t, fx.rel, ltOne, "stable")
+ before := fskFleetRow(t, fx, "home")
+ if failure == "list" {
+ fx.srv.cfg.Releases = fskRecordsFailStore{Store: spy, prefix: provision.RecordsPrefix(fx.sqid, "shop")}
+ } else {
+ st := &ltStore{Store: spy}
+ st.setHook(failNth("get", provision.RecordKey(fx.sqid, "shop", ltOne), 1, true))
+ fx.srv.cfg.Releases = st
+ }
+ spy.reset()
+ status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pubB}, token)
+ want := fmt.Sprintf("the key was not recorded for home and nothing was changed. run carlos fleets secrets-key home %s again", pubB)
+ if status != http.StatusBadGateway || body["error"] != want {
+ t.Errorf("record %s error = %d %v, want 502 %q", failure, status, body, want)
+ }
+ if row := fskFleetRow(t, fx, "home"); row != before {
+ t.Errorf("store error changed row: %+v", row)
+ }
+ if _, puts := spy.counts(); puts != 0 {
+ t.Errorf("store error made %d owner record writes", puts)
+ }
+ })
+ }
+}
+
+func TestFleetKeyFirstRegistrationWithAnInstanceIsAllowed(t *testing.T) {
+ fx, token, _ := fskFixture(t, "code-fsk-first-instance")
+ fskPlaceShop(t, fx, token, "home")
+ legacyRecord(t, fx.rel, ltOne, "stable")
+ pub, _ := fskKey(t)
+ fskRegister(t, fx, token, pub)
+ // Re-registering the same key remains a no-op, even with instances.
+ if status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pub}, token); status != http.StatusOK || body["changed"] != false {
+ t.Fatalf("same key with an instance = %d %v", status, body)
+ }
+}
+
func TestFleetSecretsKeyFailedReplacementKeepsTheOldFingerprintListed(t *testing.T) {
fx, token, _ := fskFixture(t, "code-fsk-failed-replace")
bob := fskAway(t, fx)
diff --git a/internal/console/lifetimes_audit_test.go b/internal/console/lifetimes_audit_test.go
index bd8bba95a..329989076 100644
--- a/internal/console/lifetimes_audit_test.go
+++ b/internal/console/lifetimes_audit_test.go
@@ -102,6 +102,9 @@ func TestNoUnjudgedRecordReads(t *testing.T) {
// unjudgedReadPermitted is the pinned allowlist: the only functions, by
// resolved symbol, in which a forbidden read may appear, each with why.
var unjudgedReadPermitted = map[string]string{
+ // Fleet key replacement blocks on every record, including stale or
+ // unreadable bodies: lifetime validity cannot prove an escrow is absent.
+ "(*github.com/carlosframework/platform/internal/console.Server).fleetHasInstances": "conservative presence check under the account lock, never treats an unjudged record as absent",
// The judged readers themselves: under a nil judge each delegates to its
// unjudged sibling, which is the claims-on behaviour.
"github.com/carlosframework/platform/internal/provision.ReadRecordJudged": "judged reader; a nil judge is GetRecordETag",
diff --git a/internal/console/lifetimes_create_test.go b/internal/console/lifetimes_create_test.go
index d693cbcb5..b95724951 100644
--- a/internal/console/lifetimes_create_test.go
+++ b/internal/console/lifetimes_create_test.go
@@ -739,14 +739,6 @@ func TestTwoAppsCreatingOneHostnameSerialise(t *testing.T) {
enableInstances(t, l.fx, "shop2", provision.Manifest{Schema: 1, App: "shop2", Domain: "shop.example.com", Channel: "stable"})
gate, hook := pauseNth(t, "put", provision.HostIncarnationKey(ltOne), 1)
l.bucket.setHook(hook)
- var waiting atomic.Int32
- h := func(kind, key, event string) {
- if kind == "host" && key == ltOne && event == lockWaiting {
- waiting.Add(1)
- }
- }
- lifetimeLockHook.Store(&h)
- t.Cleanup(func() { lifetimeLockHook.Store(nil) })
first := make(chan int, 1)
go func() { code, _ := l.create(t, ltOne); first <- code }()
@@ -756,17 +748,13 @@ func TestTwoAppsCreatingOneHostnameSerialise(t *testing.T) {
code, _, body := rawReq(t, http.MethodPost, instancesURL(l.fx, "bab", "shop2"), l.member, `{"host":"`+ltOne+`"}`)
second <- fmt.Sprintf("%d %s", code, ltErr(body))
}()
- deadline := time.Now().Add(10 * time.Second)
- for waiting.Load() < 2 && time.Now().Before(deadline) {
- time.Sleep(5 * time.Millisecond)
- }
- if waiting.Load() < 2 {
- t.Fatal("shop2's create never waited on the hostname")
- }
+ // Instance creates now take the account lock before the app and host
+ // locks, even without plans. Shop2 queues there while shop writes its slot.
+ waitForWaiter(t, &l.fx.srv.acctLocks, l.fx.sqid)
select {
case got := <-second:
- t.Fatalf("shop2's create answered %s while shop held the hostname", got)
- case <-time.After(50 * time.Millisecond):
+ t.Fatalf("shop2's create answered %s while shop held the account lock", got)
+ default:
}
gate.open()
if code := <-first; code != http.StatusCreated {
diff --git a/internal/console/lifetimes_recovery.go b/internal/console/lifetimes_recovery.go
index 879f9f922..bcac474b0 100644
--- a/internal/console/lifetimes_recovery.go
+++ b/internal/console/lifetimes_recovery.go
@@ -77,10 +77,14 @@ func (s *Server) recoverLifetimes(ctx context.Context) error {
}
for _, a := range allocs {
a := a
+ // A recovered record and a fleet key replacement share the account
+ // lock, taken before the app and hostname locks as at the create door.
+ unlock := s.lockAccount(a.Account)
_ = s.withAppHost(a.Account, a.App, a.Host, func() error {
s.recoverAllocationLocked(ctx, a)
return nil
})
+ unlock()
}
migs, err := s.store.PendingMigrations()
if err != nil {
diff --git a/internal/console/recordcreators_guard_test.go b/internal/console/recordcreators_guard_test.go
new file mode 100644
index 000000000..fb65f08a0
--- /dev/null
+++ b/internal/console/recordcreators_guard_test.go
@@ -0,0 +1,143 @@
+package console
+
+import (
+ "go/ast"
+ "go/types"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "golang.org/x/tools/go/packages"
+)
+
+// Pin every production entry to the record creators, including function
+// values and aliased imports. The race witnesses exercise the account
+// lock at the create door and recovery loop. Attach writes only static
+// records, purge cancels trashed allocations, and replicas have no caller.
+func TestEveryInstanceRecordCreatorIsUnderTheAccountLock(t *testing.T) {
+ const module = "github.com/carlosframework/platform"
+ const pv = module + "/internal/provision."
+ const server = "(*" + module + "/internal/console.Server)."
+ allowed := map[string]map[string]int{
+ pv + "CreateRecord": {
+ server + "createRecordMarked": 1,
+ server + "attachDomainAs": 1, // Kind static, no escrow
+ pv + "CreateRecordReplica": 1, // no production caller
+ },
+ pv + "CreateRecordReplica": {},
+ server + "createRecordLocked": {}, // none today
+ server + "createRecordMarked": {
+ server + "handleAPIInstanceCreate": 1,
+ server + "createSeedRecord": 1,
+ },
+ server + "createRecordWithLifetime": {
+ server + "handleAPIInstanceCreate": 1,
+ server + "createSeedRecord": 1,
+ },
+ server + "createRecordWithLifetimeLocked": {
+ server + "createRecordWithLifetime": 1,
+ server + "attachFirstRouteLocked": 1, // Kind static, no escrow
+ },
+ server + "allocRecordLocked": {
+ server + "createRecordWithLifetimeLocked": 1,
+ server + "recoverAllocationLocked": 2, // recovery loop or trashed purge
+ },
+ server + "finishClaimCreate": {
+ server + "handleAPIInstanceCreate": 1,
+ server + "handleAPISidecarCreate": 1, // sidecar record, no instance escrow
+ },
+ server + "recoverAllocationLocked": {
+ server + "recoverLifetimes": 1,
+ server + "purgeHostLocked": 1, // trashed app, pinned by TestPurgeRecoveryWritesNoRecord
+ },
+ }
+ root := sgRoot(t)
+ fixture := filepath.Join(root, "internal", "console", "zz_record_creators_fixture.go")
+ cfg := &packages.Config{Dir: root, Env: sgEnv(),
+ Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax |
+ packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports,
+ Overlay: map[string][]byte{fixture: []byte(`package console
+import (
+ "context"
+ p "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+func unguardedCreator(ctx context.Context, st release.Store, rec p.Record) error {
+ return p.CreateRecord(ctx, st, rec)
+}
+var unguardedCreatorValue = p.CreateRecord
+var unguardedReplicaValue = p.CreateRecordReplica
+`)}}
+ pkgs, err := packages.Load(cfg, "./...")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if packages.PrintErrors(pkgs) > 0 {
+ t.Fatal("loading record creators failed")
+ }
+ seen := map[string]map[string]int{}
+ var negative []string
+ for _, pkg := range pkgs {
+ for _, file := range pkg.Syntax {
+ for _, decl := range file.Decls {
+ enclosing := "package level"
+ if fn, ok := decl.(*ast.FuncDecl); ok {
+ obj, ok := pkg.TypesInfo.Defs[fn.Name].(*types.Func)
+ if !ok {
+ t.Fatalf("could not resolve %s", fn.Name)
+ }
+ enclosing = obj.FullName()
+ }
+ ast.Inspect(decl, func(n ast.Node) bool {
+ id, ok := n.(*ast.Ident)
+ if !ok {
+ return true
+ }
+ fn, ok := pkg.TypesInfo.Uses[id].(*types.Func)
+ if !ok {
+ return true
+ }
+ target := fn.FullName()
+ callers, guarded := allowed[target]
+ if !guarded {
+ return true
+ }
+ pos := pkg.Fset.Position(id.Pos())
+ if pos.Filename == fixture {
+ if callers[enclosing] != 0 {
+ t.Errorf("negative fixture was allowed: %s -> %s", enclosing, target)
+ }
+ negative = append(negative, enclosing+" -> "+target)
+ return true
+ }
+ if seen[target] == nil {
+ seen[target] = map[string]int{}
+ }
+ seen[target][enclosing]++
+ if callers[enclosing] == 0 {
+ t.Errorf("%s: record creator outside the lock table: %s -> %s", pos, enclosing, target)
+ }
+ return true
+ })
+ }
+ }
+ }
+ for target, callers := range allowed {
+ for caller, want := range callers {
+ if got := seen[target][caller]; got != want {
+ t.Errorf("%s -> %s: %d references, want %d; update the lock table only after checking the account lock", caller, target, got, want)
+ }
+ }
+ }
+ wantNegative := []string{
+ module + "/internal/console.unguardedCreator -> " + pv + "CreateRecord",
+ "package level -> " + pv + "CreateRecord",
+ "package level -> " + pv + "CreateRecordReplica",
+ }
+ slices.Sort(negative)
+ slices.Sort(wantNegative)
+ if !slices.Equal(negative, wantNegative) {
+ t.Fatalf("negative fixtures = %s, want %s", strings.Join(negative, "\n"), strings.Join(wantNegative, "\n"))
+ }
+}