carlos / platform Public

durability 3a: retain fleet keys for trashed apps

Count retained trash rows in the instance and sealed-value replacement
checks without changing live app listings. Use a bounded key-only record
listing, restore the cross-account hostname witness, and guard the full
seed/import caller chain. Inventory the new RecordsPrefix key site.

Add the required box-key reseal witness. It currently fails: a sweep keeps
the A-sealed escrow after EscrowKey changes to B. Leave production escrow
semantics unchanged per the controller; Task 6 remains blocked on I2.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev bf1f67fe9150945a1d118a9c8b8af4972fda4e37 parent 984fadb
8 files changed, +260 −24
  • internal/activator/escrow_test.go +28 −0
  • internal/console/fleetsecretskey.go +27 −9
  • internal/console/fleetsecretskey_test.go +153 −3
  • internal/console/lifetimes_audit_test.go +0 −3
  • internal/console/lifetimes_create_test.go +13 −8
  • internal/console/recordcreators_guard_test.go +14 −0
  • internal/console/store.go +19 −0
  • internal/provision/durability_3a_escrow_census_test.go +6 −1

Intent

Human

<task-notification> <task-id>a1d45ad92bc2e0b62</task-id> <tool-use-id>toolu_014wbTMWutVAc61F3nZnozbx</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/aab63774-dfe6-44a4-9cd9-230e6f4c3d13/tasks/a1d45ad92bc2e0b62.output</output-file> <status>completed</status> <summary>Agent "Review durability 3a Task 7" 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>**Task quality: Needs fixes.** The guard is careful and mostly sound, and the implementer's concern resolves the opposite way from how it was raised. The `host+"/"+x` mapping is the sound form. The literal form the brief asks for, `Of(l, host, x)` followed by `Stage(x)`, is the one that lets a secret through, and clean.go marks it as passing. The refusal branch can also be bypassed by reassigning the root after the check. The report is also saved at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/durability-3a/.superpowers/sdd/2026-10-30-durability-step3-escrow-fence-restore/task-7-review-opus.md`. ### Spec Compliance - **Staging set:** Publisher and Prepared `Stage`/`StagePlatform`, `Publisher.StageSealed`, and `SyncDir`/`SyncDirAt`/`Seed`/`Publish`/`Run` are all recognised (`direct`, publication_guard_test.go:97). Argument indices are correct for each one, and method expressions get offset 1. - **Interface dispatch:** `types.Implements` against both publisher types covers local interfaces and `hostfiles.PlatformStager`. An interface that embeds `PlatformStager` resolves to the embedded method's Func, so it is caught too. - **PlatformRelay:** the Name is checked in composites, assignments, zero values from `var` and `new`, and `&amp;r.Name` escapes. Matches the brief. - **Callable aliases:** these resolve to a fixed point. Mixed assignments, nil assignments, function-typed parameters and unbound escapes (return, slice, `any`, variadic) are reported. Matches the brief, with stricter handling than it asks for. - **Stage rule:** the path must be a single-definition local (`&amp;x` and closure writes count as extra writes), checked by a terminating `!= App` mismatch. The check must come first in the same or an enclosing block, with a go/cfg reachability check from the entry and from the then-branch. Matches. - **Deviation:** the implementer also accepts `Of(l, host, host+"/"+x)` (classifiedPath, :582). Judged in I1. It is the correct form, not a loosening. - **StagePlatform and StageSealed:** StagePlatform takes only the `WakeItem`/`AdoptionItem` const objects. StageSealed is typed, so that check is a tautology the compiler already enforces, which is fine. - **Sync family:** accepted are a FilesDirSkip call, a variable or field every module write to which is a FilesDirSkip call, or an error-checked dominating `RefuseSecretsAt` on the same local root. Matches, but see I2 for how "no assignment between" is read. - **No site list, no exemptions:** only package hostfiles itself is trusted, which matches "outside package hostfiles". - **Fixtures:** all nine exist and are asserted by function name and rule prefix (:868). Extra cases are inside them. - **Step 2 mutation:** ⚠️ not re-run, taken from the report only. The report says removing the check in buildPrepared makes the test FAIL naming `host.buildPrepared`. The CFG successor order is indirectly proven by `zzCleanBreak` passing, because it would fail if `Succs[0]` were not the then-branch. - **Production call sites:** I grepped every non-test, non-hostfiles `.go` file at HEAD for `.Stage(`, `.StagePlatform(`, `.StageSealed(`, the five functions, `PlatformRelay` and `PlatformStager`. The only hostfiles staging sites are: - activator escrow.go:812 and hafiles.go:539 (StageSealed) - hafiles.go:57/511 (the `syncFilesAt` alias plus `f.skip`, whose only write is `newHostFiles` hafiles.go:197) - host movesfiles.go:329/338, claimfilesseed_stage.go:149 and relocationflush.go:100/139 The console `.Stage(` hits are a GeoIP type, not hostfiles. I found no struct embedding `*hostfiles.Publisher` or `*hostfiles.Prepared` and no local stager interface. Every site is one the guard sees. ### Strengths - Path single-assignment is robust: `&amp;x`, closure writes and `:=` redeclarations all add writes. Loops and closures therefore cannot change a checked Stage path. - Dominance uses a real CFG (go/cfg) on top of the textual "same or enclosing block" rule. Goto, ineffective break and labelled exits are covered, and fixtures prove each one. - Callable escapes fail closed (`!g.bound[e]`, :818). Generic instantiation of a staging callback lands in "unknown callable parameter" instead of vanishing. - Fixtures prove the guard can fail. The `packages.PrintErrors` fatal plus fixtures that import hostfiles make a vacuous pass (renamed package or types) impossible. iface.go requires two distinct diagnostics. ### Issues #### Critical None. #### Important **I1 (plan-mandated): the guard accepts `Of(l, host, x)` with no mapping before `Stage(x)`, which is fail-open for the trio. clean.go marks this as clean.** - **Where:** publication_guard_test.go:585 (`publicationObject(info, c.Args[2]) == obj` returns true with no further check). clean.go:14, :55 and :83 are positive cases of it. - **Why:** both `Publisher.Stage` and `Prepared.Stage` take files-directory-relative paths. That is the coordinate FilesDirSkip exists for: `Of(l, host, host+"/"+rel)` (pubclass.go:177-181). Of classifies inventory-relative paths. - Take a files-relative `x = "instance.key"` or `"report.token"` under `Nested`. Rules 1-7 of `Of` do not match: not a fixed shape, not `host+"/instance.key"`, not a nested platform name, no `host.` or `.` prefix, first element is not host. Rule 8 then returns **App**. - So `if pubclass.Of(pubclass.Nested, host, rel, false) != pubclass.App { return }; p.Stage(ctx, rel, ...)` passes the guard and publishes instance.key or report.token raw. - That is a natural mistake (classify the name you are about to stage), and it is exactly what the guard exists to catch. - No production site uses the unmapped form today. buildPrepared, the only production `Stage`, uses the mapped form. So this is a hole in the guard, not a live leak. - **On the implementer's concern:** accepting `host+"/"+x` is sound. - It is FilesDirSkip's own mapping. - The guard requires the same host object as Of's host argument, a constant `"/"` and a single, preceding definition of host, and checks it at :590-601. - The mapping cannot let an unclassified path through, because Of's `clean` turns any `..`, empty or absolute result into Never. - Every hostfiles manifest is files-relative, so this is the form that matches what is staged. - **Fix (needs a controller ruling against the brief's literal text):** - Accept only the mapped form for `Stage`, or something equivalent such as `pubclass.FilesDirSkip(l, host)(x, isDir)` being false. - Rewrite clean.go's three unmapped cases to use the mapped form. - Add a fixture in which an unmapped `Of(pubclass.Nested, host, x, false)` followed by `Stage(x)` is reported. - Production needs no change. **I2: the refusal branch's "not assigned between" is checked by source position, so a loop, a closure or a pointer can reassign the root after the refusal.** - **Where:** publication_guard_test.go:660 (`unchanged`), used by `refused` (:632). - **Why:** `unchanged` only counts writes whose position lies between the refusal call and the operation. That misses three cases, and each passes with a nil skip: - `root = other` placed after the Seed inside a loop (a back edge). The second iteration seeds an unrefused tree. - A closure `reset := func(){ root = other }` written before the refusal and called after it. - `pr := &amp;root` taken before the refusal, then `*pr = other`. The `&amp;` write sits before the refusal, and the `*pr` write is not recorded at all. - **Context:** the Stage rule closes all three by requiring a single definition. The refusal rule dropped that on purpose (report: "Root initialization before the refusal is allowed") because claimfilesseed_stage.go assigns `root` inside a `work.With` closure. Nothing in production exploits this today, but it is a bypass of a stated rule. - **Fix:** - Give the refusal root the same single-definition rule as the path (`singleLocal`). - In claimfilesseed_stage.go, bind the opened descriptor once after the `work.With` block (`dir := root`) and refuse and seed `dir`. relocationflush.go's `root, err :=` already passes that rule. - Alternatively, reject any write to the root from another unit, any address-taken write, and any write reachable in the CFG from the refusal back to the call. #### Minor - **M1 Fixture assertions are loose.** publication_guard_test.go:888 never checks that `remaining` is empty, and it matches by function name and rule prefix without line numbers. - A false positive on a passing case inside a failing-fixture file goes unnoticed. - In zzUnclassified, a guard that flagged the classified first Stage instead of the second would still pass that subtest. clean.go's zzClean largely covers this second case. - Fix: assert `remaining` is empty, or assert lines. - **M2 Interface dispatch through a type that embeds a publisher is not seen.** - Take `type w struct{ *hostfiles.Publisher; ... }` behind a fresh interface `{ StagePlatform(...); Other() }`. `*Publisher` does not implement that interface, so `direct` (:97) misses the call, and the promoted method has no call site the guard can check. - My grep found no such embedding in production. - Fix if cheap: also test `types.Implements` for named types in the module that embed a publisher, or report any embedding of `*hostfiles.Publisher` or `*hostfiles.Prepared` outside hostfiles. - **M3 zeroFields (:234) only looks one level deep.** - A struct that holds a skip-bearing struct or a PlatformRelay by value, created zero (`outer{}`, `var o outer`), records no nil write for the inner func field or Name. A nil skip or empty relay Name then passes. - No production instance exists: `hostFiles` is always a pointer and no relay is built outside hostfiles. - Fix: recurse into value-typed struct fields. - **M4 (plan-mandated) Root, layout and host are not tied to the publisher.** - `FilesDirSkip(l, host)` is accepted whatever root the sync uses. If a sync were rooted at the instance directory, `shop.example.com.env` would map to `shop.example.com/shop.example.com.env`, which Of calls App, so it would publish the raw env. - The same applies to Of's and RefuseSecretsAt's host and layout arguments. - The brief's rules do not ask for this and a static guard cannot easily check it. Note it for the branch review, perhaps as a runtime assertion inside `SyncDirAt` and `Seed` that the root's base name is the host. - **M5 Size.** publication_guard_test.go is 902 lines in a single file, all on one concern. Acceptable, but splitting the collector and the checks would help the next reader. - ⚠️ **Not re-verified:** the mutation RED run, the race run, the cross-builds and the census-card result. These come from the report only. ### Assessment **Task quality: Needs fixes.** The guard does find every production staging site, and accepting the `host+"/"+x` mapping is correct and should be ruled accepted. But the brief's literal unmapped `Of(l, host, x)` form, which clean.go marks as clean, accepts a files-relative `instance.key` or `report.token` as App (I1). The refusal branch can also be bypassed by reassigning the root through a loop, a closure or a pointer (I2). Both are small fixes inside the test file, plus a one-line rebind in claimfilesseed_stage.go for I2.</result> <usage><subagent_tokens>125570</subagent_tokens><tool_uses>22</tool_uses><duration_ms>470717</duration_ms></usage> </task-notification>

