carlos / platform Public

apps place and apps create --place refuse an app whose sealed values its new boxes cannot open (staleForTarget, FSK-C47), place and a placed create run under the account lock, and env fork takes the account lock before the app lock (Task 7)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 924d47f1e609eab3d9af4ee1e899f083640b35cc parent 4abe516
9 files changed, +459 −9
  • approved_fleet_secrets_copy_test.go +2 −2
  • internal/console/apicli.go +12 −1
  • internal/console/apienv.go +10 −0
  • internal/console/fleets.go +28 −0
  • internal/console/fleetsecrets_mint_test.go +6 −4
  • internal/console/fleetsecrets_moves_test.go +316 −0
  • internal/console/fleetsecretskey.go +61 −0
  • internal/console/server.go +23 −0
  • internal/console/teamcreds.go +1 −2

Intent

Human

<task-notification> <task-id>afde850d773aca226</task-id> <tool-use-id>toolu_01NzQgNQSWoExs5NbrvNCqSk</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/afde850d773aca226.output</output-file> <status>completed</status> <summary>Agent "Implement Task 6b: relay, plan storage, guard" 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 (fix round 1 of 5). Both Important issues are fixed. Commit: 4abe5168 (on top of 72fde1a9). 1. Guard: `sealWith` is now guarded and allowed only in `SealBound` and `SealUnbound`. Any read or write of a `Sealer` field outside `NewSealer` and `Sealer`'s own methods is now reported. Two new fixtures (a constructor that fills the fields one by one, and an exported helper calling `sealWith`) failed the guard first, then pass. I also added the review's one-line check that `NewSealer` builds exactly one Sealer. 2. Background walks: the relay reconcile and plan storage now skip quietly only for a keyless fleet, a missing deployment key, or an app with no live row. Any other error, such as a failed store or registry read or `errFleetNotOwned`, fails the job again. Two new tests run each walk as a real job (keyless skipped quietly; read error and fleet-not-owned both fail it). The four failure cases failed before the fix and pass now. A mutation confirms the quiet keyless skip is checked. Tests: the covering run (the guard plus Relay, PlanStorage, Scan, StorageDeny and team-environment relay tests) passes, along with build, vet, gofmt and the darwin, windows and linux/arm64 builds. Concerns: I left the Minor about packages that are entirely excluded on linux (and nested modules), because it needs a walk of the module tree, not a one-line change. The other concerns from the first report still stand. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-secrets-key/.superpowers/sdd/2026-10-29-fleet-secrets-key/task-6b-report.md (section "Fix round 1")</result> <usage><subagent_tokens>369845</subagent_tokens><tool_uses>15</tool_uses><duration_ms>414395</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a787bf52d4c0f0466</task-id> <tool-use-id>toolu_01RMDnBoNCc65Q7VEH1uUreY</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/a787bf52d4c0f0466.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 6b 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>Important 1 (guard bypass from inside appconfig) — ADDRESSED Important 2 (background walks hid real failures) — ADDRESSED New breakage in the fix diff — none Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-secrets-key/.superpowers/sdd/2026-10-29-fleet-secrets-key/task-6b-rereview-1.md</result> <usage><subagent_tokens>67231</subagent_tokens><tool_uses>7</tool_uses><duration_ms>46152</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>ae916787ec6397887</task-id> <tool-use-id>toolu_01PgG8tQ5Any34Mjrv4WqtrV</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/ae916787ec6397887.output</output-file> <status>failed</status> <summary>Agent "Implement Task 7: moves and env fork" failed: Agent terminated early due to an API error: You've hit your session limit · resets 5:20pm (Europe/Dublin) (error type rate_limit, HTTP 429, request id req_011CgWqqdW6b47aQRucfMApo, model sent to the API: claude-sonnet-5-5)</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. This agent's work so far is saved. The limit resets at 5:20pm (Europe/Dublin). Once its requests are accepted again, send the agent a message (SendMessage) to let it continue from where it stopped instead of starting a new agent.</note> <result>Now the copy id, then run broader tests.</result> </task-notification>

Human

continbue

Human

how much left on this track?

