carlos / platform Public

Relay, plan storage and the scan recovery doors seal to the app's own key, and the guard pins every seal to sealKeyFor (Task 6b)

Relay: relayReady loses its CARLOS_SECRETS_PUBKEY arm. relaySealKey wraps
sealKeyFor (errNoDeploymentKey becomes errRelayNoSealKey, a keyless fleet
becomes FSK-C46, a 409). relayEnable and the owned-environment hook choose
the key after relayReady and before the first write; relayReissue (rotate)
and the reconcile choose it per app. relayApplyConfig and relayApplyConfigIn
take the Sealer and store its Var, so sealed_to is set. The reconcile now
re-seals an envelope whose sealed_to is not the app's key (a missing
sealed_to reads as the deployment key, so a platform app's legacy envelope
stays current), and skips an app with no key with a log line.

Plan storage skips an app whose key cannot be chosen, with a log line, and
retries next pass. Scan revoke and enforce need a key only when the regrant
would mint (objstore.GrantHealthy, now also the grant walk's own
short-circuit), so an operator can always take scanning or its Deny off a
healthy store on a keyless fleet.

TestOnlySealKeyForBuildsSealers type-checks every package that can reach
appconfig.Seal/SealBound/SealUnbound/NewSealer, archive.Seal or console's
chooseSealKey and allows each only in the functions it names, by object
identity; a non-empty appconfig.Sealer literal only in NewSealer. Five
overlay fixtures and the ErrSealerBinding case.

Account lock entry points in this commit:
- relayEnable (the enable door): takes it, before the relay app lock.
- relayReissue (per app, the rotate door): takes it.
- relayConverge (per app, the reconcile): takes it.
- relayEnvironmentHook: never takes it; the config PUT and the adopt door
  hold it, the fork door takes it in Task 7, the release door calls it
  unlocked (I2 gap, commented).
- convergeStores (plan storage, per app): takes it; its callers hold the
  lapse lock, the member lock or the billing hold, never the account lock.
- scan revoke and enforce: take it as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 72fde1a951cbe4899a2193da8d9ceab0ead4dd83 parent bdb8920
15 files changed, +1,256 −81
  • approved_fleet_secrets_copy_test.go +2 −2
  • internal/console/apirelay.go +5 −0
  • internal/console/apiscan.go +38 −4
  • internal/console/fleetsecrets_relay_test.go +471 −0
  • internal/console/planstorage.go +19 −9
  • internal/console/relayenv.go +30 −22
  • internal/console/relayops.go +128 −33
  • internal/console/relayops_test.go +13 −1
  • internal/console/sealkey_guard_test.go +456 −0
  • internal/console/testdata/sealguard/aliased/aliased.go +16 −0
  • internal/console/testdata/sealguard/arbitrary/arbitrary.go +14 −0
  • internal/console/testdata/sealguard/choose/choose.go +11 −0
  • internal/console/testdata/sealguard/ctor/ctor.go +9 −0
  • internal/console/testdata/sealguard/sealkey/sealkey.go +19 −0
  • internal/objstore/walk.go +25 −10

Intent

Human

<task-notification> <task-id>aa9024239ce777a50</task-id> <tool-use-id>toolu_01Cptp3CZhXcLVu2qRwXzVP8</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/aa9024239ce777a50.output</output-file> <status>completed</status> <summary>Agent "Implement Task 6a: store/mail seal sites" 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_WITH_CONCERNS Commit: bdb89206 on design-fleet-secrets-key (BASE 174a3972). The working tree is clean and scratch files are removed. Tests: the 8 new tests (one extra keyless-mail test, plans on and off) failed against BASE except the app-create witness, which seals nothing yet; all pass now. The Store/Mail/Relay/Scan/Webhook/Plan/Team/Email run and a wider console run pass, as do the copy gate, vet, gofmt and the darwin/windows/arm64 builds. Seven mutations (deployment-key fallbacks, wrong-key seals, a nested account lock) each make their test fail. Concerns: 1. The detached seed copy (`runFrom`) does not call `sealKeyFor` directly, as the brief says. The refusal goes through the existing held response, so the store row FSK-C44 becomes the seed's failure reason. `runFrom` takes the account lock itself. 2. The account lock is now held across whole store and email walks. Other doors on the same account wait behind them. 3. The webhook rotate door no longer gives a 503 up front when the console has no deployment key. It skips each such app, leaves it in `remaining`, and answers 200. 4. The config PUT now takes the account lock for any team write into an environment, not only one carrying a secret. Without that, a new team environment's mail credential was sealed with no lock. 5. The env fork mint (Task 7) and plan storage (6b) still seal unlocked. 6. I changed three existing tests: the provision queueing probe, and two callback rotation race tests whose in-process door now waits on the lock. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-secrets-key/.superpowers/sdd/2026-10-29-fleet-secrets-key/task-6a-report.md</result> <usage><subagent_tokens>354838</subagent_tokens><tool_uses>170</tool_uses><duration_ms>4120263</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>ac8f4c131e720bf24</task-id> <tool-use-id>toolu_014o9wm2KngxSKjsFAzqk2gW</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/ac8f4c131e720bf24.output</output-file> <status>completed</status> <summary>Agent "Review Task 6a (spec + quality)" 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>**Spec compliance:** ✅ Compliant for the 6a scope. Two things can't be verified from this diff alone. First, I1 won't hold across the branch until 6b lands: the relay still seals to the deployment key (`relayenv.go:50-73`, `relayops.go:580-591`), and plan storage seals without the account lock. Second, the environment fork's mint (`apienv.go:358`) is still unlocked; that is Task 7's job. **Task quality:** Approved. **Critical:** none. **Important:** none. **Minor (5):** - `internal/objstore/walk.go:858`: the comment still says both key halves are sealed to the deployment's key. - `internal/console/apiscan.go:465` and `:559`: scan revoke and enforce-off now refuse an app on a keyless fleet before clearing the record. That leaves its read block in place until the owner registers a key. The controller should decide whether these doors should choose a key only when they actually need to re-mint. - The account lock is taken before the request body is read, at `apistore.go:824` and `apistore_provision.go:39`. - No test covers the detached seed copy's lock (`apiinstanceseed.go:453`). - `TestAppCreateAdoptingFleetAppDoesNotDeadlock` passes on the base commit too, because app create seals nothing yet. It works as a witness only. On the five named risks (a) to (e): none shows a problem. Every remaining seal site gets its key from `sealKeyFor` for the same app. Every door refuses a keyless fleet before its first backend call. Nothing takes the account lock while a caller already holds it, and it always comes before the app lock. The three changed existing tests were changed because of the new lock, not weakened. Existing scan callback secrets won't be re-delivered, because the callback hash ignores `SealedTo`. Review: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-secrets-key/.superpowers/sdd/2026-10-29-fleet-secrets-key/task-6a-review.md`</result> <usage><subagent_tokens>161257</subagent_tokens><tool_uses>24</tool_uses><duration_ms>270269</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>afde850d773aca226</task-id> <tool-use-id>toolu_018fg43pB3Hu8o6G4uPmj5Lg</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" is waiting on its own background work</summary> <note>This agent stopped with background work of its own still running. It may resume on its own when that work completes or reports, and the same task-id notifies again if it does; the result below may be interim.</note> <result>Waiting on the wide run.</result> <usage><subagent_tokens>328279</subagent_tokens><tool_uses>122</tool_uses><duration_ms>2299658</duration_ms></usage> </task-notification>