Attributed to this commit: 10.3 g CO₂e (1,150,171 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/activator/escrow_test.go b/internal/activator/escrow_test.go
index e6a63d704..3f81b2c47 100644
--- a/internal/activator/escrow_test.go
+++ b/internal/activator/escrow_test.go
@@ -1100,6 +1100,34 @@ func TestAFleetBoxSealsToItsOwnKey(t *testing.T) {
}
}
+func TestABoxThatChangesKeyResealsItsEscrow(t *testing.T) {
+ ctx := context.Background()
+ b, rt := escrowBackend(t, escrowHost)
+ keyA, keyB := testEscrowKey(t), testEscrowKey(t)
+ b.EscrowKey = keyA
+ writeEnv(t, b, rt, envA)
+ mustPublish(t, b, rt)
+ sealA := sealerOf(t, b, rt)
+ before := loadManifest(t, b, rt)
+ prefix := b.filesPrefix(rt.Host)
+ if plain, err := hostfiles.ReadSealed(ctx, b.FilesStore, prefix, before, hostfiles.SealedEnvItem, nil, sealA); err != nil || string(plain) != envA {
+ t.Fatalf("initial escrow with A = %q, %v", plain, err)
+ }
+ b.EscrowKey = keyB
+ sealB := sealerOf(t, b, rt)
+ rep := b.EscrowSweep(ctx, []registry.Route{rt})
+ if rep.Published != 1 || len(rep.Failing) != 0 {
+ t.Errorf("key-change sweep = %+v, want one publish", rep)
+ }
+ after := loadManifest(t, b, rt)
+ if plain, err := hostfiles.ReadSealed(ctx, b.FilesStore, prefix, after, hostfiles.SealedEnvItem, nil, sealB); err != nil || string(plain) != envA {
+ t.Errorf("escrow after key change with B = %q, %v", plain, err)
+ }
+ if _, err := hostfiles.ReadSealed(ctx, b.FilesStore, prefix, after, hostfiles.SealedEnvItem, nil, sealA); err == nil {
+ t.Error("key A still opens the escrow after the sweep")
+ }
+}
+
// holdLease takes rt's instance lease on b through the production Acquire,
// as a wake does before it prepares, and gives it back when the test ends
// or when the returned func is called.
diff --git a/internal/console/fleetsecretskey.go b/internal/console/fleetsecretskey.go
index 23ba0b018..51d6d04f4 100644
--- a/internal/console/fleetsecretskey.go
+++ b/internal/console/fleetsecretskey.go
@@ -28,7 +28,6 @@ import (
"errors"
"fmt"
"log"
- "math"
"net/http"
"sort"
"strings"
@@ -40,6 +39,7 @@ import (
"github.com/carlosframework/platform/internal/objstore"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
)
// fleetSecretsKeyTimeout bounds the door's bucket work: the sealed-value
@@ -183,11 +183,12 @@ func (s *Server) handleAPIFleetSecretsKey(w http.ResponseWriter, r *http.Request
}
// fleetHasInstances lists, sorted, the fleet's placed apps that have any
-// instance record, or any record that cannot be read: their instances'
+// instance key, including one whose body 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.
+// for the escrows themselves. Includes trash until purged. Called under
+// the account lock; lists at most one key per app when the store supports it.
func (s *Server) fleetHasInstances(ctx context.Context, acct *Account, fleet string) ([]string, error) {
- apps, err := s.fleetPlacedApps(acct, fleet)
+ apps, err := s.fleetPlacedAppsIn(acct, fleet, true)
if err != nil {
return nil, err
}
@@ -196,11 +197,17 @@ func (s *Server) fleetHasInstances(ctx context.Context, acct *Account, fleet str
}
var out []string
for _, app := range apps {
- recs, unreadable, err := provision.ListRecordsStrict(ctx, s.cfg.Releases, acct.Sqid, app, math.MaxInt)
+ prefix := provision.RecordsPrefix(acct.Sqid, app)
+ var keys []string
+ if pages, ok := s.cfg.Releases.(release.PageLister); ok {
+ keys, err = pages.ListPage(ctx, prefix, "", 1)
+ } else {
+ keys, err = s.cfg.Releases.List(ctx, prefix)
+ }
if err != nil {
return nil, err
}
- if len(recs) > 0 || len(unreadable) > 0 {
+ if len(keys) > 0 {
out = append(out, app)
}
}
@@ -209,9 +216,10 @@ func (s *Server) fleetHasInstances(ctx context.Context, acct *Account, fleet str
// 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).
+// value with no sealed_to may still be sealed to the current key). Includes
+// trash until purged, since restore retains those same sealed values.
func (s *Server) fleetHasSealedValues(ctx context.Context, acct *Account, fleet string) ([]string, error) {
- apps, err := s.fleetPlacedApps(acct, fleet)
+ apps, err := s.fleetPlacedAppsIn(acct, fleet, true)
if err != nil {
return nil, err
}
@@ -351,7 +359,17 @@ func (s *Server) staleForTarget(ctx context.Context, acct *Account, app, target
// routes for an app placed before the column existed (one route listing for
// all of them).
func (s *Server) fleetPlacedApps(acct *Account, fleet string) ([]string, error) {
- apps, err := s.store.AppsIn(acct.ID)
+ return s.fleetPlacedAppsIn(acct, fleet, false)
+}
+
+func (s *Server) fleetPlacedAppsIn(acct *Account, fleet string, includeTrash bool) ([]string, error) {
+ var apps []string
+ var err error
+ if includeTrash {
+ apps, err = s.store.AppsIncludingTrashIn(acct.ID)
+ } else {
+ apps, err = s.store.AppsIn(acct.ID)
+ }
if err != nil {
return nil, err
}
diff --git a/internal/console/fleetsecretskey_test.go b/internal/console/fleetsecretskey_test.go
index 858ebb985..87336926b 100644
--- a/internal/console/fleetsecretskey_test.go
+++ b/internal/console/fleetsecretskey_test.go
@@ -15,6 +15,7 @@ import (
"fmt"
"net/http"
"os"
+ "slices"
"strings"
"testing"
"time"
@@ -441,7 +442,7 @@ 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) {
+func fskEscrow(t *testing.T, fx *consoleFixture, privateKey string) *hostfiles.ItemSealer {
t.Helper()
ctx := context.Background()
priv, err := appconfig.ParsePrivateKey(privateKey, "test")
@@ -474,6 +475,7 @@ func fskEscrow(t *testing.T, fx *consoleFixture, privateKey string) {
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)
}
+ return seal
}
func TestFleetKeyReplacementRefusedWhileAnInstanceIsPlaced(t *testing.T) {
@@ -516,6 +518,102 @@ func TestFleetKeyReplacementRefusedWhileAnInstanceIsPlaced(t *testing.T) {
}
}
+func TestFleetKeyReplacementRefusedWhileATrashedAppRetainsSecrets(t *testing.T) {
+ for _, kind := range []string{"instance", "sealed values"} {
+ t.Run(kind, func(t *testing.T) {
+ fx, token, spy := fskFixture(t, "code-fsk-trash")
+ fskPlaceShop(t, fx, token, "home")
+ privA, pubA, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ pubB, _ := fskKey(t)
+ fskRegister(t, fx, token, pubA)
+ want := fskInstanceRefusal("shop")
+ var seal *hostfiles.ItemSealer
+ if kind == "instance" {
+ legacyRecord(t, fx.rel, ltOne, "stable")
+ seal = fskEscrow(t, fx, privA)
+ } else {
+ pub, err := appconfig.ParsePublicKey(pubA, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ envelope, err := appconfig.Seal(pub, appconfig.Binding{Account: fx.sqid, App: "shop"}, []byte("value"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ fp, err := appconfig.PublicFingerprint(pubA)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": {Kind: "secret", Envelope: envelope, SealedTo: fp}})
+ want = "home already has a different secrets key, and these apps hold sealed values: shop. replacing the key would leave them unreadable. unset each app's secrets with carlos secrets unset --app <app> <var>, then run this again"
+ }
+ base := fx.ts.URL + "/api/cli/apps/" + fx.sqid + "/shop"
+ if status, body := postJSON(t, base+"/delete", map[string]string{}, token); status != http.StatusOK {
+ t.Fatalf("trash = %d %v", status, body)
+ }
+ live, err := fx.st.AppsIn(OpsAccountID)
+ if err != nil || slices.Contains(live, "shop") {
+ t.Fatalf("live apps = %v, %v", live, err)
+ }
+ before := fskFleetRow(t, fx, "home")
+ ownerKey := release.FleetOwnerKey(fx.sqid, "home")
+ owner, _, 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"] != want {
+ t.Errorf("replacement = %d %v, want 409 %q", status, body, want)
+ }
+ if row := fskFleetRow(t, fx, "home"); row != before {
+ t.Errorf("refusal changed row: %+v", row)
+ }
+ after, _, err := fx.rel.Get(context.Background(), ownerKey)
+ if err != nil || string(after) != string(owner) {
+ t.Errorf("refusal changed owner record: %s, %v", after, err)
+ }
+ if _, puts := spy.counts(); puts != 0 {
+ t.Errorf("refusal made %d owner writes", puts)
+ }
+ if status, body := postJSON(t, base+"/restore", map[string]string{}, token); status != http.StatusOK {
+ t.Fatalf("restore = %d %v", status, body)
+ }
+ if row := fskFleetRow(t, fx, "home"); row != before {
+ t.Errorf("restored app has a different fleet key: %+v", row)
+ }
+ if kind == "instance" {
+ if rec, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "shop", ltOne); err != nil || rec == nil {
+ t.Fatalf("restored record = %+v, %v", rec, err)
+ }
+ prefix := ltOne + "/files/0/"
+ m, found, err := hostfiles.Load(context.Background(), fx.rel, prefix)
+ if err != nil || !found {
+ t.Fatalf("restored escrow manifest: %v, %v", found, err)
+ }
+ if plain, err := hostfiles.ReadSealed(context.Background(), fx.rel, prefix, m, "instance.key.sealed", nil, seal); err != nil || string(plain) != "instance-secret" {
+ t.Errorf("restored escrow with A = %q, %v", plain, err)
+ }
+ } else {
+ m, err := appconfig.Get(context.Background(), fx.rel, fx.sqid, "shop")
+ if err != nil || m == nil {
+ t.Fatalf("restored bundle = %+v, %v", m, err)
+ }
+ priv, err := appconfig.ParsePrivateKey(privA, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if plain, err := appconfig.Open(priv, appconfig.Binding{Account: fx.sqid, App: "shop"}, m.Vars["API_KEY"].Envelope); err != nil || string(plain) != "value" {
+ t.Errorf("restored sealed value with A = %q, %v", plain, err)
+ }
+ }
+ })
+ }
+}
+
func TestFleetKeyReplacementNamesEveryPlacedAppSorted(t *testing.T) {
fx, token, _ := fskFixture(t, "code-fsk-sorted-instances")
pubA, _ := fskKey(t)
@@ -605,9 +703,21 @@ func TestFleetKeyReplacementFailsClosedOnRecordStoreError(t *testing.T) {
}
spy.reset()
status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pubB}, token)
+ wantStatus := http.StatusBadGateway
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 failure == "get" {
+ wantStatus, want = http.StatusConflict, fskInstanceRefusal("shop")
+ st := fx.srv.cfg.Releases.(*ltStore)
+ st.mu.Lock()
+ for _, op := range st.ops {
+ if strings.HasPrefix(op, "get "+provision.RecordsPrefix(fx.sqid, "shop")) {
+ t.Errorf("instance check fetched a body: %s", op)
+ }
+ }
+ st.mu.Unlock()
+ }
+ if status != wantStatus || body["error"] != want {
+ t.Errorf("record %s error = %d %v, want %d %q", failure, status, body, wantStatus, want)
}
if row := fskFleetRow(t, fx, "home"); row != before {
t.Errorf("store error changed row: %+v", row)
@@ -759,3 +869,43 @@ func TestFleetBYOPageNamesTheSecretsKey(t *testing.T) {
}
}
}
+
+type fskOneKeyStore struct {
+ release.Store
+ prefix string
+ pages int
+}
+
+func (s *fskOneKeyStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if prefix == s.prefix {
+ return nil, fmt.Errorf("unbounded instance list")
+ }
+ return s.Store.List(ctx, prefix)
+}
+
+func (s *fskOneKeyStore) ListPage(ctx context.Context, prefix, after string, limit int) ([]string, error) {
+ if prefix == s.prefix {
+ s.pages++
+ if after != "" || limit != 1 {
+ return nil, fmt.Errorf("instance list after=%q limit=%d", after, limit)
+ }
+ return []string{prefix + "unreadable.json"}, nil
+ }
+ return s.Store.List(ctx, prefix)
+}
+
+func TestFleetKeyReplacementListsOnlyOneInstanceKey(t *testing.T) {
+ fx, token, spy := fskFixture(t, "code-fsk-one-key")
+ fskPlaceShop(t, fx, token, "home")
+ pubA, _ := fskKey(t)
+ pubB, _ := fskKey(t)
+ fskRegister(t, fx, token, pubA)
+ st := &fskOneKeyStore{Store: spy, prefix: provision.RecordsPrefix(fx.sqid, "shop")}
+ fx.srv.cfg.Releases = st
+ if status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pubB}, token); status != http.StatusConflict || body["error"] != fskInstanceRefusal("shop") {
+ t.Errorf("replacement = %d %v, want 409", status, body)
+ }
+ if st.pages != 1 {
+ t.Errorf("bounded instance lists = %d, want 1", st.pages)
+ }
+}
diff --git a/internal/console/lifetimes_audit_test.go b/internal/console/lifetimes_audit_test.go
index 329989076..bd8bba95a 100644
--- a/internal/console/lifetimes_audit_test.go
+++ b/internal/console/lifetimes_audit_test.go
@@ -102,9 +102,6 @@ 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 b95724951..c5036b792 100644
--- a/internal/console/lifetimes_create_test.go
+++ b/internal/console/lifetimes_create_test.go
@@ -733,10 +733,16 @@ func TestCreateRefusesWhenTheAccountIsUnknown(t *testing.T) {
func TestTwoAppsCreatingOneHostnameSerialise(t *testing.T) {
l := newLtOn(t)
- if _, err := l.fx.st.CreateAppIn(OpsAccountID, "shop2", "paul@keymail.dev", time.Now()); err != nil {
+ if err := l.fx.st.CreateAccount(42, "cdef", "widgets", "bob@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ bob := cliToken(t, l.fx, "bob@keymail.dev", "code-host-lock-bob")
+ if _, err := l.fx.st.CreateAppIn(42, "shop2", "bob@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.PutManifest(context.Background(), l.fx.rel, "cdef", "shop2", provision.Manifest{Schema: 1, App: "shop2", Domain: "shop.example.com", Channel: "stable"}); err != nil {
t.Fatal(err)
}
- 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)
@@ -745,22 +751,21 @@ func TestTwoAppsCreatingOneHostnameSerialise(t *testing.T) {
waitForSignal(t, gate.entered, "shop's slot write")
second := make(chan string, 1)
go func() {
- code, _, body := rawReq(t, http.MethodPost, instancesURL(l.fx, "bab", "shop2"), l.member, `{"host":"`+ltOne+`"}`)
+ code, _, body := rawReq(t, http.MethodPost, instancesURL(l.fx, "cdef", "shop2"), bob, `{"host":"`+ltOne+`"}`)
second <- fmt.Sprintf("%d %s", code, ltErr(body))
}()
- // 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)
+ // Different accounts reach the shared hostname lock independently.
+ waitForWaiter(t, &l.fx.srv.hostLocks, ltOne)
select {
case got := <-second:
- t.Fatalf("shop2's create answered %s while shop held the account lock", got)
+ t.Fatalf("shop2's create answered %s while shop held the hostname lock", got)
default:
}
gate.open()
if code := <-first; code != http.StatusCreated {
t.Fatalf("shop's create = %d", code)
}
- if got, want := <-second, fmt.Sprintf("%d %s", http.StatusConflict, hostHeldSentence(ltOne, &apexHold{Holder: ltApp})); got != want {
+ if got, want := <-second, fmt.Sprintf("%d %s", http.StatusConflict, hostHeldSentence(ltOne, &apexHold{Holder: ltApp, OtherAccount: l.fx.sqid})); got != want {
t.Fatalf("shop2's create = %q, want %q", got, want)
}
if rows := allocRows(t, l.fx.st, ltOne); len(rows) != 1 || rows[0].App != ltApp {
diff --git a/internal/console/recordcreators_guard_test.go b/internal/console/recordcreators_guard_test.go
index fb65f08a0..73f7ff2ef 100644
--- a/internal/console/recordcreators_guard_test.go
+++ b/internal/console/recordcreators_guard_test.go
@@ -31,6 +31,14 @@ func TestEveryInstanceRecordCreatorIsUnderTheAccountLock(t *testing.T) {
server + "handleAPIInstanceCreate": 1,
server + "createSeedRecord": 1,
},
+ server + "createSeedRecord": {
+ server + "beginFrom": 1,
+ server + "beginImport": 1,
+ },
+ server + "beginFrom": {server + "createFrom": 1},
+ server + "beginImport": {server + "createImport": 1},
+ server + "createFrom": {server + "handleAPIInstanceCreate": 1},
+ server + "createImport": {server + "handleAPIInstanceCreate": 1},
server + "createRecordWithLifetime": {
server + "handleAPIInstanceCreate": 1,
server + "createSeedRecord": 1,
@@ -68,6 +76,9 @@ func unguardedCreator(ctx context.Context, st release.Store, rec p.Record) error
}
var unguardedCreatorValue = p.CreateRecord
var unguardedReplicaValue = p.CreateRecordReplica
+var unguardedSeedValue = (*Server).createSeedRecord
+var unguardedFromValue = (*Server).beginFrom
+var unguardedImportValue = (*Server).beginImport
`)}}
pkgs, err := packages.Load(cfg, "./...")
if err != nil {
@@ -134,6 +145,9 @@ var unguardedReplicaValue = p.CreateRecordReplica
module + "/internal/console.unguardedCreator -> " + pv + "CreateRecord",
"package level -> " + pv + "CreateRecord",
"package level -> " + pv + "CreateRecordReplica",
+ "package level -> " + server + "createSeedRecord",
+ "package level -> " + server + "beginFrom",
+ "package level -> " + server + "beginImport",
}
slices.Sort(negative)
slices.Sort(wantNegative)
diff --git a/internal/console/store.go b/internal/console/store.go
index 3764cc2d7..ed529a1f1 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -1845,6 +1845,25 @@ func (s *Store) AppsIn(accountID int64) ([]string, error) {
return out, rows.Err()
}
+// AppsIncludingTrashIn lists all retained app names in an account, sorted.
+// Purge removes the row; a trashed row still owns its placement and secrets.
+func (s *Store) AppsIncludingTrashIn(accountID int64) ([]string, error) {
+ rows, err := s.db.Query(`SELECT app FROM apps WHERE account_id = ? ORDER BY app`, accountID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []string
+ for rows.Next() {
+ var app string
+ if err := rows.Scan(&app); err != nil {
+ return nil, err
+ }
+ out = append(out, app)
+ }
+ return out, rows.Err()
+}
+
// HasAppIn reports whether an account already claims a LIVE app name.
// Filtered the same way as AppsIn: a trashed name still occupies the row (see
// CreateAppIn / the name-reservation rule) but must read as absent to a caller
diff --git a/internal/provision/durability_3a_escrow_census_test.go b/internal/provision/durability_3a_escrow_census_test.go
index d8979f28d..78ccb3c5f 100644
--- a/internal/provision/durability_3a_escrow_census_test.go
+++ b/internal/provision/durability_3a_escrow_census_test.go
@@ -23,6 +23,9 @@ package provision
// hand it a classification made against the rows it was given. The same
// "instances" literal (the nested run directory's name): still
// key-site, under the new unit name.
+// - internal/console/fleetsecretskey.go Server.fleetHasInstances (Task 6,
+// fix round 1), new key-site: lists one RecordsPrefix key per retained
+// placed app to refuse key replacement. No record body read or write.
func durability3aEscrowWriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), consoleProtectionTabWriteCensusInventory()...)
repins := []censusEntry{
@@ -65,5 +68,7 @@ func durability3aEscrowWriteCensusInventory() []censusEntry {
panic("durability-3a-escrow re-pin of an unlisted unit " + r.File + ":" + r.Unit)
}
}
- return entries
+ return append(entries, censusEntry{
+ "internal/console/fleetsecretskey.go", "Server.fleetHasInstances", "key-site", "key:RecordsPrefix", "1cc1f079e3c2765a10ebcff8e676d8240e41e499bc2e80480ade35e53f24ed4b",
+ })
}