Attributed to this commit: 7.59 g CO₂e (949,024 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-fleet-secrets-key, 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/approved_fleet_secrets_copy_test.go b/approved_fleet_secrets_copy_test.go
index a1a9ec6cb..582fd1fdb 100644
--- a/approved_fleet_secrets_copy_test.go
+++ b/approved_fleet_secrets_copy_test.go
@@ -56,7 +56,7 @@ var fleetSecretsCopyStatuses = []string{"pending", "approved", "struck"}
// task that writes a row's text adds its id here in the same commit, once the
// row is approved. Task 3 built the door, BYO page and fleet page rows; Task 4 the CLI rows;
// Task 5 sealKeyFor's refusals and the config door's; Task 6a the store and
-// email doors' keyless-fleet refusals; Task 6b the relay's.
+// email doors' keyless-fleet refusals; Task 6b the relay's; Task 7 the move refusal.
var fleetSecretsCopyBuilt = []string{
"FSK-C01", "FSK-C02", "FSK-C03", "FSK-C04",
"FSK-C05", "FSK-C06", "FSK-C07", "FSK-C08",
@@ -69,7 +69,7 @@ var fleetSecretsCopyBuilt = []string{
"FSK-C33", "FSK-C34", "FSK-C35", "FSK-C36",
"FSK-C37", "FSK-C38", "FSK-C39", "FSK-C40",
"FSK-C41", "FSK-C42", "FSK-C43", "FSK-C44",
- "FSK-C45", "FSK-C46",
+ "FSK-C45", "FSK-C46", "FSK-C47",
}
func mustParseFleetSecretsRecord(t *testing.T) []copyRow {
diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index d9d338192..b37cde32e 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -494,7 +494,15 @@ func (s *Server) handleAPICreateApp(w http.ResponseWriter, r *http.Request) {
// account role, and handing a CI credential the power to adopt release
// history is exactly the widening svcrole exists to prevent.
ownerClaim := p.Kind == PrincipalUser && acct.Role == RoleOwner
- defer s.planLock(acct)()
+ unlock := s.planLock(acct)
+ if place != "" && s.cfg.PlanCatalog == nil {
+ // A placed create may adopt an app's existing objects onto a fleet
+ // (claimAppWith's sealed-values check, §5.5), and that read belongs
+ // under the account lock a place holds. With plans on planLock took
+ // it; with plans off nothing did, so take it here, once.
+ unlock = s.lockAccount(acct.Sqid)
+ }
+ defer unlock()
if err := s.checkCreateApp(r.Context(), acct, name); err != nil {
if isPlanCap(err) {
writeJSON(w, http.StatusConflict, map[string]any{"error": err.Error(), "code": "cap"})
@@ -533,6 +541,9 @@ func (s *Server) handleAPICreateApp(w http.ResponseWriter, r *http.Request) {
case claimPolicyWriterRefused:
// placed is the lease refusal's message for this outcome.
jsonError(w, http.StatusServiceUnavailable, placed)
+ case claimStaleSealed:
+ // placed is the refusal's message for this outcome (FSK-C47).
+ jsonError(w, http.StatusConflict, placed)
case claimOK:
s.audit(acct, name, addr, "create", "created app "+name+" (cli)")
// Stamped in the SAME call that claims the name, after the claim has
diff --git a/internal/console/apienv.go b/internal/console/apienv.go
index 5bee22c6f..0b839ebbb 100644
--- a/internal/console/apienv.go
+++ b/internal/console/apienv.go
@@ -16,6 +16,7 @@ import (
"log"
"net/http"
"strings"
+ "sync"
"time"
"github.com/carlosframework/platform/internal/appconfig"
@@ -301,6 +302,14 @@ func (s *Server) handleAPIEnvironmentFork(w http.ResponseWriter, r *http.Request
}
ctx, cancel := context.WithTimeout(r.Context(), configStoreTimeout)
defer cancel()
+ // The mint below seals to the key sealKeyFor chooses, so the fork holds
+ // the account lock a key replacement holds (fleet secrets key spec
+ // §5.2.1), from before the app lock to the end of the mint: account
+ // first, then app. Released once, on every path, so the answer is
+ // written without it.
+ unlockAcct := s.lockAccount(acct.Sqid)
+ var releaseAcct sync.Once
+ defer releaseAcct.Do(unlockAcct)
var stripped []string
err := func() error {
defer s.lockApp(acct.Sqid, app)()
@@ -356,6 +365,7 @@ func (s *Server) handleAPIEnvironmentFork(w http.ResponseWriter, r *http.Request
})
s.bumpSerial(ctx)
s.mintOwnedEnvironment(ctx, acct, app, to)
+ releaseAcct.Do(unlockAcct)
writeJSON(w, http.StatusOK, map[string]any{"from": from, "to": to, "scope": req.Scope, "stripped": stripped})
}
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index 722b9db37..c40a460f8 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -27,6 +27,7 @@ import (
"crypto/subtle"
"encoding/hex"
"errors"
+ "fmt"
"log"
"net/http"
"net/url"
@@ -589,6 +590,16 @@ func (s *Server) appPlacement(reg consoleRegistry, acct *Account, app string) (s
return fleetFromRoutes(routes, acct.Sqid, app), nil
}
+// staleSealedRefusal is FSK-C47: a move refused because the app has sealed
+// values its new boxes cannot open. vars is non-empty and sorted. The one
+// sentence serves carlos apps place (placeAppTarget) and carlos apps create
+// --place onto an existing app's name (claimAppWith). Nothing in it asks for
+// a relay step: the relay reconcile re-seals a fleet app's relay credential
+// by itself.
+func staleSealedRefusal(app string, vars []string) string {
+ return fmt.Sprintf("%[1]s has sealed values that its new boxes cannot open: %[2]s. unset each with carlos secrets unset --app %[1]s <var>, run this command again, then set each again. afterwards run carlos store rotate --app %[1]s or carlos email rotate --app %[1]s for any credential the console minted", app, strings.Join(vars, ", "))
+}
+
// placeInstancesFailed is placeAppTarget's answer when it cannot read the
// app's instance records.
const placeInstancesFailed = "could not update this app's instances — try again"
@@ -721,6 +732,12 @@ func (s *Server) placeAppTarget(ctx context.Context, acct *Account, app, target
// put a record under it. SetRecordRegion and registry.SetPlacement refuse
// a runtime row again in the write itself, and SetRecordRegion an HA
// record under its CAS (final review F3).
+ //
+ // The account lock comes first (applocks.go: account, then app). The
+ // sealed-values check below reads the app's bundles for the target's key
+ // and the write that follows must not land between a seal to the old key
+ // and this move (§5.2.1, §5.5). None of this function's callers holds it.
+ defer s.lockAccount(acct.Sqid)()
defer s.lockApp(acct.Sqid, app)()
switch kind, err := release.EstablishedKind(ctx, s.cfg.Releases, acct.Sqid, app); {
case err != nil:
@@ -748,6 +765,17 @@ func (s *Server) placeAppTarget(ctx context.Context, acct *Account, app, target
if ha := placeHABlock(recs); ha != nil {
return http.StatusConflict, haMoveSentence(s.offlineName(ha.Region))
}
+ // A move never re-seals (spec §5.5): an app with a sealed value its new
+ // boxes cannot open is refused, before anything is written, with the
+ // names and the order that works.
+ stale, err := s.staleForTarget(ctx, acct, app, target)
+ if err != nil {
+ log.Printf("console: place %s/%s: sealed values for %q: %v", acct.Sqid, app, target, err)
+ return http.StatusBadGateway, placeSeedReadFailed
+ }
+ if len(stale) > 0 {
+ return http.StatusConflict, staleSealedRefusal(app, stale)
+ }
// The store-of-record write (2026-08-06 ruling): appPlacement consults
// THIS before it ever walks a route. It has to land before routes/records
diff --git a/internal/console/fleetsecrets_mint_test.go b/internal/console/fleetsecrets_mint_test.go
index 37131fd1a..f2917fafa 100644
--- a/internal/console/fleetsecrets_mint_test.go
+++ b/internal/console/fleetsecrets_mint_test.go
@@ -302,11 +302,13 @@ func TestAppCreateAdoptingFleetAppDoesNotDeadlock(t *testing.T) {
for _, plansOn := range []bool{false, true} {
t.Run(fmt.Sprintf("plans=%v", plansOn), func(t *testing.T) {
fx, token, _ := fskFixture(t, fmt.Sprintf("code-fcm-adopt-%v", plansOn))
- skRegister(t, fx, token, "home", skNewKey(t))
+ k := skNewKey(t)
+ skRegister(t, fx, token, "home", k)
fcmPlans(t, fx, plansOn)
- // Objects already under bab/shop's prefix, with a sealed value:
- // the create adopts them.
- fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": fskSeal(t, fx, "")})
+ // Objects already under bab/shop's prefix, with a value sealed to
+ // the fleet's key: the create adopts them (a value sealed to any
+ // other key is refused, §5.5).
+ fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": fskSeal(t, fx, k.fp)})
status, body := fcmWithin(t, "app create", func() (int, string) {
s, _, b := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new", token, `{"name":"shop","place":"fleet/home"}`)
return s, b
diff --git a/internal/console/fleetsecrets_moves_test.go b/internal/console/fleetsecrets_moves_test.go
new file mode 100644
index 000000000..463f0906a
--- /dev/null
+++ b/internal/console/fleetsecrets_moves_test.go
@@ -0,0 +1,316 @@
+package console
+
+// Moves (fleet secrets key spec §5.5, plan Task 7): `apps place` and
+// `apps create --place` refuse an app whose sealed values were sealed to a
+// different key than the target's, and `env fork` takes the account lock its
+// mint needs. Run through the real doors.
+
+import (
+ "context"
+ "fmt"
+ "html"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+)
+
+// fsmRefusal is FSK-C47's text for app shop and the sorted vars.
+func fsmRefusal(vars string) string {
+ return "shop has sealed values that its new boxes cannot open: " + vars + ". unset each with carlos secrets unset --app shop <var>, run this command again, then set each again. afterwards run carlos store rotate --app shop or carlos email rotate --app shop for any credential the console minted"
+}
+
+// fsmPlacement reads shop's stored placement.
+func fsmPlacement(t *testing.T, fx *consoleFixture) string {
+ t.Helper()
+ got, err := fx.st.AppPlacement(OpsAccountID, "shop")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return got
+}
+
+// fsmShop is a fixture with a deployment key, fleet home (keyed when
+// withKey) and an unplaced app shop.
+func fsmShop(t *testing.T, code string, withKey bool) (*consoleFixture, string, skFleetKey) {
+ t.Helper()
+ fx, token, _ := fskFixture(t, code)
+ k := skNewKey(t)
+ if withKey {
+ skRegister(t, fx, token, "home", k)
+ }
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ return fx, token, k
+}
+
+func fsmPlace(t *testing.T, fx *consoleFixture, token, target string) (int, map[string]any) {
+ t.Helper()
+ return postJSON(t, placeURL(fx, "shop"), map[string]string{"target": target}, token)
+}
+
+func TestPlaceRefusesStaleSealedValues(t *testing.T) {
+ deployFP := func(fx *consoleFixture) string { return fx.srv.expectedSecretsFP() }
+ t.Run("a deployment-key secret onto a fleet", func(t *testing.T) {
+ fx, token, _ := fsmShop(t, "code-fsm-dep", true)
+ fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": fskSeal(t, fx, deployFP(fx))})
+ status, body := fsmPlace(t, fx, token, "fleet/home")
+ if status != http.StatusConflict || body["error"] != fsmRefusal("API_KEY") {
+ t.Fatalf("place = %d %v, want 409 and FSK-C47 naming API_KEY", status, body)
+ }
+ if got := fsmPlacement(t, fx); got != "" {
+ t.Fatalf("placement after a refusal = %q, want unchanged", got)
+ }
+ })
+ t.Run("a value with no sealed_to, in an environment, listed sorted with the rest", func(t *testing.T) {
+ fx, token, _ := fsmShop(t, "code-fsm-env", true)
+ fskSetSecrets(t, fx, map[string]appconfig.Var{"ZED": fskSeal(t, fx, deployFP(fx))})
+ if err := appconfig.SaveEnvironment(context.Background(), fx.rel, fx.sqid, "shop", "stage", map[string]appconfig.Var{
+ "ALPHA": fskSeal(t, fx, ""), "PLAIN": {Kind: "env", Value: "1"},
+ }, nil); err != nil {
+ t.Fatal(err)
+ }
+ status, body := fsmPlace(t, fx, token, "fleet/home")
+ if status != http.StatusConflict || body["error"] != fsmRefusal("ALPHA, ZED") {
+ t.Fatalf("place = %d %v, want 409 naming ALPHA, ZED", status, body)
+ }
+ })
+ t.Run("a keyless fleet refuses every sealed value", func(t *testing.T) {
+ fx, token, _ := fsmShop(t, "code-fsm-keyless", false)
+ fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": fskSeal(t, fx, deployFP(fx))})
+ status, body := fsmPlace(t, fx, token, "fleet/home")
+ if status != http.StatusConflict || body["error"] != fsmRefusal("API_KEY") {
+ t.Fatalf("place = %d %v, want 409", status, body)
+ }
+ })
+ t.Run("a value sealed to the fleet's key moves home, not on to the platform", func(t *testing.T) {
+ fx, token, k := fsmShop(t, "code-fsm-back", true)
+ fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": fskSeal(t, fx, k.fp)})
+ if status, body := fsmPlace(t, fx, token, "fleet/home"); status != http.StatusOK {
+ t.Fatalf("place a fleet-sealed app on its own fleet = %d %v, want 200", status, body)
+ }
+ status, body := fsmPlace(t, fx, token, "")
+ if status != http.StatusConflict || body["error"] != fsmRefusal("API_KEY") {
+ t.Fatalf("unplace = %d %v, want 409 (the platform's boxes hold the deployment key)", status, body)
+ }
+ if got := fsmPlacement(t, fx); got != "fleet/home" {
+ t.Fatalf("placement after the refused unplace = %q", got)
+ }
+ })
+ t.Run("the app page's form refuses with the same sentence", func(t *testing.T) {
+ fx, _, _ := fsmShop(t, "code-fsm-browser", true)
+ fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": fskSeal(t, fx, deployFP(fx))})
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-fsm-browser-form")
+ csrf := sessionToken(t, fx, c)
+ if status, _, _ := postForm(t, c, fx.u("/apps/shop/place"), url.Values{"csrf": {csrf}, "target": {"fleet/home"}}); status != http.StatusSeeOther {
+ t.Fatalf("app place page = %d, want 303", status)
+ }
+ if _, _, page := get(t, c, fx.u("/apps/shop/settings/placement")); !strings.Contains(page, html.EscapeString(fsmRefusal("API_KEY"))) {
+ t.Fatalf("no refusal flash on the app page:\n%s", page)
+ }
+ if got := fsmPlacement(t, fx); got != "" {
+ t.Fatalf("placement after the refused form = %q", got)
+ }
+ })
+}
+
+func TestPlaceAllowsAppWithNoSecrets(t *testing.T) {
+ t.Run("no config at all", func(t *testing.T) {
+ fx, token, _ := fsmShop(t, "code-fsm-none", true)
+ if status, body := fsmPlace(t, fx, token, "fleet/home"); status != http.StatusOK {
+ t.Fatalf("place = %d %v, want 200", status, body)
+ }
+ if got := fsmPlacement(t, fx); got != "fleet/home" {
+ t.Fatalf("placement = %q", got)
+ }
+ })
+ t.Run("plain variables only, on a keyless fleet", func(t *testing.T) {
+ fx, token, _ := fsmShop(t, "code-fsm-plain", false)
+ if err := appconfig.SetEnv(context.Background(), fx.rel, fx.sqid, "shop", map[string]string{"MODE": "live"}); err != nil {
+ t.Fatal(err)
+ }
+ if status, body := fsmPlace(t, fx, token, "fleet/home"); status != http.StatusOK {
+ t.Fatalf("place = %d %v, want 200", status, body)
+ }
+ })
+ t.Run("values already sealed to the target's key", func(t *testing.T) {
+ fx, token, k := fsmShop(t, "code-fsm-match", true)
+ fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": fskSeal(t, fx, k.fp)})
+ if status, body := fsmPlace(t, fx, token, "fleet/home"); status != http.StatusOK {
+ t.Fatalf("place = %d %v, want 200", status, body)
+ }
+ })
+}
+
+func TestCreatePlaceAdoptingRefusesBeforeTheRow(t *testing.T) {
+ fx, token, _ := fskFixture(t, "code-fsm-adopt")
+ skRegister(t, fx, token, "home", skNewKey(t))
+ // Objects already under bab/shop's prefix, sealed to the deployment key:
+ // the create would adopt them onto a fleet whose boxes cannot open them.
+ fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": fskSeal(t, fx, fx.srv.expectedSecretsFP())})
+ status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new", map[string]string{"name": "shop", "place": "fleet/home"}, token)
+ if status != http.StatusConflict || out["error"] != fsmRefusal("API_KEY") {
+ t.Fatalf("adopting create = %d %v, want 409 and FSK-C47", status, out)
+ }
+ if has, err := fx.st.HasAppIn(OpsAccountID, "shop"); err != nil || has {
+ t.Fatalf("app row after the refusal: has=%v err=%v, want none", has, err)
+ }
+ // Without --place the same adoption goes through: the check is the
+ // move's, not the create's.
+ status, out = postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new", map[string]string{"name": "shop"}, token)
+ if status != http.StatusOK && status != http.StatusCreated {
+ t.Fatalf("adopting create without --place = %d %v", status, out)
+ }
+}
+
+func TestAppCreatePlaceDoesNotDeadlock(t *testing.T) {
+ for _, plansOn := range []bool{false, true} {
+ for _, adopt := range []bool{false, true} {
+ t.Run(fmt.Sprintf("plans=%v,adopt=%v", plansOn, adopt), func(t *testing.T) {
+ fx, token, _ := fskFixture(t, fmt.Sprintf("code-fsm-lock-%v-%v", plansOn, adopt))
+ k := skNewKey(t)
+ skRegister(t, fx, token, "home", k)
+ fcmPlans(t, fx, plansOn)
+ if adopt {
+ fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": fskSeal(t, fx, k.fp)})
+ }
+ status, body := fcmWithin(t, "app create --place", func() (int, string) {
+ s, _, b := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new", token, `{"name":"shop","place":"fleet/home"}`)
+ return s, b
+ })
+ if status != http.StatusOK && status != http.StatusCreated {
+ t.Fatalf("create = %d %s", status, body)
+ }
+ if got := fsmPlacement(t, fx); got != "fleet/home" {
+ t.Fatalf("placement = %q, want fleet/home", got)
+ }
+ })
+ }
+ }
+}
+
+func TestPlaceDoesNotDeadlock(t *testing.T) {
+ for _, plansOn := range []bool{false, true} {
+ t.Run(fmt.Sprintf("plans=%v", plansOn), func(t *testing.T) {
+ fx, token, _ := fsmShop(t, fmt.Sprintf("code-fsm-place-%v", plansOn), true)
+ fcmPlans(t, fx, plansOn)
+ status, body := fcmWithin(t, "apps place", func() (int, string) {
+ s, _, b := rawReq(t, http.MethodPost, placeURL(fx, "shop"), token, `{"target":"fleet/home"}`)
+ return s, b
+ })
+ if status != http.StatusOK {
+ t.Fatalf("place = %d %s", status, body)
+ }
+ })
+ }
+}
+
+// TestForkWaitsForTheAccountLock: env fork mints a credential for the new
+// environment, sealed to the app's key, so it holds the account lock a key
+// replacement holds (§5.2.1). With the lock held elsewhere the fork waits;
+// when it is released the fork completes.
+func TestForkWaitsForTheAccountLock(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-fsm-fork")
+ owner := cliToken(t, fx, "paul@keymail.dev", "code-fsm-fork-owner")
+ ctx := context.Background()
+ enableInstances(t, fx, "titogo", titoManifest())
+ if err := appconfig.SaveEnvironment(ctx, fx.rel, "bab", "titogo", "lagged", map[string]appconfig.Var{
+ "OWN": {Kind: "env", Value: "1"},
+ }, nil); err != nil {
+ t.Fatal(err)
+ }
+ release := fx.srv.lockAccount("bab")
+ type answer struct {
+ status int
+ body string
+ }
+ done := make(chan answer, 1)
+ go func() {
+ s, _, b := rawReq(t, http.MethodPost, envDoorURL(fx, "/fork"), owner, `{"from":"lagged","to":"lagged-team","scope":"alta"}`)
+ done <- answer{s, b}
+ }()
+ select {
+ case a := <-done:
+ release()
+ t.Fatalf("fork answered %d %s while the account lock was held elsewhere", a.status, a.body)
+ case <-time.After(400 * time.Millisecond):
+ }
+ if _, _, found, err := appconfig.GetEnvironment(ctx, fx.rel, "bab", "titogo", "lagged-team"); err != nil || found {
+ release()
+ t.Fatalf("fork wrote the environment before the lock was free: found=%v err=%v", found, err)
+ }
+ release()
+ select {
+ case a := <-done:
+ if a.status != http.StatusOK {
+ t.Fatalf("fork after the lock was released = %d %s", a.status, a.body)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("fork did not finish after the account lock was released")
+ }
+}
+
+// fsmWaitsForAccountLock holds the account lock, starts do, and checks it
+// has not answered after a beat, then releases the lock and checks it
+// completes with want.
+func fsmWaitsForAccountLock(t *testing.T, fx *consoleFixture, what string, want int, do func() (int, string)) {
+ t.Helper()
+ release := fx.srv.lockAccount(fx.sqid)
+ type answer struct {
+ status int
+ body string
+ }
+ done := make(chan answer, 1)
+ go func() {
+ s, b := do()
+ done <- answer{s, b}
+ }()
+ select {
+ case a := <-done:
+ release()
+ t.Fatalf("%s answered %d %s while the account lock was held elsewhere", what, a.status, a.body)
+ case <-time.After(400 * time.Millisecond):
+ }
+ release()
+ select {
+ case a := <-done:
+ if a.status != want {
+ t.Fatalf("%s after the lock was released = %d %s, want %d", what, a.status, a.body, want)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatalf("%s did not finish after the account lock was released", what)
+ }
+}
+
+// TestPlaceWaitsForTheAccountLock: the stale read and the placement write
+// are one step under the account lock, so a seal that holds it (a config
+// PUT, a key replacement) is never overtaken by a move.
+func TestPlaceWaitsForTheAccountLock(t *testing.T) {
+ fx, token, _ := fsmShop(t, "code-fsm-place-lock", true)
+ fsmWaitsForAccountLock(t, fx, "apps place", http.StatusOK, func() (int, string) {
+ s, _, b := rawReq(t, http.MethodPost, placeURL(fx, "shop"), token, `{"target":"fleet/home"}`)
+ return s, b
+ })
+}
+
+// TestCreatePlaceHoldsTheAccountLockWithPlansOff: with no plan catalog the
+// create door took no account lock, so a placed create takes it itself for
+// the adoption check; with plans on planLock does.
+func TestCreatePlaceHoldsTheAccountLock(t *testing.T) {
+ for _, plansOn := range []bool{false, true} {
+ t.Run(fmt.Sprintf("plans=%v", plansOn), func(t *testing.T) {
+ fx, token, _ := fskFixture(t, fmt.Sprintf("code-fsm-create-lock-%v", plansOn))
+ skRegister(t, fx, token, "home", skNewKey(t))
+ fcmPlans(t, fx, plansOn)
+ fsmWaitsForAccountLock(t, fx, "app create --place", http.StatusOK, func() (int, string) {
+ s, _, b := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new", token, `{"name":"shop","place":"fleet/home"}`)
+ return s, b
+ })
+ })
+ }
+}
diff --git a/internal/console/fleetsecretskey.go b/internal/console/fleetsecretskey.go
index bdb95bb95..dbeab77dc 100644
--- a/internal/console/fleetsecretskey.go
+++ b/internal/console/fleetsecretskey.go
@@ -229,6 +229,67 @@ func (s *Server) fleetStaleValues(ctx context.Context, acct *Account, fleet, fp
return out, nil
}
+// staleForTarget lists, sorted, the sealed vars of app, in any bundle (default,
+// named environments, instance overlays), that the boxes of target cannot
+// open: those whose sealed_to is absent or is not the target's key
+// fingerprint (spec §5.5). target is "" (the platform's boxes, the
+// deployment key) or "fleet/<name>" (that fleet's key; a keyless fleet opens
+// nothing, so every sealed value is stale for it). The same reading as
+// fleetStaleValues, appSealedVars, so the two cannot disagree about what a
+// bundle holds.
+//
+// CARLOS_RELAY is left out: the relay reconcile re-seals an envelope that is
+// not sealed to the app's key by itself once the app is placed (Task 6b), so
+// it is not a value the owner has to unset.
+//
+// It takes no lock. Callers that go on to write the placement hold the
+// account lock (and, for a place, the app lock) from this read through the
+// write (§5.2.1). It refuses nothing itself.
+func (s *Server) staleForTarget(ctx context.Context, acct *Account, app, target string) ([]string, error) {
+ var fp string
+ if target == "" {
+ fp = s.expectedSecretsFP()
+ } else {
+ name, ok := registry.FleetPlacement(target)
+ if !ok {
+ return nil, fmt.Errorf("console: stale for target: %q names no fleet", target)
+ }
+ reg, err := openRegistry(s.cfg.Registry)
+ if err != nil {
+ return nil, err
+ }
+ row, err := reg.GetFleet(name)
+ if err != nil {
+ return nil, err
+ }
+ if row == nil || row.Account != acct.Sqid {
+ return nil, errFleetNotOwned{Fleet: name}
+ }
+ fp = row.SecretsKeyFP
+ }
+ vars, _, err := s.appSealedVars(ctx, acct.Sqid, app)
+ if err != nil {
+ return nil, err
+ }
+ set := map[string]bool{}
+ for _, v := range vars {
+ if v.name == relayVar {
+ continue
+ }
+ // An empty fp is a target with no key to match: nothing is sealed
+ // to it, an absent sealed_to included.
+ if fp == "" || v.sealedTo != fp {
+ set[v.name] = true
+ }
+ }
+ out := make([]string, 0, len(set))
+ for name := range set {
+ out = append(out, name)
+ }
+ sort.Strings(out)
+ return out, nil
+}
+
// fleetPlacedApps lists, sorted, the account's live apps placed on fleet,
// read as appPlacement reads one: the store's placement column, then the
// routes for an app placed before the column existed (one route listing for
diff --git a/internal/console/server.go b/internal/console/server.go
index cb240d491..0367ee493 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -4904,6 +4904,7 @@ const (
claimTemporaryReserved // a tmp- name at a permanent door (temporary static sites spec ruling 7)
claimPolicyClearFailed // an earlier app's policy at the name's key could not be cleared (#328, #329)
claimPolicyWriterRefused // the create could not take the policy writer holding (another console holds it)
+ claimStaleSealed // adopting an existing app onto a fleet whose boxes cannot open its sealed values (fleet secrets key spec §5.5); placed carries the message
)
// Create door copy (collected for review in plan Task 15): the create-time
@@ -5038,6 +5039,12 @@ func (s *Server) claimApp(ctx context.Context, acct *Account, name, addr, placem
// for that outcome alone the second value is the refusal's message, not a
// placement. A name with no policy object takes no holding at all.
//
+// An owner adopting an existing app onto a placement (adoptingExistingApp
+// with a non-empty placement) is a move of its sealed values: the check
+// carlos apps place makes runs before createClaimAppRow, and a value the
+// target's boxes cannot open is claimStaleSealed, whose second value is
+// likewise the refusal's message (spec §5.5).
+//
// A zero expiresAt is the permanent claim every existing door makes, and it
// refuses a tmp- name: nothing permanent may be created in that namespace
// (spec ruling 7). A non-zero one is /new-temporary's claim: it refuses any
@@ -5148,6 +5155,22 @@ func (s *Server) claimAppWith(ctx context.Context, acct *Account, name, addr, pl
}
return claimTaken, "", nil
}
+ // Adopting an app whose objects already exist onto a placement is a move
+ // of its sealed values (spec §5.5): refused before the row is written,
+ // the same check carlos apps place makes. A create with no objects has
+ // nothing sealed to move. The door holds the account lock from here to
+ // the end of the create (handleAPICreateApp: planLock, or the lock it
+ // takes itself for a placement), so it is not taken again.
+ if adoptingExistingApp && placement != "" {
+ stale, err := s.staleForTarget(ctx, acct, name, placement)
+ if err != nil {
+ log.Printf("console: claim %s/%s: sealed values for %q: %v", acct.Sqid, name, placement, err)
+ return claimStoreFailed, "", nil
+ }
+ if len(stale) > 0 {
+ return claimStaleSealed, staleSealedRefusal(name, stale), nil
+ }
+ }
region, source := s.resolveNewAppRegion(ctx, rq, adoptingExistingApp)
if s.beforeClaimInsert != nil {
s.beforeClaimInsert()
diff --git a/internal/console/teamcreds.go b/internal/console/teamcreds.go
index 61f1e5280..3a1fc91b3 100644
--- a/internal/console/teamcreds.go
+++ b/internal/console/teamcreds.go
@@ -46,8 +46,7 @@ func (s *Server) mintOwnedEnvironmentCredentials(ctx context.Context, acct *Acco
// The password is sealed to the app's own key (sealKeyFor); an app on a
// keyless fleet gets no credential and the error says why. It takes no
// lock: its callers hold the account lock (the config PUT for a team
-// write, the email enable door, the environment adopt door), except the
-// environment fork door, which takes it in Task 7.
+// write, the email enable door, the environment adopt and fork doors).
func (s *Server) mintOwnedEnvironmentMail(ctx context.Context, acct *Account, app, env string) error {
if s.cfg.Releases == nil || s.cfg.MailProvisioner == nil {
return nil