Attributed to this commit: 18.4 g CO₂e (2,302,252 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 6003679a7..a1a9ec6cb 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.
+// email doors' keyless-fleet refusals; Task 6b the relay's.
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-C45", "FSK-C46",
}
func mustParseFleetSecretsRecord(t *testing.T) []copyRow {
diff --git a/internal/console/apirelay.go b/internal/console/apirelay.go
index 7744a59c2..7902c1daa 100644
--- a/internal/console/apirelay.go
+++ b/internal/console/apirelay.go
@@ -97,7 +97,12 @@ func relayNoBucket(w http.ResponseWriter) {
// re-running the runbook, not this console failing, so they are matched by
// their own stable wording rather than left to read as a 502.
func relayDoorError(w http.ResponseWriter, verb string, err error) {
+ var keyless errRelayKeylessFleet
switch {
+ case errors.As(err, &keyless):
+ // The app's fleet has no secrets key (FSK-C46): the owner's to fix,
+ // and nothing was written.
+ jsonError(w, http.StatusConflict, keyless.Error())
case errors.Is(err, errRelayNoRegions), errors.Is(err, errRelayNoSealKey),
errors.Is(err, errRelayNotHeld), errors.Is(err, errRelayNoBucket):
jsonError(w, http.StatusServiceUnavailable, err.Error())
diff --git a/internal/console/apiscan.go b/internal/console/apiscan.go
index 6f4b73713..c64aa339c 100644
--- a/internal/console/apiscan.go
+++ b/internal/console/apiscan.go
@@ -461,9 +461,10 @@ func (s *Server) handleAPIScanRevoke(w http.ResponseWriter, r *http.Request) {
return
}
// The account lock from the key choice through the delivery (fleet
- // secrets key spec §5.2.1), before any app lock.
+ // secrets key spec §5.2.1), before any app lock. The key is needed only
+ // if the regrant below would mint (scanRegrantSealer).
defer s.lockAccount(acct.Sqid)()
- sealer, ok := s.storeSealKey(w, r.Context(), acct, app)
+ sealer, ok := s.scanRegrantSealer(w, r.Context(), acct, app)
if !ok {
return
}
@@ -555,9 +556,10 @@ func (s *Server) handleAPIScanEnforce(w http.ResponseWriter, r *http.Request) {
return
}
// The account lock from the key choice through the delivery (fleet
- // secrets key spec §5.2.1), before any app lock.
+ // secrets key spec §5.2.1), before any app lock. The key is needed only
+ // if the regrant below would mint (scanRegrantSealer).
defer s.lockAccount(acct.Sqid)()
- sealer, ok := s.storeSealKey(w, r.Context(), acct, app)
+ sealer, ok := s.scanRegrantSealer(w, r.Context(), acct, app)
if !ok {
return
}
@@ -630,6 +632,38 @@ var (
errEnforceOnEncrypted = errors.New("console: enforcement on a client-encrypted store")
)
+// scanRegrantSealer is the sealer for a scan door whose only store write is
+// regrantForScanning (revoke and enforce): the app's own key when one can be
+// chosen (storeSealKey). When the app has none (a keyless fleet, or a
+// platform app on a console without a usable deployment key), a regrant of
+// a healthy store, or of no provisioned store, mints and seals nothing
+// (objstore.GrantHealthy), so the door goes on with the zero Sealer, which
+// refuses every binding and seals nothing. Only a regrant that would mint is
+// refused, with storeSealKey's answer, before the door writes anything. So
+// an operator can always take scanning, or its Deny, off a healthy store,
+// whatever the app's key (ledger ruling, plan Task 6b). Any other failure
+// to choose the key is refused as storeSealKey refuses it. It takes no lock;
+// the door holds the account lock.
+func (s *Server) scanRegrantSealer(w http.ResponseWriter, ctx context.Context, acct *Account, app string) (appconfig.Sealer, bool) {
+ _, err := s.sealKeyFor(ctx, acct.Sqid, app)
+ var keyless errFleetNoSecretsKey
+ if errors.As(err, &keyless) || errors.Is(err, errNoDeploymentKey) || errors.Is(err, errDeploymentKeyUnreadable) {
+ rec, _, rerr := objstore.Get(ctx, s.cfg.Releases, acct.Sqid, app)
+ nothing := rerr == nil && (rec == nil || rec.Provisioned == nil)
+ healthy := false
+ if rerr == nil && !nothing {
+ healthy, rerr = objstore.GrantHealthy(ctx, s.cfg.Releases, s.cfg.StoreDeployment, rec, acct.Sqid, app, "")
+ }
+ if rerr != nil {
+ log.Printf("console: api scan %s/%s: reading the store to see whether a regrant mints: %v", acct.Sqid, app, rerr)
+ }
+ if nothing || healthy {
+ return appconfig.Sealer{}, true
+ }
+ }
+ return s.storeSealKey(w, ctx, acct, app)
+}
+
// regrantForScanning re-runs the store walk so the app's inline policy catches
// up with the record. Grant is the only writer of that policy, and it is
// idempotent on a healthy store: everything but the policy short-circuits.
diff --git a/internal/console/fleetsecrets_relay_test.go b/internal/console/fleetsecrets_relay_test.go
new file mode 100644
index 000000000..20d6426b0
--- /dev/null
+++ b/internal/console/fleetsecrets_relay_test.go
@@ -0,0 +1,471 @@
+package console
+
+// The relay, plan storage and the scan recovery doors for an app on a fleet
+// (fleet secrets key spec §5.2, §5.2.1; plan Task 6b). What these pin, in
+// the order they would hurt if lost: a relay key for a fleet app is sealed
+// to its fleet's key, on enable, on a rotation, on the reconcile and in each
+// owned environment, never to the deployment key; a relay enable on a
+// keyless fleet writes nothing; the reconcile re-seals an envelope sealed to
+// a key the app's boxes do not hold, and leaves a platform app's legacy
+// envelope alone; plan storage skips an app whose key cannot be chosen and
+// converges it once it can; and an operator can always turn scanning or its
+// enforcement off, keyless fleet or not, unless doing so would mint.
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/relay"
+)
+
+// fsrRelayWorld is fcmFleetShop (bab, home, shop placed on it, the
+// deployment key) with the relay armed: one region, a staged master and the
+// writer lease held. armRelay is not used: it replaces the deployment key.
+func fsrRelayWorld(t *testing.T, code string, withKey bool) *fcmWorld {
+ t.Helper()
+ w := fcmFleetShop(t, code, withKey)
+ w.fx.srv.cfg.RelayRegions = []string{"eu-west-1"}
+ w.fx.srv.cfg.PlatformDomain = "oncarlos.com"
+ t.Setenv(relayMastersEnv("eu-west-1"), "k1:"+relayTestMaster(1))
+ if err := w.fx.srv.relayAcquire(context.Background()); err != nil {
+ t.Fatalf("acquire the writer lease: %v", err)
+ }
+ return w
+}
+
+// fsrCart adds cart, an app placed nowhere, to bab.
+func fsrCart(t *testing.T, w *fcmWorld) {
+ t.Helper()
+ if _, err := w.fx.st.CreateAppIn(OpsAccountID, "cart", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// fsrEnableRelay is `carlos relay enable` for app, through the door.
+func fsrEnableRelay(t *testing.T, w *fcmWorld, app string) {
+ t.Helper()
+ if status, out := postJSON(t, relayURL(w.fx, app), map[string]any{}, w.token); status != http.StatusOK {
+ t.Fatalf("relay enable %s = %d %v", app, status, out)
+ }
+}
+
+// fsrOwnedEnv makes env an environment of shop owned by the team scope
+// alta, the state a team's first write leaves.
+func fsrOwnedEnv(t *testing.T, w *fcmWorld, app, env string) {
+ t.Helper()
+ if _, err := appconfig.ApplyEnvironmentOwned(context.Background(), w.fx.rel, w.fx.sqid, app, env, "alta",
+ map[string]appconfig.Var{"TEAM_ONLY": {Kind: "env", Value: "1"}}, nil); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// fsrEnvVars is env's bundle of app.
+func fsrEnvVars(t *testing.T, w *fcmWorld, app, env string) map[string]appconfig.Var {
+ t.Helper()
+ m, err := appconfig.LoadEnvironment(context.Background(), w.fx.rel, w.fx.sqid, app, env)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return m.Vars
+}
+
+// sealedToDeployment asserts v is sealed to the deployment key and opens
+// with it alone, for bab/app. Returns the plaintext.
+func (w *fcmWorld) sealedToDeployment(t *testing.T, app, name string, v appconfig.Var) string {
+ t.Helper()
+ depFP, err := appconfig.PublicFingerprint(w.fx.srv.cfg.SecretsPub)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if v.SealedTo != depFP {
+ t.Fatalf("%s sealed_to = %q, want the deployment's %q", name, v.SealedTo, depFP)
+ }
+ plain, err := w.open(t, w.depPriv, app, v)
+ if err != nil {
+ t.Fatalf("the deployment key does not open %s: %v", name, err)
+ }
+ if _, err := w.open(t, w.fleet.priv, app, v); err == nil {
+ t.Fatalf("home's key opens %s", name)
+ }
+ return plain
+}
+
+// TestRelayApplyOnFleet: enabling the relay for shop, on home with its key
+// registered, seals the app's CARLOS_RELAY and each owned environment's to
+// home's key; the record's digest is the envelope's.
+func TestRelayApplyOnFleet(t *testing.T) {
+ w := fsrRelayWorld(t, "code-fsr-apply", true)
+ fsrOwnedEnv(t, w, "shop", "crew")
+ fsrEnableRelay(t, w, "shop")
+
+ v := appVars(t, w.fx, "shop")[relayVar]
+ app := w.sealedToFleet(t, "shop's "+relayVar, v)
+ env := w.sealedToFleet(t, "crew's "+relayVar, fsrEnvVars(t, w, "shop", "crew")[relayVar])
+ if app == env {
+ t.Fatal("the environment's relay config is the app's")
+ }
+ rec := relayRecord(t, w.fx, "shop")
+ if rec == nil || rec.IssuedDigest != relayEnvelopeDigest(v.Envelope) || rec.Environments["crew"] == nil {
+ t.Fatalf("relay record = %+v, want the delivered envelope's digest and crew's identity", rec)
+ }
+}
+
+// TestRelayEnableOnFleetWithNoDeploymentKey: a console with no
+// CARLOS_SECRETS_PUBKEY still serves a fleet app whose fleet has a key, and
+// still refuses a platform app with the relay's own answer.
+func TestRelayEnableOnFleetWithNoDeploymentKey(t *testing.T) {
+ w := fsrRelayWorld(t, "code-fsr-nodep", true)
+ fsrCart(t, w)
+ w.fx.srv.cfg.SecretsPub = ""
+
+ fsrEnableRelay(t, w, "shop")
+ w.sealedToFleet(t, "shop's "+relayVar, appVars(t, w.fx, "shop")[relayVar])
+
+ status, out := postJSON(t, relayURL(w.fx, "cart"), map[string]any{}, w.token)
+ if status != http.StatusServiceUnavailable || out["error"] != errRelayNoSealKey.Error() {
+ t.Fatalf("relay enable for a platform app with no deployment key = %d %v, want 503 %q", status, out, errRelayNoSealKey)
+ }
+ if rec := relayRecord(t, w.fx, "cart"); rec != nil {
+ t.Fatalf("a refused enable wrote cart's record: %+v", rec)
+ }
+}
+
+// TestRelayEnableOnKeylessFleetRefusesBeforeMutation: home has no key, so
+// the enable answers FSK-C46 and writes no record, no config and no
+// aggregate entry.
+func TestRelayEnableOnKeylessFleetRefusesBeforeMutation(t *testing.T) {
+ w := fsrRelayWorld(t, "code-fsr-keyless", false)
+ want := fmt.Sprintf("%s has no secrets key, so the console cannot deliver a relay key to %s and will not issue one. run carlos fleets secrets-key %s <pubkey>", "home", "shop", "home")
+
+ status, out := postJSON(t, relayURL(w.fx, "shop"), map[string]any{}, w.token)
+ if status != http.StatusConflict || out["error"] != want {
+ t.Fatalf("relay enable on a keyless fleet = %d %v, want 409 %q", status, out, want)
+ }
+ if rec := relayRecord(t, w.fx, "shop"); rec != nil {
+ t.Fatalf("a refused enable wrote the relay record: %+v", rec)
+ }
+ if v, ok := appVars(t, w.fx, "shop")[relayVar]; ok {
+ t.Fatalf("a refused enable delivered %s: %+v", relayVar, v)
+ }
+ if _, ok := relayAuthority(t, w.fx).Lookup(w.fx.sqid, "shop"); ok {
+ t.Fatal("a refused enable published shop in the aggregate")
+ }
+}
+
+// TestRelayRotateUsesEachAppsKey: one rotation through the operator's door
+// re-issues a platform app (cart) and a fleet app (shop); each new value is
+// sealed to its own boxes' key.
+func TestRelayRotateUsesEachAppsKey(t *testing.T) {
+ w := fsrRelayWorld(t, "code-fsr-rotate", true)
+ fsrCart(t, w)
+ fsrEnableRelay(t, w, "shop")
+ fsrEnableRelay(t, w, "cart")
+ before := map[string]string{
+ "shop": w.sealedToFleet(t, "shop's "+relayVar, appVars(t, w.fx, "shop")[relayVar]),
+ "cart": w.sealedToDeployment(t, "cart", "cart's "+relayVar, appVars(t, w.fx, "cart")[relayVar]),
+ }
+
+ w.fx.srv.cfg.RelayOperators = []string{"paul@keymail.dev"}
+ t.Setenv(relayMastersEnv("eu-west-1"), "k1:"+relayTestMaster(1)+",k2:"+relayTestMaster(2))
+ seedHeartbeat(t, w.fx, "box1", "eu-west-1", time.Minute, "k1", "k2")
+ status, out := postJSON(t, w.fx.ts.URL+"/api/cli/relay/rotate", map[string]any{"region": "eu-west-1"}, w.token)
+ if status != http.StatusOK || out["apps"] != float64(2) {
+ t.Fatalf("rotate = %d %v, want both apps re-issued", status, out)
+ }
+ after := map[string]string{
+ "shop": w.sealedToFleet(t, "shop's "+relayVar+" after rotate", appVars(t, w.fx, "shop")[relayVar]),
+ "cart": w.sealedToDeployment(t, "cart", "cart's "+relayVar+" after rotate", appVars(t, w.fx, "cart")[relayVar]),
+ }
+ for app := range before {
+ if before[app] == after[app] {
+ t.Fatalf("%s's relay config did not change on a rotation", app)
+ }
+ }
+}
+
+// TestRelayReconcileUsesEachAppsKey: one reconcile pass re-delivers a
+// platform app's and a fleet app's missing CARLOS_RELAY, each to its own key.
+func TestRelayReconcileUsesEachAppsKey(t *testing.T) {
+ w := fsrRelayWorld(t, "code-fsr-reconcile", true)
+ fsrCart(t, w)
+ fsrEnableRelay(t, w, "shop")
+ fsrEnableRelay(t, w, "cart")
+ ctx := context.Background()
+ for _, app := range []string{"shop", "cart"} {
+ if _, err := appconfig.Apply(ctx, w.fx.rel, w.fx.sqid, app, nil, []string{relayVar}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := w.fx.srv.relayReconcile(ctx); err != nil {
+ t.Fatalf("reconcile: %v", err)
+ }
+ w.sealedToFleet(t, "shop's reconciled "+relayVar, appVars(t, w.fx, "shop")[relayVar])
+ w.sealedToDeployment(t, "cart", "cart's reconciled "+relayVar, appVars(t, w.fx, "cart")[relayVar])
+}
+
+// TestRelayReconcileResealsAStaleEnvelope: an envelope sealed to the
+// deployment key with no sealed_to, which is what a console before fleet
+// keys wrote for every app, is re-sealed to home's key for shop (app and
+// owned environment), with the same plaintext. The same legacy envelope on
+// cart, a platform app, is current and left alone: the rollout re-seals
+// nothing that was right.
+func TestRelayReconcileResealsAStaleEnvelope(t *testing.T) {
+ w := fsrRelayWorld(t, "code-fsr-stale", true)
+ fsrCart(t, w)
+ fsrOwnedEnv(t, w, "shop", "crew")
+ fsrEnableRelay(t, w, "shop")
+ fsrEnableRelay(t, w, "cart")
+ ctx := context.Background()
+ dep, err := appconfig.ParsePublicKey(w.fx.srv.cfg.SecretsPub, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // legacy rewrites a delivered value as the old console wrote it: the
+ // same plaintext sealed to the deployment key, no sealed_to, and the
+ // record's digest moved to match, so only sealed_to tells it apart.
+ legacy := func(app, env string, plain string) string {
+ t.Helper()
+ envelope, err := appconfig.Seal(dep, appconfig.Binding{Account: w.fx.sqid, App: app}, []byte(plain))
+ if err != nil {
+ t.Fatal(err)
+ }
+ set := map[string]appconfig.Var{relayVar: {Kind: "secret", Envelope: envelope}}
+ if env == "" {
+ _, err = appconfig.Apply(ctx, w.fx.rel, w.fx.sqid, app, set, nil)
+ } else {
+ _, err = appconfig.ApplyEnvironment(ctx, w.fx.rel, w.fx.sqid, app, env, set, nil)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec, etag, err := relay.GetRecord(ctx, w.fx.rel, w.fx.sqid, app)
+ if err != nil || rec == nil {
+ t.Fatalf("relay record %s: %+v %v", app, rec, err)
+ }
+ if env == "" {
+ rec.IssuedDigest = relayEnvelopeDigest(envelope)
+ } else {
+ rec.Environments[env].IssuedDigest = relayEnvelopeDigest(envelope)
+ }
+ if _, err := relay.PutRecord(ctx, w.fx.rel, w.fx.sqid, app, rec, etag); err != nil {
+ t.Fatal(err)
+ }
+ return envelope
+ }
+ shopPlain := w.sealedToFleet(t, "shop's "+relayVar, appVars(t, w.fx, "shop")[relayVar])
+ crewPlain := w.sealedToFleet(t, "crew's "+relayVar, fsrEnvVars(t, w, "shop", "crew")[relayVar])
+ cartPlain := w.sealedToDeployment(t, "cart", "cart's "+relayVar, appVars(t, w.fx, "cart")[relayVar])
+ legacy("shop", "", shopPlain)
+ legacy("shop", "crew", crewPlain)
+ cartLegacy := legacy("cart", "", cartPlain)
+
+ if err := w.fx.srv.relayReconcile(ctx); err != nil {
+ t.Fatalf("reconcile: %v", err)
+ }
+ if got := w.sealedToFleet(t, "shop's resealed "+relayVar, appVars(t, w.fx, "shop")[relayVar]); got != shopPlain {
+ t.Fatalf("shop's resealed relay config = %q, want the same value %q", got, shopPlain)
+ }
+ if got := w.sealedToFleet(t, "crew's resealed "+relayVar, fsrEnvVars(t, w, "shop", "crew")[relayVar]); got != crewPlain {
+ t.Fatalf("crew's resealed relay config = %q, want the same value %q", got, crewPlain)
+ }
+ if v := appVars(t, w.fx, "cart")[relayVar]; v.Envelope != cartLegacy || v.SealedTo != "" {
+ t.Fatalf("cart's legacy relay envelope was rewritten (%+v); it was sealed to cart's own key", v)
+ }
+}
+
+// fsrLegacyShop is bab with home (its key registered when withKey), the
+// deployment key, and shop's store granted while shop was placed nowhere.
+// shop is then placed on home by writing the column, as an app placed
+// before fleets had keys. The place door is not used: §5.5 has it refuse a
+// move of an app whose sealed values home's boxes cannot open.
+func fsrLegacyShop(t *testing.T, code string, withKey bool) (*fcmWorld, *objstore.MemProvisioner) {
+ t.Helper()
+ fx, token, _ := fskFixture(t, code)
+ dep := skNewKey(t)
+ fx.srv.cfg.SecretsPub = dep.pub
+ 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)
+ }
+ appconfig.SetBoundSealing(false)
+ t.Cleanup(func() { appconfig.SetBoundSealing(false) })
+ w := &fcmWorld{fx: fx, token: token, fleet: k, depPriv: dep.priv}
+ fake := w.armStore(t, "shop")
+ if status, out := postJSON(t, storeURL(fx, "shop")+"/grant", map[string]any{}, token); status != http.StatusOK {
+ t.Fatalf("grant shop = %d %v", status, out)
+ }
+ return w, fake
+}
+
+// fsrPlaceByColumn writes shop's placement as an app placed before fleets
+// had keys.
+func fsrPlaceByColumn(t *testing.T, w *fcmWorld, fleet string) {
+ t.Helper()
+ if err := w.fx.st.SetAppPlacement(OpsAccountID, "shop", "fleet/"+fleet); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestPlanStorageSkipsKeylessFleet: the storage stage over shop (on a
+// keyless fleet) and cart (on the platform). cart is denied; shop is left
+// exactly as it was, nothing sealed or written; once home has a key, the
+// next pass converges shop too.
+func TestPlanStorageSkipsKeylessFleet(t *testing.T) {
+ w, fake := fsrLegacyShop(t, "code-fsr-plan", false)
+ fsrCart(t, w)
+ if status, out := postJSON(t, storeURL(w.fx, "cart"), map[string]any{}, w.token); status != http.StatusOK {
+ t.Fatalf("declare cart's store = %d %v", status, out)
+ }
+ if status, out := postJSON(t, storeURL(w.fx, "cart")+"/grant", map[string]any{}, w.token); status != http.StatusOK {
+ t.Fatalf("grant cart = %d %v", status, out)
+ }
+ fsrPlaceByColumn(t, w, "home")
+ w.fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := w.fx.account(t)
+ st := storageRow(acct, 2_000_000_000, 1_500_000_000, planNow.Add(-10*24*time.Hour))
+ st.NoticeAt = planNow.Add(-9 * 24 * time.Hour)
+ ctx := context.Background()
+
+ if err := w.fx.srv.convergeStorageDeny(ctx, acct, st, true, planNow); err != nil {
+ t.Fatalf("storage stage: %v", err)
+ }
+ cart := storedRecord(t, w.fx, "cart")
+ if cart.WritesDenied == nil || !hasWriteDeny(t, fake.PolicyFor(cart.Provisioned.IAMUser)) {
+ t.Fatalf("cart, a platform app, was not denied: %+v", cart)
+ }
+ shop := storedRecord(t, w.fx, "shop")
+ if shop.WritesDenied != nil || shop.WritesDenyApplied != nil || hasWriteDeny(t, fake.PolicyFor(shop.Provisioned.IAMUser)) {
+ t.Fatalf("shop, on a keyless fleet, was converged: %+v", shop)
+ }
+
+ skRegister(t, w.fx, w.token, "home", w.fleet)
+ if err := w.fx.srv.convergeStorageDeny(ctx, acct, st, true, planNow.Add(time.Hour)); err != nil {
+ t.Fatalf("storage stage after the key: %v", err)
+ }
+ shop = storedRecord(t, w.fx, "shop")
+ if shop.WritesDenied == nil || shop.WritesDenyApplied == nil || !*shop.WritesDenyApplied || !hasWriteDeny(t, fake.PolicyFor(shop.Provisioned.IAMUser)) {
+ t.Fatalf("shop was not converged on the pass after its fleet got a key: %+v", shop)
+ }
+}
+
+// fsrScanEnforcing is fsrLegacyShop with scanning granted and enforcing on
+// shop's store, and shop then placed on keyless home.
+func fsrScanEnforcing(t *testing.T, code string) (*fcmWorld, *objstore.MemProvisioner) {
+ t.Helper()
+ w, fake := fsrLegacyShop(t, code, false)
+ w.fx.srv.cfg.CallbackSigner = callbackTestSigner(t, testWebhookMaster, "")
+ w.fx.srv.cfg.StoreScanner = objstore.NewMemScanner()
+ enableDeploymentScanning(t, w.fx)
+ grantScanning(t, w.fx, w.token, "shop")
+ if status, out := postJSON(t, scanURL(w.fx, "shop")+"/enforce", map[string]any{"on": true}, w.token); status != http.StatusOK {
+ t.Fatalf("enforce on = %d %v", status, out)
+ }
+ fsrPlaceByColumn(t, w, "home")
+ return w, fake
+}
+
+const fsrEnforcementDeny = "s3:ExistingObjectTag"
+
+// fsrBreakDelivery removes shop's delivered store secret, so the next grant
+// has to mint and seal a new key.
+func fsrBreakDelivery(t *testing.T, w *fcmWorld) {
+ t.Helper()
+ _, _, _, _, secretName := objstore.EnvNames(objstore.DefaultEnvPrefix)
+ if _, err := appconfig.Apply(context.Background(), w.fx.rel, w.fx.sqid, "shop", nil, []string{secretName}); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestScanRevokeOnKeylessFleet: revoking scanning re-mints nothing on a
+// healthy store, so it needs no key and works on a keyless fleet: the
+// record is cleared and the policy's Deny comes out. With the store's
+// delivery broken the regrant would mint, so the door refuses with FSK-C44
+// before it clears anything.
+func TestScanRevokeOnKeylessFleet(t *testing.T) {
+ w, fake := fsrScanEnforcing(t, "code-fsr-scan-revoke")
+ user := storedRecord(t, w.fx, "shop").Provisioned.IAMUser
+
+ broken, _ := fsrScanEnforcing(t, "code-fsr-scan-revoke-broken")
+ fsrBreakDelivery(t, broken)
+ want := "home has no secrets key, so the console cannot deliver a store credential to shop and will not mint one. run carlos fleets secrets-key home <pubkey>"
+ status, out := postJSON(t, scanURL(broken.fx, "shop")+"/revoke", map[string]any{}, broken.token)
+ if status != http.StatusConflict || out["error"] != want {
+ t.Fatalf("revoke that would mint, on a keyless fleet = %d %v, want 409 %q", status, out, want)
+ }
+ if rec := storedRecord(t, broken.fx, "shop"); rec.Scanning == nil || rec.Scanning.Enabled == nil || rec.Scanning.Enforce == nil {
+ t.Fatalf("a refused revoke cleared the record: %+v", rec.Scanning)
+ }
+
+ status, out = postJSON(t, scanURL(w.fx, "shop")+"/revoke", map[string]any{}, w.token)
+ if status != http.StatusOK {
+ t.Fatalf("revoke on a keyless fleet = %d %v, want 200", status, out)
+ }
+ if rec := storedRecord(t, w.fx, "shop"); rec.Scanning != nil && (rec.Scanning.Enabled != nil || rec.Scanning.Enforce != nil) {
+ t.Fatalf("revoke left scanning recorded: %+v", rec.Scanning)
+ }
+ if strings.Contains(fake.PolicyFor(user), fsrEnforcementDeny) {
+ t.Fatalf("revoke left the enforcement deny in the policy:\n%s", fake.PolicyFor(user))
+ }
+}
+
+// TestScanEnforceOffOnKeylessFleet: the same for `scan enforce off`.
+func TestScanEnforceOffOnKeylessFleet(t *testing.T) {
+ w, fake := fsrScanEnforcing(t, "code-fsr-scan-enforce")
+ user := storedRecord(t, w.fx, "shop").Provisioned.IAMUser
+
+ broken, _ := fsrScanEnforcing(t, "code-fsr-scan-enforce-broken")
+ fsrBreakDelivery(t, broken)
+ want := "home has no secrets key, so the console cannot deliver a store credential to shop and will not mint one. run carlos fleets secrets-key home <pubkey>"
+ status, out := postJSON(t, scanURL(broken.fx, "shop")+"/enforce", map[string]any{"on": false}, broken.token)
+ if status != http.StatusConflict || out["error"] != want {
+ t.Fatalf("enforce off that would mint, on a keyless fleet = %d %v, want 409 %q", status, out, want)
+ }
+ if rec := storedRecord(t, broken.fx, "shop"); rec.Scanning == nil || rec.Scanning.Enforce == nil {
+ t.Fatalf("a refused enforce off cleared the record: %+v", rec.Scanning)
+ }
+
+ status, out = postJSON(t, scanURL(w.fx, "shop")+"/enforce", map[string]any{"on": false}, w.token)
+ if status != http.StatusOK {
+ t.Fatalf("enforce off on a keyless fleet = %d %v, want 200", status, out)
+ }
+ if rec := storedRecord(t, w.fx, "shop"); rec.Scanning == nil || rec.Scanning.Enforce != nil {
+ t.Fatalf("enforce off left the deny on the record: %+v", rec.Scanning)
+ }
+ if strings.Contains(fake.PolicyFor(user), fsrEnforcementDeny) {
+ t.Fatalf("enforce off left the enforcement deny in the policy:\n%s", fake.PolicyFor(user))
+ }
+}
+
+// TestTeamEnvironmentRelayOnFleetDoesNotDeadlock: a team's first write into
+// a new environment of shop, with the relay enabled, runs the relay's
+// environment hook under the config PUT's account lock. The hook takes no
+// lock of its own, so the PUT answers, and the environment's identity is
+// sealed to home's key.
+func TestTeamEnvironmentRelayOnFleetDoesNotDeadlock(t *testing.T) {
+ for _, plansOn := range []bool{false, true} {
+ t.Run(fmt.Sprintf("plans=%v", plansOn), func(t *testing.T) {
+ w := fsrRelayWorld(t, fmt.Sprintf("code-fsr-team-relay-%v", plansOn), true)
+ fsrEnableRelay(t, w, "shop")
+ fcmPlans(t, w.fx, plansOn)
+ team := teamToken(t, w.fx.st, OpsAccountID, "alta-shop", "shop", "alta")
+ set := map[string]any{"TEAM_ONLY": map[string]string{"kind": "env", "value": "1"}}
+ status, body := fcmWithin(t, "team environment create", func() (int, string) {
+ s, _, b := rawReq(t, http.MethodPut, configURL(w.fx, "shop"), team, string(mustJSON(t, map[string]any{"environment": "crew", "set": set})))
+ return s, b
+ })
+ if status != http.StatusOK {
+ t.Fatalf("team PUT into a new environment = %d %s", status, body)
+ }
+ w.sealedToFleet(t, "crew's "+relayVar, fsrEnvVars(t, w, "shop", "crew")[relayVar])
+ })
+ }
+}
diff --git a/internal/console/planstorage.go b/internal/console/planstorage.go
index 9c54015a0..4b2b788cb 100644
--- a/internal/console/planstorage.go
+++ b/internal/console/planstorage.go
@@ -40,6 +40,12 @@ func (s *Server) clearStorageDeny(ctx context.Context, acct *Account, now time.T
// convergeStores applies want to every provisioned store of the account.
// Each store is tried; one that fails does not hold the others back
// (Astra plans-4b finding 4).
+//
+// Each app's stores converge under the account lock, from the choice of
+// the app's key through the last write (fleet secrets key spec §5.2.1).
+// The walk is the entry point that takes it: its callers (the grace pass,
+// the keep door, a plan transition) hold the lapse lock, the member lock or
+// the billing hold, never the account lock, so it is taken once.
func (s *Server) convergeStores(ctx context.Context, acct *Account, want bool, st capState, now time.Time) error {
if s.cfg.PlanCatalog == nil || s.cfg.StoreProvisioner == nil {
return nil
@@ -55,11 +61,14 @@ func (s *Server) convergeStores(ctx context.Context, acct *Account, want bool, s
errs = append(errs, fmt.Errorf("%s: %w", app, err))
continue
}
- for _, env := range append([]string{""}, envs...) {
- if err := s.convergeStoreDeny(ctx, acct, app, env, st, want, now); err != nil {
- errs = append(errs, fmt.Errorf("%s/%s: %w", app, env, err))
+ func() {
+ defer s.lockAccount(acct.Sqid)()
+ for _, env := range append([]string{""}, envs...) {
+ if err := s.convergeStoreDeny(ctx, acct, app, env, st, want, now); err != nil {
+ errs = append(errs, fmt.Errorf("%s/%s: %w", app, env, err))
+ }
}
- }
+ }()
}
return errors.Join(errs...)
}
@@ -81,13 +90,14 @@ func (s *Server) convergeStoreDeny(ctx context.Context, acct *Account, app, env
if have == want && applied == want {
return nil
}
- // The app's own key (sealKeyFor). An app whose key cannot be chosen,
- // such as one on a keyless fleet, is left as it is and tried again on
- // the next pass. Task 6b settles this walk's skip and its lock.
+ // The app's own key (sealKeyFor), chosen before the first write, under
+ // the account lock convergeStores holds. An app whose key cannot be
+ // chosen, such as one on a keyless fleet, is skipped with a log line:
+ // nothing is written, so WritesDenyApplied still disagrees and the next
+ // pass tries again. That is the app's state, not a failure of the pass.
sealer, err := s.sealKeyFor(ctx, acct.Sqid, app)
if err != nil {
- log.Printf("console: plan storage %s/%s: no secrets key, store policy left as it is: %v", acct.Sqid, app, err)
- jobFailed(ctx, fmt.Errorf("plan storage %s/%s: no secrets key, store policy left as it is: %w", acct.Sqid, app, err))
+ log.Printf("console: plan storage %s/%s: skipped, no key to seal a store credential to; the next pass tries again: %v", acct.Sqid, app, err)
return nil
}
action, detail := "store.writes_allowed", fmt.Sprintf("plan storage: %d of %d bytes; new uploads allowed again", st.Used, st.Limit)
diff --git a/internal/console/relayenv.go b/internal/console/relayenv.go
index aab5aff05..2f984823d 100644
--- a/internal/console/relayenv.go
+++ b/internal/console/relayenv.go
@@ -41,15 +41,13 @@ func (s *Server) ownedEnvironmentNames(ctx context.Context, acct, app string) ([
// relayApplyConfigIn is relayApplyConfig for one owned environment: its
// own incarnation (drawn once, kept across re-applies so a rotation or a
// region change does not move it), the record's regions, written into
-// env's bundle. It mutates rec.Environments[env]; the caller writes the
-// record.
-func (s *Server) relayApplyConfigIn(ctx context.Context, acct, app string, rec *relay.Record, env string) error {
+// env's bundle, sealed with the app's own sealer (relaySealKey: an owned
+// environment's boxes are the app's). It mutates rec.Environments[env]; the
+// caller writes the record.
+func (s *Server) relayApplyConfigIn(ctx context.Context, sealer appconfig.Sealer, acct, app string, rec *relay.Record, env string) error {
if err := s.requireRelayLease(); err != nil {
return err
}
- if s.cfg.SecretsPub == "" {
- return errRelayNoSealKey
- }
if rec.Environments == nil {
rec.Environments = map[string]*relay.EnvironmentIssue{}
}
@@ -66,11 +64,7 @@ func (s *Server) relayApplyConfigIn(ctx context.Context, acct, app string, rec *
if err != nil {
return err
}
- pub, err := appconfig.ParsePublicKey(s.cfg.SecretsPub, "CARLOS_SECRETS_PUBKEY")
- if err != nil {
- return err
- }
- envelope, err := appconfig.Seal(pub, appconfig.Binding{Account: acct, App: app}, []byte(value))
+ v, err := sealer.Seal(appconfig.Binding{Account: acct, App: app}, []byte(value))
if err != nil {
return err
}
@@ -78,11 +72,11 @@ func (s *Server) relayApplyConfigIn(ctx context.Context, acct, app string, rec *
return err
}
if _, err := appconfig.ApplyEnvironment(ctx, s.cfg.Releases, acct, app, env,
- map[string]appconfig.Var{relayVar: {Kind: "secret", Envelope: envelope}}, nil); err != nil {
+ map[string]appconfig.Var{relayVar: v}, nil); err != nil {
return err
}
issue.IssuedSuffixes = suffixes
- issue.IssuedDigest = relayEnvelopeDigest(envelope)
+ issue.IssuedDigest = relayEnvelopeDigest(v.Envelope)
return nil
}
@@ -108,9 +102,9 @@ func (s *Server) relayUnsetConfigIn(ctx context.Context, acct, app, env string)
}
// relayEnvironmentCurrent reports whether env's bundle holds exactly what
-// the record says was issued to it, given the masters in force:
-// relayConvergeWalk's test, per environment.
-func (s *Server) relayEnvironmentCurrent(ctx context.Context, acct, app string, rec *relay.Record, env string) (bool, error) {
+// the record says was issued to it, given the masters in force, sealed to
+// the app's key now: relayConvergeWalk's test, per environment.
+func (s *Server) relayEnvironmentCurrent(ctx context.Context, sealer appconfig.Sealer, acct, app string, rec *relay.Record, env string) (bool, error) {
issue := rec.Environments[env]
if issue == nil {
return false, nil
@@ -130,7 +124,8 @@ func (s *Server) relayEnvironmentCurrent(ctx context.Context, acct, app string,
v, present := m.Vars[relayVar]
return present && v.Kind == "secret" && v.Envelope != "" &&
maps.Equal(issue.IssuedSuffixes, want) &&
- issue.IssuedDigest != "" && relayEnvelopeDigest(v.Envelope) == issue.IssuedDigest, nil
+ issue.IssuedDigest != "" && relayEnvelopeDigest(v.Envelope) == issue.IssuedDigest &&
+ s.relaySealedToCurrent(v, sealer), nil
}
// relayConvergeEnvironments brings the record's environment identities
@@ -138,8 +133,9 @@ func (s *Server) relayEnvironmentCurrent(ctx context.Context, acct, app string,
// a current identity (issued if not), and every identity whose environment
// is no longer owned is withdrawn (its variable unset, its entry dropped,
// so the next aggregate stops carrying it). It reports whether anything
-// moved; the caller writes the record and publishes.
-func (s *Server) relayConvergeEnvironments(ctx context.Context, acct, app string, rec *relay.Record) (bool, error) {
+// moved; the caller writes the record and publishes. sealer is the app's
+// (relaySealKey), chosen by the caller before its first write.
+func (s *Server) relayConvergeEnvironments(ctx context.Context, sealer appconfig.Sealer, acct, app string, rec *relay.Record) (bool, error) {
owned, err := s.ownedEnvironmentNames(ctx, acct, app)
if err != nil {
return false, err
@@ -148,14 +144,14 @@ func (s *Server) relayConvergeEnvironments(ctx context.Context, acct, app string
changed := false
for _, env := range owned {
isOwned[env] = true
- current, err := s.relayEnvironmentCurrent(ctx, acct, app, rec, env)
+ current, err := s.relayEnvironmentCurrent(ctx, sealer, acct, app, rec, env)
if err != nil {
return changed, err
}
if current {
continue
}
- if err := s.relayApplyConfigIn(ctx, acct, app, rec, env); err != nil {
+ if err := s.relayApplyConfigIn(ctx, sealer, acct, app, rec, env); err != nil {
return changed, err
}
changed = true
@@ -193,6 +189,14 @@ func (s *Server) relayWithdrawEnvironments(ctx context.Context, acct, app string
// (teamcreds.go): with the relay enabled for the app, converge the
// environment set and publish; otherwise nothing. Under the app's lock
// and permit like every relay operation.
+//
+// The app's key (relaySealKey) is chosen after relayReady and before the
+// first write; an app with none gets nothing, and its callers log why. It
+// takes no account lock: its callers hold it (the config PUT for a team
+// write, the environment adopt door), or take it themselves first (the
+// environment fork door, Task 7). The release paths call it unlocked; a
+// release seals nothing unless an owned environment is also missing its
+// identity.
func (s *Server) relayEnvironmentHook(ctx context.Context, acct, app string) error {
if s.cfg.Releases == nil {
return nil
@@ -210,6 +214,10 @@ func (s *Server) relayEnvironmentHook(ctx context.Context, acct, app string) err
}
return err
}
+ sealer, err := s.relaySealKey(ctx, acct, app)
+ if err != nil {
+ return err
+ }
mu := s.relayAppLock(acct, app)
mu.Lock()
defer mu.Unlock()
@@ -221,7 +229,7 @@ func (s *Server) relayEnvironmentHook(ctx context.Context, acct, app string) err
if err != nil || rec == nil || !rec.Enabled {
return err
}
- changed, err := s.relayConvergeEnvironments(ctx, acct, app, rec)
+ changed, err := s.relayConvergeEnvironments(ctx, sealer, acct, app, rec)
if err != nil {
return err
}
diff --git a/internal/console/relayops.go b/internal/console/relayops.go
index 83f08cf55..903426758 100644
--- a/internal/console/relayops.go
+++ b/internal/console/relayops.go
@@ -470,10 +470,12 @@ func (s *Server) relayURLs(region string) []string {
}
}
-// relayReady is the three configuration facts every operation needs before it
-// touches anything: a bucket to write, a region to issue for, and a key to
-// seal with. Checked together, and BEFORE the first write, for storeSealKey's
-// reason: a key minted without delivery is worse than no key at all.
+// relayReady is the two deployment facts every operation needs before it
+// touches anything: a bucket to write and a region to issue for. The third,
+// a key to seal with, is the app's own (relaySealKey), so each operation
+// asks for it per app, right after this and BEFORE the first write, for
+// storeSealKey's reason: a key minted without delivery is worse than no key
+// at all.
func (s *Server) relayReady() error {
if s.cfg.Releases == nil {
return errRelayNoBucket
@@ -481,12 +483,70 @@ func (s *Server) relayReady() error {
if len(s.relayRegions()) == 0 {
return errRelayNoRegions
}
- if s.cfg.SecretsPub == "" {
- return errRelayNoSealKey
- }
return nil
}
+// errRelayKeylessFleet is the relay's answer for an app placed on a fleet
+// with no secrets key (FSK-C46): the door's 409.
+type errRelayKeylessFleet struct{ Fleet, App string }
+
+func (e errRelayKeylessFleet) Error() string {
+ return fmt.Sprintf("%s has no secrets key, so the console cannot deliver a relay key to %s and will not issue one. run carlos fleets secrets-key %s <pubkey>", e.Fleet, e.App, e.Fleet)
+}
+
+// errRelaySealKey is any refusal of relaySealKey: no key could be chosen for
+// the app, so nothing was sealed or written for it. The reconcile reads it
+// as "skip this app until its key is right", not as a failed pass. It says
+// what the error it carries says.
+type errRelaySealKey struct{ err error }
+
+func (e errRelaySealKey) Error() string { return e.err.Error() }
+func (e errRelaySealKey) Unwrap() error { return e.err }
+
+// relaySealKey is sealKeyFor for the relay: the sealer for acct/app's relay
+// credentials, the app's and every owned environment's. sealKeyFor's two
+// configuration refusals become the relay's own answers: errRelayNoSealKey
+// for an app placed nowhere on a console with no CARLOS_SECRETS_PUBKEY, and
+// errRelayKeylessFleet for an app on a fleet with no key. Every refusal comes
+// back as errRelaySealKey.
+//
+// It takes no lock (sealKeyFor's rule). Its callers hold the account lock
+// from here through their write: relayEnable, relayReissue and
+// relayConverge take it; relayEnvironmentHook runs under its caller's.
+func (s *Server) relaySealKey(ctx context.Context, acct, app string) (appconfig.Sealer, error) {
+ sealer, err := s.sealKeyFor(ctx, acct, app)
+ if err == nil {
+ return sealer, nil
+ }
+ var keyless errFleetNoSecretsKey
+ switch {
+ case errors.Is(err, errNoDeploymentKey):
+ err = errRelayNoSealKey
+ case errors.As(err, &keyless):
+ err = errRelayKeylessFleet{Fleet: keyless.Fleet, App: app}
+ }
+ return appconfig.Sealer{}, errRelaySealKey{err}
+}
+
+// relaySealedToCurrent is whether v was sealed to sealer's key, the half of
+// "current" the suffixes and the digest cannot see: an envelope the relay
+// wrote before the app's key changed (a fleet app's, sealed to the
+// deployment key before its fleet had one) matches both and opens on none of
+// the app's boxes. A value written before sealed_to existed names no key;
+// the relay sealed every such value to the deployment key, so that is the
+// key it is read as, and a platform app's legacy envelope stays current.
+func (s *Server) relaySealedToCurrent(v appconfig.Var, sealer appconfig.Sealer) bool {
+ to := v.SealedTo
+ if to == "" {
+ pub, err := s.deploymentSealKey()
+ if err != nil {
+ return false
+ }
+ to = appconfig.KeyFingerprint(pub)
+ }
+ return to == sealer.Fingerprint()
+}
+
// relayResolveRegions turns an app's request into the region list its record
// carries: every armed region in the CONSOLE's order when the caller named
// none, or the named subset — still in the console's order, since that order
@@ -570,25 +630,19 @@ func (s *Server) relayConfigVar(ctx context.Context, acct, app string) (appconfi
return v, ok, nil
}
-// relayApplyConfig derives the app's key, seals it and writes it into the
-// DEFAULT config bundle, recording on the record which identities it just
-// issued. It mutates rec.IssuedSuffixes; the caller writes the record.
-func (s *Server) relayApplyConfig(ctx context.Context, acct, app string, rec *relay.Record) error {
+// relayApplyConfig derives the app's key, seals it with the app's own sealer
+// (relaySealKey) and writes it into the DEFAULT config bundle, recording on
+// the record which identities it just issued. It mutates rec.IssuedSuffixes;
+// the caller writes the record.
+func (s *Server) relayApplyConfig(ctx context.Context, sealer appconfig.Sealer, acct, app string, rec *relay.Record) error {
if err := s.requireRelayLease(); err != nil {
return err
}
- if s.cfg.SecretsPub == "" {
- return errRelayNoSealKey
- }
value, suffixes, err := s.relayConfigValue(ctx, acct, app, rec)
if err != nil {
return err
}
- pub, err := appconfig.ParsePublicKey(s.cfg.SecretsPub, "CARLOS_SECRETS_PUBKEY")
- if err != nil {
- return err
- }
- env, err := appconfig.Seal(pub, appconfig.Binding{Account: acct, App: app}, []byte(value))
+ v, err := sealer.Seal(appconfig.Binding{Account: acct, App: app}, []byte(value))
if err != nil {
return err
}
@@ -596,11 +650,11 @@ func (s *Server) relayApplyConfig(ctx context.Context, acct, app string, rec *re
return err
}
if _, err := appconfig.Apply(ctx, s.cfg.Releases, acct, app,
- map[string]appconfig.Var{relayVar: {Kind: "secret", Envelope: env}}, nil); err != nil {
+ map[string]appconfig.Var{relayVar: v}, nil); err != nil {
return err
}
rec.IssuedSuffixes = suffixes
- rec.IssuedDigest = relayEnvelopeDigest(env)
+ rec.IssuedDigest = relayEnvelopeDigest(v.Envelope)
return nil
}
@@ -983,13 +1037,21 @@ func (s *Server) relayEnable(ctx context.Context, acct *Account, app string, reg
if err != nil {
return nil, err
}
+ // The account lock from the key choice through the last write (fleet
+ // secrets key spec §5.2.1), before the relay's app lock. The only caller
+ // is the enable door, which holds no lock.
+ defer s.lockAccount(acct.Sqid)()
+ sealer, err := s.relaySealKey(ctx, acct.Sqid, app)
+ if err != nil {
+ return nil, err
+ }
mu := s.relayAppLock(acct.Sqid, app)
mu.Lock()
defer mu.Unlock()
var out *relay.Record
err = s.relayAppMutation(ctx, acct.Sqid, app, "relay-enable", func(ctx context.Context) error {
var err error
- out, err = s.relayEnableWalk(ctx, acct, app, want, by)
+ out, err = s.relayEnableWalk(ctx, sealer, acct, app, want, by)
return err
})
if err != nil {
@@ -999,7 +1061,7 @@ func (s *Server) relayEnable(ctx context.Context, acct *Account, app string, reg
}
// relayEnableWalk is relayEnable's body under the app's lock and permit.
-func (s *Server) relayEnableWalk(ctx context.Context, acct *Account, app string, want []string, by string) (*relay.Record, error) {
+func (s *Server) relayEnableWalk(ctx context.Context, sealer appconfig.Sealer, acct *Account, app string, want []string, by string) (*relay.Record, error) {
if err := s.requireRelayLease(); err != nil {
return nil, err
}
@@ -1041,12 +1103,12 @@ func (s *Server) relayEnableWalk(ctx context.Context, acct *Account, app string,
if etag, err = s.relayPutRecord(ctx, acct.Sqid, app, rec, etag); err != nil {
return nil, err
}
- if err := s.relayApplyConfig(ctx, acct.Sqid, app, rec); err != nil {
+ if err := s.relayApplyConfig(ctx, sealer, acct.Sqid, app, rec); err != nil {
return nil, err
}
// Every owned environment gets its own identity beside the app's
// (relayenv.go, team-scoped credentials §3a).
- if _, err := s.relayConvergeEnvironments(ctx, acct.Sqid, app, rec); err != nil {
+ if _, err := s.relayConvergeEnvironments(ctx, sealer, acct.Sqid, app, rec); err != nil {
return nil, err
}
rec.Phase = relayPhaseAggregate
@@ -1442,17 +1504,26 @@ func (s *Server) relayRotate(ctx context.Context, region string) (relayRotateRes
// aggregate does not CHANGE on a rotation (the incarnation is untouched), but
// it is published anyway because the phase walk is what makes the operation
// resumable, and a publish is cheap next to a half-recorded rotation.
+//
+// Each app's own key (relaySealKey), chosen under the account lock, which is
+// held through the app's last write (fleet secrets key spec §5.2.1). The
+// rotation holds no lock between apps.
func (s *Server) relayReissue(ctx context.Context, r relayAppRecord) error {
+ defer s.lockAccount(r.Account)()
+ sealer, err := s.relaySealKey(ctx, r.Account, r.App)
+ if err != nil {
+ return err
+ }
mu := s.relayAppLock(r.Account, r.App)
mu.Lock()
defer mu.Unlock()
return s.relayAppMutation(ctx, r.Account, r.App, "relay-reissue", func(ctx context.Context) error {
- return s.relayReissueWalk(ctx, r)
+ return s.relayReissueWalk(ctx, sealer, r)
})
}
// relayReissueWalk is relayReissue's body under the app's lock and permit.
-func (s *Server) relayReissueWalk(ctx context.Context, r relayAppRecord) error {
+func (s *Server) relayReissueWalk(ctx context.Context, sealer appconfig.Sealer, r relayAppRecord) error {
if err := s.requireRelayLease(); err != nil {
return err
}
@@ -1468,12 +1539,12 @@ func (s *Server) relayReissueWalk(ctx context.Context, r relayAppRecord) error {
if etag, err = s.relayPutRecord(ctx, r.Account, r.App, rec, etag); err != nil {
return err
}
- if err := s.relayApplyConfig(ctx, r.Account, r.App, rec); err != nil {
+ if err := s.relayApplyConfig(ctx, sealer, r.Account, r.App, rec); err != nil {
return err
}
// The environments' identities re-issue from the master in force now
// as the app's does.
- if _, err := s.relayConvergeEnvironments(ctx, r.Account, r.App, rec); err != nil {
+ if _, err := s.relayConvergeEnvironments(ctx, sealer, r.Account, r.App, rec); err != nil {
return err
}
rec.Phase = relayPhaseAggregate
@@ -1523,6 +1594,14 @@ func (s *Server) relayReconcile(ctx context.Context) error {
var advanced []pending
for _, r := range recs {
etag, changed, err := s.relayConverge(ctx, r)
+ var noKey errRelaySealKey
+ if errors.As(err, &noKey) {
+ // No key could be chosen for this app (a keyless fleet, say):
+ // nothing was written for it, and the next pass tries again.
+ // The app's state, not a failure of the pass.
+ log.Printf("console: relay reconcile %s/%s: skipped, no key to seal to: %v", r.Account, r.App, err)
+ continue
+ }
if err != nil {
log.Printf("console: relay reconcile %s/%s: %v", r.Account, r.App, err)
jobFailed(ctx, fmt.Errorf("relay reconcile %s/%s: %w", r.Account, r.App, err))
@@ -1547,7 +1626,12 @@ func (s *Server) relayReconcile(ctx context.Context) error {
// relayConverge brings ONE record's config into agreement with it, returning
// the etag it left the record at and whether the record still needs marking
// done after the publish.
+//
+// Under the account lock (fleet secrets key spec §5.2.1), taken here per
+// app before the relay's app lock: the reconcile holds no lock between
+// apps, and the walk chooses the app's key under it.
func (s *Server) relayConverge(ctx context.Context, r relayAppRecord) (string, bool, error) {
+ defer s.lockAccount(r.Account)()
mu := s.relayAppLock(r.Account, r.App)
mu.Lock()
defer mu.Unlock()
@@ -1578,6 +1662,13 @@ func (s *Server) relayConvergeWalk(ctx context.Context, r relayAppRecord) (strin
return "", false, err
}
if rec.Enabled {
+ // The app's own key, chosen before anything is written for it. An
+ // app with none (errRelaySealKey) is skipped by the reconcile and
+ // tried again on the next pass.
+ sealer, err := s.relaySealKey(ctx, r.Account, r.App)
+ if err != nil {
+ return "", false, err
+ }
want, err := s.relayExpectedSuffixes(ctx, r.Account, r.App, rec)
if err != nil {
return "", false, err
@@ -1592,14 +1683,18 @@ func (s *Server) relayConvergeWalk(ctx context.Context, r relayAppRecord) (strin
// the exact envelope this console last wrote (a straggler write from
// a superseded console, or a member setting CARLOS_RELAY themselves,
// moves that). A record from before IssuedDigest existed has none, so
- // it re-applies once and then carries one.
+ // it re-applies once and then carries one. And the envelope is sealed
+ // to the key the app's boxes hold now (relaySealedToCurrent): one
+ // sealed before the app's fleet had a key is re-sealed, same value,
+ // once the key is registered.
current := present && v.Kind == "secret" && v.Envelope != "" &&
maps.Equal(rec.IssuedSuffixes, want) &&
- rec.IssuedDigest != "" && relayEnvelopeDigest(v.Envelope) == rec.IssuedDigest
+ rec.IssuedDigest != "" && relayEnvelopeDigest(v.Envelope) == rec.IssuedDigest &&
+ s.relaySealedToCurrent(v, sealer)
// The environment set converges with the app's own config
// (relayenv.go): an owned environment with no current identity
// gets one, a released one loses its own.
- envChanged, err := s.relayConvergeEnvironments(ctx, r.Account, r.App, rec)
+ envChanged, err := s.relayConvergeEnvironments(ctx, sealer, r.Account, r.App, rec)
if err != nil {
return "", false, err
}
@@ -1607,7 +1702,7 @@ func (s *Server) relayConvergeWalk(ctx context.Context, r relayAppRecord) (strin
return etag, false, nil
}
if !current {
- if err := s.relayApplyConfig(ctx, r.Account, r.App, rec); err != nil {
+ if err := s.relayApplyConfig(ctx, sealer, r.Account, r.App, rec); err != nil {
return "", false, err
}
}
diff --git a/internal/console/relayops_test.go b/internal/console/relayops_test.go
index 603151c2e..8d61d6d0b 100644
--- a/internal/console/relayops_test.go
+++ b/internal/console/relayops_test.go
@@ -275,6 +275,11 @@ func TestRelayPublishAggregateIsEtagFirst(t *testing.T) {
fx, _ := relayFixture(t, "code-relay-etag")
ctx := context.Background()
acct := fx.account(t)
+ // meet is a live app: the relay seals each app's key to the key its
+ // own row chooses (sealKeyFor), and an app with no row has none.
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "meet", "alice@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
if _, err := fx.srv.relayEnable(ctx, acct, "titogo", nil, "alice@keymail.dev"); err != nil {
t.Fatal(err)
@@ -427,7 +432,12 @@ func TestRelayReconcileRepairsDeletionWithoutRecord(t *testing.T) {
// deletion walk sweeps the record; publishing right after is what makes the
// app's credentials stop verifying while the operator is still watching.
func TestRelayPurgeRepublishesTheAggregate(t *testing.T) {
- fx, c, csrf := trashPageFixture(t)
+ // trashPageFixture's steps, with the relay enabled while kass is still
+ // live: an app in the Trash has no seal key (sealKeyFor reads live
+ // rows), so the enable comes first, as it would in life.
+ fx := newConsoleFixture(t)
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-trash")
armRelay(t, fx)
ctx := context.Background()
@@ -437,6 +447,8 @@ func TestRelayPurgeRepublishesTheAggregate(t *testing.T) {
if _, ok := relayAuthority(t, fx).Lookup(fx.sqid, "kass"); !ok {
t.Fatal("the enable did not publish")
}
+ trashKass(t, fx, "paul@keymail.dev", time.Now())
+ csrf := sessionToken(t, fx, c)
status, _, body := postGated(t, fx, c, fx.u("/trash/delete"),
url.Values{"csrf": {csrf}, "app": {"kass"}, "confirm": {"kass"}})
diff --git a/internal/console/sealkey_guard_test.go b/internal/console/sealkey_guard_test.go
new file mode 100644
index 000000000..e8ee0b230
--- /dev/null
+++ b/internal/console/sealkey_guard_test.go
@@ -0,0 +1,456 @@
+package console
+
+// TestOnlySealKeyForBuildsSealers is the guard of I1 (fleet secrets key spec
+// §2.1): the only keys anything in this module seals an app's config to are
+// the ones sealKeyFor chooses (the app's fleet's key or the deployment key),
+// plus the few seals that predate it and are pinned here by name. It
+// type-checks every non-test package that can reach a sealing function and
+// collects, by object identity (types.Info.Uses resolving to the function,
+// so an aliased import, a same-package call and a function value all
+// count), every use of:
+//
+// - appconfig.Seal, appconfig.SealBound, appconfig.SealUnbound and
+// appconfig.NewSealer, which seal to whatever key they are handed;
+// - archive.Seal (internal/moves/archive), which does the same for a move;
+// - console's chooseSealKey, sealKeyFor without the sealer: whoever reads
+// its key could build one.
+//
+// Each is allowed only inside the functions sealGuardAllowed names for it.
+// (appconfig.Sealer).Seal is allowed anywhere: a Sealer comes only from
+// NewSealer, so it seals only to a key an allowed caller chose. That rests on
+// two more checks: a composite literal of appconfig.Sealer with any field set
+// appears only in NewSealer (an empty one is the zero Sealer, which refuses
+// every binding and seals nothing), and the struct has no exported field.
+//
+// Negative fixtures (testdata/sealguard) are laid over the real packages with
+// go list's overlay, so each resolves exactly as real code would, and each
+// must be named. A sealer used for another app is refused at run time, not
+// here (ErrSealerBinding); the last subtest pins that.
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "go/types"
+ "os"
+ "path/filepath"
+ "slices"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+
+ "golang.org/x/tools/go/packages"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+)
+
+const (
+ sgModule = "github.com/carlosframework/platform"
+ sgAppconfig = sgModule + "/internal/appconfig"
+ sgArchive = sgModule + "/internal/moves/archive"
+ sgConsole = sgModule + "/internal/console"
+ sgHost = sgModule + "/internal/host"
+
+ sgSeal = sgAppconfig + ".Seal"
+ sgSealBound = sgAppconfig + ".SealBound"
+ sgSealUnbound = sgAppconfig + ".SealUnbound"
+ sgNewSealer = sgAppconfig + ".NewSealer"
+ sgArchiveSeal = sgArchive + ".Seal"
+ sgChooseSealKey = "(*" + sgConsole + ".Server).chooseSealKey"
+)
+
+// sgTargets is every guarded function, by types.Func.FullName.
+var sgTargets = []string{sgSeal, sgSealBound, sgSealUnbound, sgNewSealer, sgArchiveSeal, sgChooseSealKey}
+
+// sealGuardAllowed is the allowlist: an enclosing function (FullName) and
+// the guarded functions it may use. Nothing else may use any of them.
+var sealGuardAllowed = map[string][]string{
+ // The envelope's own two writers.
+ "(" + sgAppconfig + ".Sealer).Seal": {sgSealBound, sgSealUnbound},
+ sgSeal: {sgSealBound, sgSealUnbound},
+ // The one choice of key (sealkey.go).
+ "(*" + sgConsole + ".Server).sealKeyFor": {sgNewSealer, sgChooseSealKey},
+ // The config PUT's check of what a client sealed: it reads the choice
+ // for the fleet's name in its refusals and never seals (ledger ruling,
+ // Task 5).
+ "(*" + sgConsole + ".Server).configCheckSealedTo": {sgChooseSealKey},
+ // The CLI, sealing to the key the console's config GET served.
+ sgModule + ".sealSecretAPI": {sgSealBound, sgSealUnbound},
+ // The CLI's direct-bucket mode (Task 8 adds its key checks).
+ sgModule + ".runSecretsSet": {sgSeal},
+ // A platform move's archive, sealed to the deployment key on the box
+ // (fleet instances are not moved).
+ sgArchiveSeal: {sgSealBound},
+ "(*" + sgHost + ".movesWorker).buildArchive": {sgArchiveSeal},
+ "(*" + sgHost + ".movesWorker).offlineArchive": {sgArchiveSeal},
+}
+
+// sgFinding is one use the allowlist does not admit.
+type sgFinding struct {
+ pos token.Position
+ what string // the guarded function, or "appconfig.Sealer{...}"
+ in string // the enclosing function's FullName, "" at package level
+}
+
+func (f sgFinding) String() string {
+ in := f.in
+ if in == "" {
+ in = "package level"
+ }
+ return fmt.Sprintf("%s:%d: %s in %s", f.pos.Filename, f.pos.Line, f.what, in)
+}
+
+func sgRoot(t *testing.T) string {
+ t.Helper()
+ root, err := filepath.Abs(filepath.Join("..", ".."))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return root
+}
+
+// sgEnv type-checks the files a linux/amd64 build compiles. Files left out
+// by build constraints are checked by sgIgnoredFiles.
+func sgEnv() []string {
+ return append(os.Environ(), "GOOS=linux", "GOARCH=amd64", "CGO_ENABLED=0")
+}
+
+// sgReaches reports whether a package can name a guarded function: it is
+// one of their packages, or it imports one. A package that imports neither
+// cannot refer to their objects (chooseSealKey is unexported).
+func sgReaches(path string, imports map[string]*packages.Package) bool {
+ for _, p := range []string{sgAppconfig, sgArchive, sgConsole} {
+ if path == p {
+ return true
+ }
+ }
+ return imports[sgAppconfig] != nil || imports[sgArchive] != nil
+}
+
+// sgList is every package of the module, names, imports and files only.
+func sgList(t *testing.T, root string) []*packages.Package {
+ t.Helper()
+ cfg := &packages.Config{Dir: root, Env: sgEnv(),
+ Mode: packages.NeedName | packages.NeedImports | packages.NeedFiles}
+ pkgs, err := packages.Load(cfg, "./...")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if packages.PrintErrors(pkgs) > 0 {
+ t.Fatal("listing the module failed")
+ }
+ return pkgs
+}
+
+// sgLoad type-checks the named packages from source, with overlay.
+func sgLoad(t *testing.T, root string, overlay map[string][]byte, paths []string) []*packages.Package {
+ t.Helper()
+ cfg := &packages.Config{Dir: root, Env: sgEnv(), Overlay: overlay,
+ Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax |
+ packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports}
+ pkgs, err := packages.Load(cfg, paths...)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if packages.PrintErrors(pkgs) > 0 {
+ t.Fatal("type-checking the guarded packages failed")
+ }
+ return pkgs
+}
+
+// sgIsSealer reports whether typ is appconfig.Sealer.
+func sgIsSealer(typ types.Type) bool {
+ n, ok := types.Unalias(typ).(*types.Named)
+ return ok && n.Obj().Pkg() != nil && n.Obj().Pkg().Path() == sgAppconfig && n.Obj().Name() == "Sealer"
+}
+
+// sgScan returns every use the allowlist does not admit, and how often each
+// allowed (enclosing, target) pair was seen. Positions are relative to root.
+func sgScan(root string, pkgs []*packages.Package) ([]sgFinding, map[string]int) {
+ targets := map[string]bool{}
+ for _, name := range sgTargets {
+ targets[name] = true
+ }
+ var out []sgFinding
+ seen := map[string]int{}
+ rel := func(p token.Position) token.Position {
+ if r, err := filepath.Rel(root, p.Filename); err == nil {
+ p.Filename = r
+ }
+ return p
+ }
+ for _, pkg := range pkgs {
+ info := pkg.TypesInfo
+ for _, file := range pkg.Syntax {
+ for _, decl := range file.Decls {
+ in := ""
+ if fd, ok := decl.(*ast.FuncDecl); ok {
+ if fn, ok := info.Defs[fd.Name].(*types.Func); ok {
+ in = fn.FullName()
+ }
+ }
+ ast.Inspect(decl, func(n ast.Node) bool {
+ switch n := n.(type) {
+ case *ast.Ident:
+ fn, ok := info.Uses[n].(*types.Func)
+ if !ok {
+ return true
+ }
+ name := fn.Origin().FullName()
+ if !targets[name] {
+ return true
+ }
+ if slices.Contains(sealGuardAllowed[in], name) {
+ seen[in+" -> "+name]++
+ return true
+ }
+ out = append(out, sgFinding{rel(pkg.Fset.Position(n.Pos())), name, in})
+ case *ast.CompositeLit:
+ tv, ok := info.Types[n]
+ if !ok || !sgIsSealer(tv.Type) || len(n.Elts) == 0 {
+ return true
+ }
+ if in == sgNewSealer {
+ seen[in+" -> appconfig.Sealer{...}"]++
+ return true
+ }
+ out = append(out, sgFinding{rel(pkg.Fset.Position(n.Pos())), "appconfig.Sealer{...}", in})
+ }
+ return true
+ })
+ }
+ }
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].String() < out[j].String() })
+ return out, seen
+}
+
+// sgIgnoredFiles names every non-test file a linux build leaves out (build
+// constraints) that the type-checked scan therefore never sees, if it could
+// name a guarded function: it imports appconfig or archive, or it belongs to
+// appconfig, archive or console and mentions a guarded name. A real hit means
+// the guard needs a load under that file's GOOS or tags.
+func sgIgnoredFiles(t *testing.T, root string, pkgs []*packages.Package) []string {
+ t.Helper()
+ names := []string{"chooseSealKey", "NewSealer", "SealBound", "SealUnbound", "Seal(", "Sealer{"}
+ var out []string
+ for _, pkg := range pkgs {
+ for _, path := range pkg.IgnoredFiles {
+ if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
+ continue
+ }
+ src, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, err := parser.ParseFile(token.NewFileSet(), path, src, parser.ImportsOnly)
+ if err != nil {
+ t.Fatalf("%s: %v", path, err)
+ }
+ hit := ""
+ for _, imp := range f.Imports {
+ if p, _ := strconv.Unquote(imp.Path.Value); p == sgAppconfig || p == sgArchive {
+ hit = "imports " + p
+ }
+ }
+ if hit == "" && sgReaches(pkg.PkgPath, nil) {
+ for _, name := range names {
+ if bytes.Contains(src, []byte(name)) {
+ hit = "mentions " + name
+ break
+ }
+ }
+ }
+ if hit != "" {
+ r, _ := filepath.Rel(root, path)
+ out = append(out, r+": "+hit)
+ }
+ }
+ }
+ sort.Strings(out)
+ return out
+}
+
+func TestOnlySealKeyForBuildsSealers(t *testing.T) {
+ root := sgRoot(t)
+ listed := sgList(t, root)
+ var paths []string
+ for _, p := range listed {
+ if sgReaches(p.PkgPath, p.Imports) {
+ paths = append(paths, p.PkgPath)
+ }
+ }
+ pkgs := sgLoad(t, root, nil, paths)
+ t.Logf("type-checked %d package(s) that can reach a sealing function: %s", len(pkgs), strings.Join(paths, " "))
+
+ t.Run("targets resolve", func(t *testing.T) {
+ // A renamed or moved function would otherwise leave the guard
+ // watching a name nothing has.
+ found := map[string]bool{}
+ for _, pkg := range pkgs {
+ for _, obj := range pkg.TypesInfo.Defs {
+ if fn, ok := obj.(*types.Func); ok {
+ found[fn.FullName()] = true
+ }
+ }
+ }
+ for _, name := range sgTargets {
+ if !found[name] {
+ t.Errorf("the guard names %s, which the module no longer declares", name)
+ }
+ }
+ for in := range sealGuardAllowed {
+ if !found[in] {
+ t.Errorf("the allowlist names %s, which the module no longer declares", in)
+ }
+ }
+ })
+
+ t.Run("Sealer has no exported field", func(t *testing.T) {
+ for _, pkg := range pkgs {
+ if pkg.PkgPath != sgAppconfig {
+ continue
+ }
+ st, ok := pkg.Types.Scope().Lookup("Sealer").Type().Underlying().(*types.Struct)
+ if !ok {
+ t.Fatal("appconfig.Sealer is not a struct")
+ }
+ for i := range st.NumFields() {
+ if f := st.Field(i); f.Exported() {
+ t.Errorf("appconfig.Sealer has an exported field %s: a literal outside appconfig could then build a sealer for any key", f.Name())
+ }
+ }
+ return
+ }
+ t.Fatal("appconfig was not loaded")
+ })
+
+ t.Run("every use is allowed", func(t *testing.T) {
+ findings, seen := sgScan(root, pkgs)
+ for _, f := range findings {
+ t.Errorf("%s: only sealKeyFor chooses a seal key (fleet secrets key spec §2.1); seal through its Sealer, or add the function to sealGuardAllowed with a ruling", f)
+ }
+ // The scan resolves identities at all: sealKeyFor's own sealer is
+ // found where it is allowed.
+ if seen["(*"+sgConsole+".Server).sealKeyFor -> "+sgNewSealer] == 0 {
+ t.Errorf("the scan did not see sealKeyFor's NewSealer; it is not resolving uses (seen: %v)", seen)
+ }
+ var used []string
+ for k, n := range seen {
+ used = append(used, fmt.Sprintf("%s: %d", k, n))
+ }
+ sort.Strings(used)
+ t.Logf("allowed uses:\n%s", strings.Join(used, "\n"))
+ })
+
+ t.Run("build-constrained files", func(t *testing.T) {
+ for _, f := range sgIgnoredFiles(t, root, listed) {
+ t.Errorf("%s, and a linux build leaves it out, so the guard never type-checks it: load it under its own GOOS or tags here", f)
+ }
+ })
+
+ t.Run("fixtures are named", func(t *testing.T) {
+ overlay, want := sgFixtures(t, root)
+ fpkgs := sgLoad(t, root, overlay, []string{sgConsole, sgAppconfig})
+ findings, _ := sgScan(root, fpkgs)
+ var got []string
+ for _, f := range findings {
+ got = append(got, f.what+" in "+f.in)
+ }
+ for _, w := range want {
+ if !slices.Contains(got, w) {
+ t.Errorf("the guard did not name the fixture's %s (it named %v)", w, got)
+ }
+ }
+ for _, g := range got {
+ if !slices.Contains(want, g) {
+ t.Errorf("the guard named %s, which no fixture plants", g)
+ }
+ }
+ })
+
+ t.Run("a sealer for one app refuses another", func(t *testing.T) {
+ _, pubB64, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := appconfig.ParsePublicKey(pubB64, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ shop := appconfig.NewSealer(pub, appconfig.Binding{Account: "bab", App: "shop"}, true)
+ if _, err := shop.Seal(appconfig.Binding{Account: "bab", App: "other"}, []byte("x")); !errors.Is(err, appconfig.ErrSealerBinding) {
+ t.Fatalf("bab/shop's sealer sealing for bab/other = %v, want ErrSealerBinding", err)
+ }
+ var zero appconfig.Sealer
+ for _, b := range []appconfig.Binding{{}, {Account: "bab", App: "shop"}} {
+ if _, err := zero.Seal(b, []byte("x")); err == nil {
+ t.Fatalf("the zero Sealer sealed for %+v; the guard allows it anywhere because it seals nothing", b)
+ }
+ }
+ })
+}
+
+// sgFixtures lays each negative fixture over the package it targets and
+// returns the overlay and the findings it must produce ("what in enclosing").
+//
+// - arbitrary: a console function sealing to a key of its own choosing;
+// - aliased: the same through `ac "…/internal/appconfig"`, a call and a
+// package-level function value;
+// - sealkey: a second NewSealer in sealkey.go, outside sealKeyFor, built
+// from chooseSealKey (the fixture is appended to the real file);
+// - ctor: a second constructor inside appconfig, returning Sealer{...};
+// - choose: chooseSealKey called from a console function that is neither
+// sealKeyFor nor the config PUT's check.
+func sgFixtures(t *testing.T, root string) (map[string][]byte, []string) {
+ t.Helper()
+ dir := filepath.Join(root, "internal", "console", "testdata", "sealguard")
+ read := func(name string) []byte {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join(dir, name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+ }
+ consoleDir := filepath.Join(root, "internal", "console")
+ appconfigDir := filepath.Join(root, "internal", "appconfig")
+ overlay := map[string][]byte{
+ filepath.Join(consoleDir, "zz_sealguard_arbitrary.go"): read("arbitrary/arbitrary.go"),
+ filepath.Join(consoleDir, "zz_sealguard_aliased.go"): read("aliased/aliased.go"),
+ filepath.Join(consoleDir, "zz_sealguard_choose.go"): read("choose/choose.go"),
+ filepath.Join(appconfigDir, "zz_sealguard_ctor.go"): read("ctor/ctor.go"),
+ }
+ // The sealkey fixture's declarations go at the end of the real
+ // sealkey.go, whose imports they share.
+ sealkeyPath := filepath.Join(consoleDir, "sealkey.go")
+ real, err := os.ReadFile(sealkeyPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fixture := read("sealkey/sealkey.go")
+ f, err := parser.ParseFile(token.NewFileSet(), "sealkey.go", fixture, parser.ImportsOnly)
+ if err != nil {
+ t.Fatal(err)
+ }
+ end := f.Name.End()
+ if len(f.Decls) > 0 {
+ end = f.Decls[len(f.Decls)-1].End()
+ }
+ overlay[sealkeyPath] = append(append(append([]byte{}, real...), '\n'), fixture[end-1:]...)
+
+ server := "(*" + sgConsole + ".Server)"
+ return overlay, []string{
+ sgNewSealer + " in " + sgConsole + ".sealGuardArbitrary",
+ sgSealBound + " in " + sgConsole + ".sealGuardAliased",
+ sgSeal + " in ",
+ sgNewSealer + " in " + server + ".sealKeyForOtherApp",
+ sgChooseSealKey + " in " + server + ".sealKeyForOtherApp",
+ "appconfig.Sealer{...} in " + sgAppconfig + ".sealGuardSealer",
+ sgChooseSealKey + " in " + server + ".sealGuardChoose",
+ }
+}
diff --git a/internal/console/testdata/sealguard/aliased/aliased.go b/internal/console/testdata/sealguard/aliased/aliased.go
new file mode 100644
index 000000000..552a34402
--- /dev/null
+++ b/internal/console/testdata/sealguard/aliased/aliased.go
@@ -0,0 +1,16 @@
+// A negative fixture of TestOnlySealKeyForBuildsSealers, laid over
+// internal/console: the same seal through an aliased import, as a call and
+// as a package-level function value.
+package console
+
+import (
+ "crypto/ecdh"
+
+ ac "github.com/carlosframework/platform/internal/appconfig"
+)
+
+var sealGuardValue = ac.Seal
+
+func sealGuardAliased(pub *ecdh.PublicKey, plaintext []byte) (string, error) {
+ return ac.SealBound(pub, ac.Binding{Account: "bab", App: "shop"}, plaintext)
+}
diff --git a/internal/console/testdata/sealguard/arbitrary/arbitrary.go b/internal/console/testdata/sealguard/arbitrary/arbitrary.go
new file mode 100644
index 000000000..7025027b1
--- /dev/null
+++ b/internal/console/testdata/sealguard/arbitrary/arbitrary.go
@@ -0,0 +1,14 @@
+// A negative fixture of TestOnlySealKeyForBuildsSealers, laid over
+// internal/console: a seal to a key of the caller's own choosing.
+package console
+
+import "github.com/carlosframework/platform/internal/appconfig"
+
+func sealGuardArbitrary(pubB64 string, plaintext []byte) (appconfig.Var, error) {
+ pub, err := appconfig.ParsePublicKey(pubB64, "fixture")
+ if err != nil {
+ return appconfig.Var{}, err
+ }
+ b := appconfig.Binding{Account: "bab", App: "shop"}
+ return appconfig.NewSealer(pub, b, true).Seal(b, plaintext)
+}
diff --git a/internal/console/testdata/sealguard/choose/choose.go b/internal/console/testdata/sealguard/choose/choose.go
new file mode 100644
index 000000000..431b4c765
--- /dev/null
+++ b/internal/console/testdata/sealguard/choose/choose.go
@@ -0,0 +1,11 @@
+// A negative fixture of TestOnlySealKeyForBuildsSealers, laid over
+// internal/console: chooseSealKey read outside sealKeyFor and the config
+// PUT's check.
+package console
+
+import "context"
+
+func (s *Server) sealGuardChoose(ctx context.Context, acctSqid, app string) (string, error) {
+ c, err := s.chooseSealKey(ctx, acctSqid, app)
+ return c.fleet, err
+}
diff --git a/internal/console/testdata/sealguard/ctor/ctor.go b/internal/console/testdata/sealguard/ctor/ctor.go
new file mode 100644
index 000000000..f13eb831c
--- /dev/null
+++ b/internal/console/testdata/sealguard/ctor/ctor.go
@@ -0,0 +1,9 @@
+// A negative fixture of TestOnlySealKeyForBuildsSealers, laid over
+// internal/appconfig: a second constructor that builds a Sealer literal.
+package appconfig
+
+import "crypto/ecdh"
+
+func sealGuardSealer(pub *ecdh.PublicKey, b Binding) Sealer {
+ return Sealer{pub: pub, binding: b, bound: true}
+}
diff --git a/internal/console/testdata/sealguard/sealkey/sealkey.go b/internal/console/testdata/sealguard/sealkey/sealkey.go
new file mode 100644
index 000000000..e523ddf12
--- /dev/null
+++ b/internal/console/testdata/sealguard/sealkey/sealkey.go
@@ -0,0 +1,19 @@
+// A negative fixture of TestOnlySealKeyForBuildsSealers. Its declarations
+// are appended to the real internal/console/sealkey.go: a second NewSealer
+// in that file, outside sealKeyFor.
+package console
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+)
+
+// sealKeyForOtherApp reuses the app's choice for another app's binding.
+func (s *Server) sealKeyForOtherApp(ctx context.Context, acctSqid, app, other string) (appconfig.Sealer, error) {
+ c, err := s.chooseSealKey(ctx, acctSqid, app)
+ if err != nil {
+ return appconfig.Sealer{}, err
+ }
+ return appconfig.NewSealer(c.pub, appconfig.Binding{Account: c.sqid, App: other}, c.bound), nil
+}
diff --git a/internal/objstore/walk.go b/internal/objstore/walk.go
index baaa15f46..9f7bd0487 100644
--- a/internal/objstore/walk.go
+++ b/internal/objstore/walk.go
@@ -130,6 +130,24 @@ func EnvDelivered(ctx context.Context, s release.Store, acct, app, prefix string
return EnvDeliveredIn(ctx, s, acct, app, "", prefix, wantEndpoint)
}
+// GrantHealthy is the grant walk's idempotence short-circuit, asked from
+// outside: whether a grant of rec (acct/app's store in env) run now stops
+// after rewriting the policy, minting and sealing nothing. That is the case
+// when rec is provisioned with d's endpoint and every delivered var is
+// present (EnvDeliveredIn). A caller that only needs the policy rewritten
+// (the console's scan revoke and enforce doors) needs a key to seal to only
+// when this is false.
+func GrantHealthy(ctx context.Context, s release.Store, d Deployment, rec *Record, acct, app, env string) (bool, error) {
+ if rec == nil || rec.Declared == nil || rec.Provisioned == nil || rec.Provisioned.Endpoint != d.Endpoint {
+ return false, nil
+ }
+ missing, err := EnvDeliveredIn(ctx, s, acct, app, env, rec.Declared.EnvPrefix, d.Endpoint != "")
+ if err != nil {
+ return false, err
+ }
+ return len(missing) == 0, nil
+}
+
// EnvDeliveredIn is EnvDelivered against the bundle a store actually delivers
// into: the app's default bundle for the app's own store, and the named
// environment's bundle for an environment store. Reading the default bundle
@@ -304,14 +322,10 @@ func claimRawGrantIn(ctx context.Context, s release.Store, p Provisioner, d Depl
// deployment has since changed or dropped means it is reaching for the
// wrong one, which only a re-walk (which rewrites the set, and unsets
// _ENDPOINT when there is no longer an endpoint) can put right.
- if rec.Provisioned != nil && rec.Provisioned.Endpoint == d.Endpoint {
- missing, err := EnvDeliveredIn(ctx, s, acct, app, env, rec.Declared.EnvPrefix, d.Endpoint != "")
- if err != nil {
- return nil, err
- }
- if len(missing) == 0 {
- return rec, nil
- }
+ if healthy, err := GrantHealthy(ctx, s, d, rec, acct, app, env); err != nil {
+ return nil, err
+ } else if healthy {
+ return rec, nil
}
// 3. the bucket
region, err := p.EnsureBucket(ctx, bucket)
@@ -855,8 +869,9 @@ func deleteRecordIfUnchanged(ctx context.Context, s release.Store, acct, app, en
// writeEnv delivers the whole coordinate set in ONE appconfig.Apply — one CAS
// write, so an app never reads a bucket name paired with the previous key.
-// Both key halves are sealed for the deployment's secrets key; the plaintext
-// secret exists nowhere else, in no other object and no log line.
+// Both key halves are sealed by seal, the app's own sealer (the console's
+// sealKeyFor); the plaintext secret exists nowhere else, in no other object
+// and no log line.
//
// A deployment with no endpoint UNSETS the endpoint variable rather than
// leaving whatever is there: dropping an endpoint override is a real change