carlos / platform Public

sealKeyFor: the one choice of seal key for an app (the fleet's own key, checked to be the account's, or the deployment key; a keyless fleet, another account's fleet, an unknown account or app is a refusal, never a fallback), served by the config GET (secrets_keyless_fleet on a keyless fleet) and checked by the config PUT against each secret's sealed_to under the account lock (FSK-C37 to C43)

The PUT takes s.lockAccount at the door only for a request carrying a
sealed value, before teamApplyEnvironment's app lock, and holds it through
Apply/ApplyEnvironment; nothing on that path takes the account lock again
(planLock is only on the create doors). A fleet app's secret must carry
sealed_to equal to the fleet key's fingerprint and be v2; a platform app's
may omit it (older CLIs) but not name another key. The CLI sends the
fingerprint of the key it sealed with, the terminal override included, and
names the keyless fleet in the fix. backfillAppPlacements writes the
placement column from routes in the fleet owner backfill's goroutine
(ruling R-1). appconfig.EnvelopeBound reads the envelope version.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev e2b7e42415ae31a550ba2c38ca45ec0f87a292fb parent ec89355
11 files changed, +1,128 −50
  • apimode.go +15 −9
  • apimode_test.go +3 −3
  • appconfig_cli.go +36 −20
  • approved_fleet_secrets_copy_test.go +4 −1
  • cmd/console/main.go +6 −0
  • fleets_secrets_key_cli_test.go +76 −0
  • internal/appconfig/crypto.go +13 −0
  • internal/appconfig/crypto_bind_test.go +17 −0
  • internal/console/apiconfig.go +160 −17
  • internal/console/sealkey.go +248 −0
  • internal/console/sealkey_test.go +550 −0

Intent

Human

<task-notification> <task-id>ab16a4d6efd90caa1</task-id> <tool-use-id>toolu_01TUHuLrm8eQq9N2VWRewjdF</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/ab16a4d6efd90caa1.output</output-file> <status>completed</status> <summary>Agent "Implement Task 4: CLI commands" 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: ec893556. The `packed-refs.lock` hook error printed, but `git log -1` shows the commit exists. Tests: the new CLI tests, the copy gate (FSK-C12 to C36 built) and the related fleet/usage/census/claim tests pass, plus a wider `Copy|Scan|Moves|Doc` run. The new tests run the real verbs against a real console. Builds and vet are clean on linux, darwin, windows and linux-arm64. The Go commands ran with the sandbox disabled because the sandbox makes the Go cache read-only. Concerns: 1. The deck has no row for "the console could not list the stale values" (answer's `stale` absent). The CLI prints nothing about stale in that case, so a bare "registered" line can read as nothing stale. 2. The deck doesn't say how to join vars or whether to indent. I print one unindented line per app per kind, with vars joined by ", ". 3. C24 ("no fleet called X") fires on the door's plain 404, which an unknown account also produces. A wrong `--account` can therefore read as a missing fleet. 4. `docs/site/cli.md` and `README.md` still mention `secrets genkey` only, with no deck rows to update them. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-secrets-key/.superpowers/sdd/2026-10-29-fleet-secrets-key/task-4-report.md</result> <usage><subagent_tokens>145161</subagent_tokens><tool_uses>39</tool_uses><duration_ms>455352</duration_ms></usage> </task-notification>

Attributed to this commit: 20.6 g CO₂e (2,617,834 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/apimode.go b/apimode.go
index dd5222cd1..97eb46ec9 100644
--- a/apimode.go
+++ b/apimode.go
@@ -2888,8 +2888,12 @@ type apiConfig struct {
// for; "" from a console that predates bound envelopes (see
// handleAPIConfigGet).
SecretsAccount string
- Environments []string
- Vars []apiConfigVar
+ // SecretsKeylessFleet names the fleet the app is placed on when that
+ // fleet has no secrets key, and the console therefore serves none; ""
+ // otherwise, and from an older console.
+ SecretsKeylessFleet string
+ Environments []string
+ Vars []apiConfigVar
}
// configGet reads one app's config bundle through the console — the default
@@ -2924,6 +2928,7 @@ func (s *apiSession) configGet(ctx context.Context, a apiAcct, app, environment
ExecDelivery string `json:"exec_delivery"`
SecretsPubkey string `json:"secrets_pubkey"`
SecretsAccount string `json:"secrets_account"`
+ KeylessFleet string `json:"secrets_keyless_fleet"`
Environments []string `json:"environments"`
Vars []struct {
Key string `json:"key"`
@@ -2935,12 +2940,13 @@ func (s *apiSession) configGet(ctx context.Context, a apiAcct, app, environment
return apiConfig{}, fmt.Errorf("config: unreadable response: %w", err)
}
out := apiConfig{
- Bundle: res.Bundle,
- ExecDelivery: res.ExecDelivery,
- SecretsPubkey: res.SecretsPubkey,
- SecretsAccount: res.SecretsAccount,
- Environments: res.Environments,
- Vars: make([]apiConfigVar, len(res.Vars)),
+ Bundle: res.Bundle,
+ ExecDelivery: res.ExecDelivery,
+ SecretsPubkey: res.SecretsPubkey,
+ SecretsAccount: res.SecretsAccount,
+ SecretsKeylessFleet: res.KeylessFleet,
+ Environments: res.Environments,
+ Vars: make([]apiConfigVar, len(res.Vars)),
}
for i, v := range res.Vars {
out.Vars[i] = apiConfigVar{Key: v.Key, Kind: v.Kind, Value: v.Value}
@@ -2951,7 +2957,7 @@ func (s *apiSession) configGet(ctx context.Context, a apiAcct, app, environment
// apiConfigApply is one config write through the console's config door,
// mirroring PUT /api/cli/apps/{account}/{app}/config's body exactly. Set's
// values marshal through appconfig.Var's OWN json tags
-// (`{"kind","value","envelope"}`, value/envelope omitempty) — the wire
+// (`{"kind","value","envelope","sealed_to"}`, the last three omitempty) — the wire
// shape the spec pins for both env and secret vars, so no separate wire
// struct is needed here. ExecDelivery is a pointer because "absent" (no
// change requested) and "" are different requests on the wire, but the CLI
diff --git a/apimode_test.go b/apimode_test.go
index f0b7c91ed..74aa45bda 100644
--- a/apimode_test.go
+++ b/apimode_test.go
@@ -4134,9 +4134,9 @@ func TestSecretsPubKeyAPINamesTheBundleBeingWritten(t *testing.T) {
}))
defer ts.Close()
s := newTestSession(ts.URL)
- pub, sealAcct := secretsPubKeyAPI(s, apiAcct{Seg: "bab"}, "docs", "team")
- if pub == nil || sealAcct != "bab" {
- t.Fatalf("secretsPubKeyAPI = %v, %q", pub, sealAcct)
+ pub, sealAcct, fp := secretsPubKeyAPI(s, apiAcct{Seg: "bab"}, "docs", "team")
+ if pub == nil || sealAcct != "bab" || fp != appconfig.KeyFingerprint(pub) {
+ t.Fatalf("secretsPubKeyAPI = %v, %q, %q", pub, sealAcct, fp)
}
if len(gotPaths) != 1 || gotPaths[0] != "/api/cli/apps/bab/docs/config?environment=team" {
t.Fatalf("GET paths = %v, want the environment's own config GET", gotPaths)
diff --git a/appconfig_cli.go b/appconfig_cli.go
index 786ea6cb6..d27556599 100644
--- a/appconfig_cli.go
+++ b/appconfig_cli.go
@@ -837,27 +837,32 @@ func secretsPubKey() *ecdh.PublicKey {
return k
}
-// secretsPubKeyAPI resolves the sealing key for API-mode `secrets set`:
-// CARLOS_SECRETS_PUBKEY in THIS terminal's own environment wins — matching
+// secretsPubKeyAPI resolves the sealing key for API-mode `secrets set`.
+// CARLOS_SECRETS_PUBKEY in THIS terminal's own environment wins, matching
// secretsPubKey's direct-mode rule exactly, so the same env var works
-// whichever mode a script happens to run in — otherwise the console's own
-// served public key (Config.SecretsPub, GET config's "secrets_pubkey"
-// field). That fallback is what makes `carlos auth login` alone sufficient
-// for `secrets set` (spec decision 2): public material by design, it only
-// encrypts. Neither present: a fatal naming both fixes — CARLOS_SECRETS_KEY
-// (the PRIVATE half) never leaves the box holding it, so there is no third
-// way to get a key here.
+// whichever mode a script happens to run in. Otherwise it is the console's
+// served public key (GET config's "secrets_pubkey" field): the fleet's own
+// key for an app placed on a fleet, the deployment's otherwise. That
+// fallback is what makes `carlos auth login` alone sufficient for `secrets
+// set` (spec decision 2): public material by design, it only encrypts.
+// Neither present: a fatal naming the fixes (secretsKeyFromConfig).
+// CARLOS_SECRETS_KEY (the PRIVATE half) never leaves the box holding it, so
+// there is no third way to get a key here.
//
// It also returns the account sqid to bind the envelopes to, which only the
// console can supply (the flag may be a name), so the GET is made even when
// the key comes from the environment. "" means the console does not write
-// bound envelopes (switched off, or too old); the caller seals v1 then.
+// bound envelopes (switched off, or too old); the caller seals v1 then. And
+// it returns the key's fingerprint, which the caller sends as each var's
+// sealed_to, so the console can refuse a value sealed to a key the app's
+// boxes do not hold (fleet secrets key spec §5.3), the terminal's override
+// included.
//
// The GET names the bundle being written (environment), not the default
// bundle (team-scoped credentials §5): a team credential reaches only the
// environments its scope owns, and the default-bundle GET answers it 404;
// an owned environment's GET carries secrets_pubkey like any other.
-func secretsPubKeyAPI(sess *apiSession, account apiAcct, app, environment string) (*ecdh.PublicKey, string) {
+func secretsPubKeyAPI(sess *apiSession, account apiAcct, app, environment string) (*ecdh.PublicKey, string, string) {
cfg, err := sess.configGet(context.Background(), account, app, environment)
if err != nil {
log.Fatal(err)
@@ -867,17 +872,28 @@ func secretsPubKeyAPI(sess *apiSession, account apiAcct, app, environment string
if err != nil {
log.Fatal(err)
}
- return k, cfg.SecretsAccount
+ return k, cfg.SecretsAccount, appconfig.KeyFingerprint(k)
}
- if cfg.SecretsPubkey == "" {
- log.Fatal("no CARLOS_SECRETS_PUBKEY in env and this console does not serve one — " +
- "set the env var, or set CARLOS_SECRETS_PUBKEY in the console's environment")
- }
- k, err := appconfig.ParsePublicKey(cfg.SecretsPubkey, "console secrets_pubkey")
+ k, err := secretsKeyFromConfig(cfg, app)
if err != nil {
log.Fatal(err)
}
- return k, cfg.SecretsAccount
+ return k, cfg.SecretsAccount, appconfig.KeyFingerprint(k)
+}
+
+// secretsKeyFromConfig is the console's served key out of a config GET, or
+// the refusal when it serves none. A console that knows the app is on a
+// keyless fleet names it (secrets_keyless_fleet); otherwise the fleet stays
+// a placeholder for the caller to fill.
+func secretsKeyFromConfig(cfg apiConfig, app string) (*ecdh.PublicKey, error) {
+ if cfg.SecretsPubkey == "" {
+ fleet := cfg.SecretsKeylessFleet
+ if fleet == "" {
+ fleet = "<fleet>"
+ }
+ return nil, fmt.Errorf("the console serves no secrets key for %s. if %s is placed on a fleet, run carlos fleets secrets-key %s <pubkey>. otherwise set CARLOS_SECRETS_PUBKEY in your terminal", app, app, fleet)
+ }
+ return appconfig.ParsePublicKey(cfg.SecretsPubkey, "console secrets_pubkey")
}
// secretsEnvelopeV2Env reads CONSOLE_SECRETS_ENVELOPE_V2 for direct-bucket
@@ -968,14 +984,14 @@ func runSecretsSet(args []string) {
// only symptom is a render failure in the hourly adopt log.
acct := resolvedAccount(sess, acctRaw, acctIDRaw)
app2 := resolvedApp(sess, acct, *app, usage)
- pub, sealAcct := secretsPubKeyAPI(sess, acct, app2, *environment)
+ pub, sealAcct, sealedTo := secretsPubKeyAPI(sess, acct, app2, *environment)
set := make(map[string]appconfig.Var, len(kv))
for k, v := range kv {
env, err := sealSecretAPI(pub, sealAcct, app2, []byte(v))
if err != nil {
log.Fatalf("seal %s: %v", k, err)
}
- set[k] = appconfig.Var{Kind: "secret", Envelope: env}
+ set[k] = appconfig.Var{Kind: "secret", Envelope: env, SealedTo: sealedTo}
}
res, err := sess.configApply(context.Background(), acct, app2,
apiConfigApply{Environment: *environment, Set: set})
diff --git a/approved_fleet_secrets_copy_test.go b/approved_fleet_secrets_copy_test.go
index 5a507351d..ad01eadb5 100644
--- a/approved_fleet_secrets_copy_test.go
+++ b/approved_fleet_secrets_copy_test.go
@@ -54,7 +54,8 @@ var fleetSecretsCopyStatuses = []string{"pending", "approved", "struck"}
// fleetSecretsCopyBuilt is every id whose text the code or docs carry. The
// 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.
+// 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.
var fleetSecretsCopyBuilt = []string{
"FSK-C01", "FSK-C02", "FSK-C03", "FSK-C04",
"FSK-C05", "FSK-C06", "FSK-C07", "FSK-C08",
@@ -65,6 +66,8 @@ var fleetSecretsCopyBuilt = []string{
"FSK-C25", "FSK-C26", "FSK-C27", "FSK-C28",
"FSK-C29", "FSK-C30", "FSK-C31", "FSK-C32",
"FSK-C33", "FSK-C34", "FSK-C35", "FSK-C36",
+ "FSK-C37", "FSK-C38", "FSK-C39", "FSK-C40",
+ "FSK-C41", "FSK-C42", "FSK-C43",
}
func mustParseFleetSecretsRecord(t *testing.T) []copyRow {
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 044004a13..2ed8f8de2 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -659,10 +659,16 @@ func serve() {
// Started after ConfigureClaimRuntime, which swaps cfg.Releases for its
// boundary, so the goroutine never races that swap. Bounded, and it
// never holds up serving; a no-op with no store or registry.
+ //
+ // Then the app placement backfill (fleet secrets key plan ruling R-1):
+ // the placement column from routes, for apps placed before the column
+ // existed. Not before the first seal: sealKeyFor reads the same routes
+ // until it lands.
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
srv.RunFleetOwnerBackfill(ctx)
+ srv.RunAppPlacementBackfill(ctx)
}()
// The alert watcher polls alerts/boxes/*.json every minute and keymails
// operators on each fire/clear (internal/console/alertwatch.go). Started
diff --git a/fleets_secrets_key_cli_test.go b/fleets_secrets_key_cli_test.go
index b34931fb0..fba190c3b 100644
--- a/fleets_secrets_key_cli_test.go
+++ b/fleets_secrets_key_cli_test.go
@@ -25,6 +25,7 @@ import (
// credential, a fleet home, and an app shop placed on it.
type fskCLI struct {
rel release.Store
+ st *console.Store
sess *apiSession
depPub string // the deployment's own public key
account string
@@ -95,6 +96,7 @@ func fskCLIFixture(t *testing.T) *fskCLI {
}
fx := &fskCLI{
rel: rel,
+ st: cst,
sess: &apiSession{c: newConsoleClient(ts.URL, token), console: ts.URL, address: addr},
depPub: depPub,
account: release.OpsAccount,
@@ -370,3 +372,77 @@ func TestSecretsFingerprintReadsHostEnv(t *testing.T) {
t.Errorf("bad-key error echoes the key: %v", err)
}
}
+
+// TestSecretsSetSendsSealedTo: API-mode `secrets set` seals to the key the
+// console serves and sends that key's fingerprint as sealed_to, which the
+// console stores with the value: the fleet's own key, v2, for an app on a
+// fleet, and the deployment key for an app placed nowhere.
+func TestSecretsSetSendsSealedTo(t *testing.T) {
+ fx := fskCLIFixture(t)
+ privB64, pub, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ fp, _ := appconfig.PublicFingerprint(pub)
+ captureStdout(t)
+ RunFleets([]string{"secrets-key", "-account", "ops", "home", pub})
+
+ runCapturingRealStdout(t, func() {
+ runSecretsSet([]string{"-account", "ops", "-app", "shop", "API_KEY=hunter2"})
+ })
+ m, err := appconfig.Get(context.Background(), fx.rel, fx.account, "shop")
+ if err != nil {
+ t.Fatal(err)
+ }
+ v := m.Vars["API_KEY"]
+ if v.SealedTo != fp {
+ t.Fatalf("stored sealed_to = %q, want home's %s", v.SealedTo, fp)
+ }
+ if !appconfig.EnvelopeBound(v.Envelope) {
+ t.Fatal("a fleet app's secret was sealed v1")
+ }
+ priv, _ := appconfig.ParsePrivateKey(privB64, "test")
+ if got, err := appconfig.Open(priv, appconfig.Binding{Account: fx.account, App: "shop"}, v.Envelope); err != nil || string(got) != "hunter2" {
+ t.Fatalf("home's private key does not open the value: %q %v", got, err)
+ }
+
+ // An app placed nowhere: the deployment key, and its fingerprint.
+ if _, err := fx.st.CreateAppIn(console.OpsAccountID, "other", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ runCapturingRealStdout(t, func() {
+ runSecretsSet([]string{"-account", "ops", "-app", "other", "API_KEY=hunter2"})
+ })
+ m, err = appconfig.Get(context.Background(), fx.rel, fx.account, "other")
+ if err != nil {
+ t.Fatal(err)
+ }
+ depFP, _ := appconfig.PublicFingerprint(fx.depPub)
+ if got := m.Vars["API_KEY"].SealedTo; got != depFP {
+ t.Fatalf("platform app sealed_to = %q, want the deployment key %s", got, depFP)
+ }
+}
+
+// TestSecretsSetOnKeylessFleetNamesTheFleet: a console that serves no key
+// because the app's fleet has none says which fleet, and the CLI names it in
+// the fix; with no fleet named, the fleet stays a placeholder.
+func TestSecretsSetOnKeylessFleetNamesTheFleet(t *testing.T) {
+ fx := fskCLIFixture(t)
+ cfg, err := fx.sess.configGet(context.Background(), apiAcct{Seg: "ops"}, "shop", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cfg.SecretsKeylessFleet != "home" || cfg.SecretsPubkey != "" {
+ t.Fatalf("config GET = keyless %q pubkey %q, want home and none", cfg.SecretsKeylessFleet, cfg.SecretsPubkey)
+ }
+ _, err = secretsKeyFromConfig(cfg, "shop")
+ want := "the console serves no secrets key for shop. if shop is placed on a fleet, run carlos fleets secrets-key home <pubkey>. otherwise set CARLOS_SECRETS_PUBKEY in your terminal"
+ if err == nil || err.Error() != want {
+ t.Fatalf("err = %v, want %q", err, want)
+ }
+ _, err = secretsKeyFromConfig(apiConfig{}, "shop")
+ want = "the console serves no secrets key for shop. if shop is placed on a fleet, run carlos fleets secrets-key <fleet> <pubkey>. otherwise set CARLOS_SECRETS_PUBKEY in your terminal"
+ if err == nil || err.Error() != want {
+ t.Fatalf("err = %v, want %q", err, want)
+ }
+}
diff --git a/internal/appconfig/crypto.go b/internal/appconfig/crypto.go
index 8628b5ff0..93fabc53f 100644
--- a/internal/appconfig/crypto.go
+++ b/internal/appconfig/crypto.go
@@ -230,6 +230,19 @@ func splitVersion(raw []byte) (bool, []byte) {
return false, raw
}
+// EnvelopeBound reports whether envelopeB64 is a v2 (bound) envelope, read
+// off its prefix without any key. Bad base64 reads as false. The console's
+// config door uses it to refuse a v1 envelope for an app on a fleet, whose
+// envelopes are always v2.
+func EnvelopeBound(envelopeB64 string) bool {
+ raw, err := base64.StdEncoding.DecodeString(envelopeB64)
+ if err != nil {
+ return false
+ }
+ bound, _ := splitVersion(raw)
+ return bound
+}
+
// Open decrypts an envelope with priv, for the config named by b. A v2
// envelope opens only if it was sealed for b. A v1 envelope opens regardless
// of b: those were written before the binding existed and are most of every
diff --git a/internal/appconfig/crypto_bind_test.go b/internal/appconfig/crypto_bind_test.go
index db15fabd2..2baaf10ca 100644
--- a/internal/appconfig/crypto_bind_test.go
+++ b/internal/appconfig/crypto_bind_test.go
@@ -200,3 +200,20 @@ func TestSealWritesV1UntilBoundSealingIsOn(t *testing.T) {
t.Fatal("v2 envelope from Seal opened under another account")
}
}
+
+// EnvelopeBound reads the version off the prefix: v2 from SealBound, v1
+// from SealUnbound, and false for anything that is not base64.
+func TestEnvelopeBound(t *testing.T) {
+ _, pub := bindKeys(t)
+ v2, err := SealBound(pub, Binding{Account: "bab", App: "shop"}, []byte("x"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ v1, err := SealUnbound(pub, []byte("x"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !EnvelopeBound(v2) || EnvelopeBound(v1) || EnvelopeBound("not base64!") {
+ t.Fatalf("EnvelopeBound(v2, v1, junk) = %v, %v, %v; want true, false, false", EnvelopeBound(v2), EnvelopeBound(v1), EnvelopeBound("not base64!"))
+ }
+}
diff --git a/internal/console/apiconfig.go b/internal/console/apiconfig.go
index 54513dbe2..612fd58b1 100644
--- a/internal/console/apiconfig.go
+++ b/internal/console/apiconfig.go
@@ -257,22 +257,55 @@ func (s *Server) handleAPIConfigGet(w http.ResponseWriter, r *http.Request) {
if m.ExecDelivery != "" {
out["exec_delivery"] = m.ExecDelivery
}
- // Public material by design — it only encrypts. Serving it is what makes
- // `carlos auth login` sufficient for `carlos secrets set`; omitted when
- // this deployment configured none, so the CLI can tell "no key here"
- // from "empty key" and fall back to its own env var.
- if s.cfg.SecretsPub != "" {
- out["secrets_pubkey"] = s.cfg.SecretsPub
- }
- // The account a secret for this app is bound to (appconfig.Binding), as
- // the sqid this console resolved the request to — the CLI may only know
- // the account by name. Present ONLY while this deployment writes bound
- // (v2) envelopes (CONSOLE_SECRETS_ENVELOPE_V2): its presence is how the
- // CLI learns to seal v2, and absent — this console with the switch off,
- // or an older console — it seals v1, which every box can open
- // (discussion #220).
- if appconfig.BoundSealing() {
- out["secrets_account"] = acct.Sqid
+ // The key a client seals this app's secrets with, from sealKeyFor (fleet
+ // secrets key spec §5.2): the fleet's own key for an app placed on a
+ // fleet, the deployment's for one placed nowhere. Public material by
+ // design, it only encrypts; serving it is what makes `carlos auth login`
+ // sufficient for `carlos secrets set`. Omitted when there is none, so the
+ // CLI can tell "no key here" from "empty key".
+ //
+ // secrets_account is the account a secret for this app is bound to
+ // (appconfig.Binding), as the sqid this console resolved the request to;
+ // the CLI may only know the account by name. Its presence is how the CLI
+ // learns to seal v2. For a fleet app it is always present, because a
+ // fleet's envelopes are always v2. For a platform app it follows the
+ // deployment switch (CONSOLE_SECRETS_ENVELOPE_V2): absent, the CLI seals
+ // v1, which every box can open (discussion #220).
+ //
+ // On a keyless fleet both are omitted and secrets_keyless_fleet names the
+ // caller's own fleet, so the CLI can name the fix (B8). Not a refusal:
+ // the same GET serves `env list` and `secrets list`, and the PUT refuses
+ // the seal itself.
+ sealer, err := s.sealKeyFor(ctx, acct.Sqid, app)
+ var keyless errFleetNoSecretsKey
+ var unknown errUnknownApp
+ switch {
+ case errors.As(err, &unknown):
+ // The gate saw the app a moment ago; it went since. The gate's own
+ // answer.
+ http.NotFound(w, r)
+ return
+ case err == nil:
+ out["secrets_pubkey"] = sealer.PublicKeyB64()
+ if sealer.Bound() {
+ out["secrets_account"] = acct.Sqid
+ }
+ case errors.As(err, &keyless):
+ out["secrets_keyless_fleet"] = keyless.Fleet
+ case errors.Is(err, errNoDeploymentKey), errors.Is(err, errDeploymentKeyUnreadable):
+ // A platform app on a console without a usable key: the terminal's
+ // own CARLOS_SECRETS_PUBKEY is the only key, as before, and the
+ // account still follows the switch.
+ if errors.Is(err, errDeploymentKeyUnreadable) {
+ log.Printf("console: api config get %s/%s: %v", acct.Sqid, app, err)
+ }
+ if appconfig.BoundSealing() {
+ out["secrets_account"] = acct.Sqid
+ }
+ default:
+ log.Printf("console: api config get %s/%s: seal key: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusBadGateway, "could not read the config — try again")
+ return
}
writeJSON(w, http.StatusOK, out)
}
@@ -317,6 +350,9 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
Kind string `json:"kind"`
Value string `json:"value"`
Envelope string `json:"envelope"`
+ // SealedTo is the fingerprint of the key the client sealed
+ // with; absent from an older CLI (fleet secrets key §5.3).
+ SealedTo string `json:"sealed_to"`
} `json:"set"`
Unset []string `json:"unset"`
// A POINTER, so an absent field ("leave it alone") is
@@ -404,7 +440,9 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
fmt.Sprintf(`var %s is kind "secret" but carries a plaintext value — seal it client-side and send only the envelope`, k))
return
}
- sets[k] = appconfig.Var{Kind: "secret", Envelope: v.Envelope}
+ // SealedTo is checked against the app's key below, under the
+ // account lock, before anything is written.
+ sets[k] = appconfig.Var{Kind: "secret", Envelope: v.Envelope, SealedTo: v.SealedTo}
default:
jsonError(w, http.StatusBadRequest,
fmt.Sprintf(`var %s: invalid kind %q — want "env" or "secret"`, k, v.Kind))
@@ -463,6 +501,28 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
bundle := configBundleName(envName)
removed := 0
audit := ""
+ // A request carrying a sealed value holds the account lock from the
+ // key check through the write (fleet secrets key spec §5.2.1), so a key
+ // replacement cannot land between them: the key door takes the same
+ // lock and then sees this value. Taken here, at the door, before any
+ // app lock (teamApplyEnvironment's comes after: account, then app).
+ // Nothing below takes the account lock again: planLock is only on the
+ // create doors. A plain env write takes no lock.
+ unlockAcct := func() {}
+ if configSetsSecret(sets) {
+ unlock := s.lockAccount(acct.Sqid)
+ held := true
+ unlockAcct = func() {
+ if held {
+ held = false
+ unlock()
+ }
+ }
+ defer unlockAcct()
+ if !s.configCheckSealedTo(w, r, ctx, acct, app, keys, sets) {
+ return
+ }
+ }
if team {
managed, err := s.platformManagedKeys(ctx, acct.Sqid, app, envName)
if err != nil {
@@ -481,6 +541,9 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
// unset-only refusal (applyAt), and asking to set a flag is not asking
// to remove anything.
if len(sets) > 0 || len(req.Unset) > 0 {
+ if configPutBeforeApply != nil {
+ configPutBeforeApply()
+ }
var err error
switch {
case envName == "":
@@ -498,6 +561,7 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
s.configStoreError(w, fmt.Sprintf("api config apply %s/%s (%s)", acct.Sqid, app, bundle), err)
return
}
+ unlockAcct()
// Counts and the bundle, never keys and never values — an audit trail
// that recorded a secret's envelope would be a copy of the secret
// store in a database with different reach. The unset count is what
@@ -546,6 +610,85 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, out)
}
+// configPutBeforeApply runs inside the PUT's account lock, after its key
+// check and before its write. Test-only (TestConfigPutRacesReplacement);
+// nil in production.
+var configPutBeforeApply func()
+
+// configSetsSecret reports whether a PUT's sets carry a sealed value.
+func configSetsSecret(sets map[string]appconfig.Var) bool {
+ for _, v := range sets {
+ if v.Kind == "secret" {
+ return true
+ }
+ }
+ return false
+}
+
+// configCheckSealedTo checks each sealed var of a PUT against the key the
+// app's boxes hold (fleet secrets key spec §5.3), answering the refusal
+// itself and reporting whether the PUT may go on. keys is the sorted var
+// names, so a request with several defects always refuses on the same one.
+// The caller holds the account lock.
+//
+// For an app on a fleet, each value must say it is sealed to the fleet's key
+// (an older CLI says nothing and is told to upgrade) and be v2. For an app
+// placed nowhere, an absent sealed_to is today's behaviour and accepted; a
+// present one must be the deployment key. A console without a usable
+// deployment key has nothing to compare, and accepts as it always has.
+//
+// It reads chooseSealKey, not sealKeyFor: the PUT never seals, and it needs
+// the fleet's name for its refusals. sealKeyFor is chooseSealKey plus the
+// sealer, so the key checked here is the key the GET served.
+func (s *Server) configCheckSealedTo(w http.ResponseWriter, r *http.Request, ctx context.Context, acct *Account, app string, keys []string, sets map[string]appconfig.Var) bool {
+ c, err := s.chooseSealKey(ctx, acct.Sqid, app)
+ var keyless errFleetNoSecretsKey
+ var unknown errUnknownApp
+ switch {
+ case err == nil:
+ case errors.As(err, &keyless):
+ jsonError(w, http.StatusConflict, keyless.Error())
+ return false
+ case errors.Is(err, errNoDeploymentKey), errors.Is(err, errDeploymentKeyUnreadable):
+ return true
+ case errors.As(err, &unknown):
+ // The gate saw the app a moment ago; it went since. The gate's own
+ // answer.
+ http.NotFound(w, r)
+ return false
+ default:
+ log.Printf("console: api config apply %s/%s: seal key: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusBadGateway, "could not read the config — try again")
+ return false
+ }
+ fp := appconfig.KeyFingerprint(c.pub)
+ for _, k := range keys {
+ v, ok := sets[k]
+ if !ok || v.Kind != "secret" {
+ continue
+ }
+ if c.fleet == "" {
+ if v.SealedTo != "" && v.SealedTo != fp {
+ jsonError(w, http.StatusBadRequest, fmt.Sprintf("%s was sealed to a key that this app's boxes do not hold. unset CARLOS_SECRETS_PUBKEY in your terminal and set %s again", k, k))
+ return false
+ }
+ continue
+ }
+ switch {
+ case v.SealedTo == "":
+ jsonError(w, http.StatusBadRequest, fmt.Sprintf("%s cannot be checked, because the carlos CLI that sealed it did not say which key it used, and %s is placed on %s. upgrade the carlos CLI and set %s again", k, app, c.fleet, k))
+ return false
+ case v.SealedTo != fp:
+ jsonError(w, http.StatusBadRequest, fmt.Sprintf("%s was sealed to a key that %s's boxes do not hold. unset CARLOS_SECRETS_PUBKEY in your terminal and set %s again", k, c.fleet, k))
+ return false
+ case !appconfig.EnvelopeBound(v.Envelope):
+ jsonError(w, http.StatusBadRequest, fmt.Sprintf("%s was sealed in an older format that %s's boxes do not accept. upgrade the carlos CLI and set %s again", k, c.fleet, k))
+ return false
+ }
+ }
+ return true
+}
+
// apiConfigRestart is the config door's answer to "did that reach
// anything?" — the wire half of appconfig.AwaitingRestart.
//
diff --git a/internal/console/sealkey.go b/internal/console/sealkey.go
new file mode 100644
index 000000000..3d726ac09
--- /dev/null
+++ b/internal/console/sealkey.go
@@ -0,0 +1,248 @@
+package console
+
+// sealKeyFor: the one answer to "which key does a secret for this app get
+// sealed to" (fleet secrets key spec §5.2, plan Task 5).
+//
+// I1 (spec §2.1) rests here. A value sealed for app X of account A must open
+// only on platform boxes (the deployment key) or on boxes of a fleet A owns.
+// So this function returns exactly one of two keys: the key of the fleet the
+// app is placed on, after checking that fleet belongs to A, or the
+// deployment key for an app placed nowhere. Every other case is a refusal,
+// never a fallback: a keyless fleet, a fleet of another account, an app or
+// account it cannot find. The deployment key is never the answer for a
+// fleet-placed app, because that app's boxes do not hold it and the
+// operator's boxes would.
+//
+// It takes the account's sqid and resolves the row itself (spec A2): a
+// caller that built an &Account{Sqid: ...} by hand has a zero ID, and the
+// placement reads by ID would answer "not placed".
+//
+// It takes no lock. Callers that seal and write hold s.lockAccount(sqid)
+// from this call through their write (§5.2.1); the lock is not reentrant,
+// so taking it here would deadlock every one of them.
+
+import (
+ "context"
+ "crypto/ecdh"
+ "errors"
+ "fmt"
+ "log"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+var (
+ // errUnknownAccount: the sqid names no live account.
+ errUnknownAccount = errors.New("console: seal key: no account with that sqid")
+ // errNoDeploymentKey: an app placed nowhere, on a console with no
+ // CARLOS_SECRETS_PUBKEY.
+ errNoDeploymentKey = errors.New("console: seal key: no deployment secrets key (CARLOS_SECRETS_PUBKEY)")
+ // errDeploymentKeyUnreadable: the console's CARLOS_SECRETS_PUBKEY does
+ // not parse. Wrapped with the parse error.
+ errDeploymentKeyUnreadable = errors.New("console: seal key: the deployment secrets key (CARLOS_SECRETS_PUBKEY) cannot be read")
+)
+
+// errFleetNoSecretsKey: the app is placed on Fleet, which has no secrets key
+// registered. Its message is the owner's fix.
+type errFleetNoSecretsKey struct{ Fleet string }
+
+func (e errFleetNoSecretsKey) Error() string {
+ return fmt.Sprintf("%s has no secrets key, so apps placed on it cannot hold secrets. run carlos fleets secrets-key %s <pubkey> with a key from carlos secrets genkey", e.Fleet, e.Fleet)
+}
+
+// errUnknownApp: the account has no live app called App. A missing row is
+// a refusal, never "not placed" (spec A2).
+type errUnknownApp struct{ App string }
+
+func (e errUnknownApp) Error() string {
+ return fmt.Sprintf("no app called %s in this account. check the name with carlos apps list", e.App)
+}
+
+// errFleetNotOwned: the app's placement names a fleet that does not exist or
+// belongs to another account. No door writes such a placement
+// (placeAppTarget refuses it); this is the I1 backstop for a row that says
+// so anyway. Not copy: the message names nothing of the other account and
+// is for the log.
+type errFleetNotOwned struct{ Fleet string }
+
+func (e errFleetNotOwned) Error() string {
+ return fmt.Sprintf("console: seal key: placement fleet/%s is not a fleet of this account", e.Fleet)
+}
+
+// sealChoice is sealKeyFor's reading of where an app's secrets go, before a
+// sealer is built from it: the key, whether its envelopes are bound, and the
+// fleet ("" for the deployment key).
+type sealChoice struct {
+ sqid string
+ pub *ecdh.PublicKey
+ bound bool
+ fleet string
+}
+
+// sealKeyFor returns the sealer for every seal of acctSqid/app's config.
+// See the file comment for the rules; chooseSealKey applies them.
+func (s *Server) sealKeyFor(ctx context.Context, acctSqid, app 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: app}, c.bound), nil
+}
+
+// chooseSealKey is sealKeyFor without the sealer: the config PUT, which
+// checks what a client sealed and never seals itself, reads the fleet name
+// for its refusals from here. sealKeyFor is this plus NewSealer, so the two
+// cannot disagree.
+func (s *Server) chooseSealKey(ctx context.Context, acctSqid, app string) (sealChoice, error) {
+ acct, err := s.store.AccountBySqid(acctSqid)
+ if err != nil {
+ return sealChoice{}, fmt.Errorf("console: seal key: account %s: %w", acctSqid, err)
+ }
+ if acct == nil {
+ return sealChoice{}, errUnknownAccount
+ }
+ found, err := s.store.HasAppIn(acct.ID, app)
+ if err != nil {
+ return sealChoice{}, fmt.Errorf("console: seal key: app %s/%s: %w", acct.Sqid, app, err)
+ }
+ if !found {
+ return sealChoice{}, errUnknownApp{App: app}
+ }
+ placement, reg, err := s.sealPlacement(acct, app)
+ if err != nil {
+ return sealChoice{}, fmt.Errorf("console: seal key: placement of %s/%s: %w", acct.Sqid, app, err)
+ }
+ if placement == "" {
+ pub, err := s.deploymentSealKey()
+ if err != nil {
+ return sealChoice{}, err
+ }
+ return sealChoice{sqid: acct.Sqid, pub: pub, bound: appconfig.BoundSealing()}, nil
+ }
+ name, ok := registry.FleetPlacement(placement)
+ if !ok {
+ // Not a placement any door writes. Refused rather than read as
+ // "not placed": the app may well run on a fleet.
+ return sealChoice{}, fmt.Errorf("console: seal key: %s/%s has placement %q, which names no fleet", acct.Sqid, app, placement)
+ }
+ row, err := reg.GetFleet(name)
+ if err != nil {
+ return sealChoice{}, fmt.Errorf("console: seal key: fleet %s: %w", name, err)
+ }
+ if row == nil || row.Account != acct.Sqid {
+ return sealChoice{}, errFleetNotOwned{Fleet: name}
+ }
+ if row.SecretsPub == "" {
+ return sealChoice{}, errFleetNoSecretsKey{Fleet: name}
+ }
+ pub, err := appconfig.ParsePublicKey(row.SecretsPub, "fleet "+name+" secrets key")
+ if err != nil {
+ return sealChoice{}, fmt.Errorf("console: seal key: %w", err)
+ }
+ if fp := appconfig.KeyFingerprint(pub); fp != row.SecretsKeyFP {
+ // The door writes both from one parse; a row where they differ was
+ // not written by it, and its key is not the one registered.
+ return sealChoice{}, fmt.Errorf("console: seal key: fleet %s's key is %s but its row records %s", name, fp, row.SecretsKeyFP)
+ }
+ // Fleet-key envelopes are always v2, whatever the deployment switch says.
+ return sealChoice{sqid: acct.Sqid, pub: pub, bound: true, fleet: name}, nil
+}
+
+// sealPlacement is appPlacement (the store's column, then routes) with the
+// registry it read. A console with no registry reads the column alone, and
+// cannot resolve a fleet the column names: reg is nil then, and a fleet
+// placement is an error.
+func (s *Server) sealPlacement(acct *Account, app string) (string, consoleRegistry, error) {
+ if s.cfg.Registry == "" {
+ placement, err := s.store.AppPlacement(acct.ID, app)
+ if err == nil && placement != "" {
+ err = errors.New("this console has no registry to read the fleet from")
+ }
+ return placement, nil, err
+ }
+ reg, err := openRegistry(s.cfg.Registry)
+ if err != nil {
+ return "", nil, err
+ }
+ placement, err := s.appPlacement(reg, acct, app)
+ return placement, reg, err
+}
+
+// deploymentSealKey parses the console's CARLOS_SECRETS_PUBKEY, with the two
+// refusals the seal sites have always made.
+func (s *Server) deploymentSealKey() (*ecdh.PublicKey, error) {
+ if s.cfg.SecretsPub == "" {
+ return nil, errNoDeploymentKey
+ }
+ pub, err := appconfig.ParsePublicKey(s.cfg.SecretsPub, "CARLOS_SECRETS_PUBKEY")
+ if err != nil {
+ return nil, fmt.Errorf("%w: %v", errDeploymentKeyUnreadable, err)
+ }
+ return pub, nil
+}
+
+// backfillAppPlacements writes the placement column from routes for every
+// live app whose column is empty and whose routes say fleet/<f>
+// (fleetFromRoutes), so the column becomes the one authority (spec §5.2 step
+// 2). It does not change any answer appPlacement gives: appPlacement already
+// falls back to the same routes for those apps. That is why it need not
+// finish before the first seal (plan ruling R-1). One route listing for the
+// whole pass; every app is tried, and the failures are joined.
+func (s *Server) backfillAppPlacements(ctx context.Context) error {
+ if s.cfg.Registry == "" {
+ return nil
+ }
+ reg, err := openRegistry(s.cfg.Registry)
+ if err != nil {
+ return err
+ }
+ routes, err := reg.List()
+ if err != nil {
+ return err
+ }
+ accts, err := s.store.Accounts()
+ if err != nil {
+ return err
+ }
+ var errs []error
+ for _, acct := range accts {
+ apps, err := s.store.AppsIn(acct.ID)
+ if err != nil {
+ errs = append(errs, fmt.Errorf("%s: %w", acct.Sqid, err))
+ continue
+ }
+ for _, app := range apps {
+ if err := ctx.Err(); err != nil {
+ return errors.Join(append(errs, err)...)
+ }
+ placed, err := s.store.AppPlacement(acct.ID, app)
+ if err != nil {
+ errs = append(errs, fmt.Errorf("%s/%s: %w", acct.Sqid, app, err))
+ continue
+ }
+ if placed != "" {
+ continue
+ }
+ target := fleetFromRoutes(routes, acct.Sqid, app)
+ if target == "" {
+ continue
+ }
+ if err := s.store.SetAppPlacementContext(ctx, acct.ID, app, target); err != nil {
+ errs = append(errs, fmt.Errorf("%s/%s: %w", acct.Sqid, app, err))
+ continue
+ }
+ log.Printf("console: app placement backfill: %s/%s placed on %s, from its routes", acct.Sqid, app, target)
+ }
+ }
+ return errors.Join(errs...)
+}
+
+// RunAppPlacementBackfill is backfillAppPlacements for cmd/console, run in
+// the goroutine that runs the fleet owner backfill, never holding up
+// serving. It logs the outcome; the next start tries again.
+func (s *Server) RunAppPlacementBackfill(ctx context.Context) {
+ if err := s.backfillAppPlacements(ctx); err != nil {
+ log.Printf("console: app placement backfill: %v", err)
+ }
+}
diff --git a/internal/console/sealkey_test.go b/internal/console/sealkey_test.go
new file mode 100644
index 000000000..e4b80072a
--- /dev/null
+++ b/internal/console/sealkey_test.go
@@ -0,0 +1,550 @@
+package console
+
+// sealKeyFor and the config doors that use it (fleet secrets key spec §5.2,
+// §5.2.1, §5.3; plan Task 5). The properties, in the order they would hurt
+// if lost: a value for an app on a fleet is never sealed to the deployment
+// key nor to another account's fleet key (I1), the config GET serves the key
+// the app's boxes hold, the PUT refuses a value it can see is sealed to the
+// wrong key or in the wrong format, and a key replacement cannot slip
+// between the PUT's check and its write.
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// skFleetKey is a fresh fleet keypair: the private key (standing in for the
+// box's CARLOS_SECRETS_KEY), the public half as registered, its fingerprint.
+type skFleetKey struct {
+ priv string
+ pub string
+ fp string
+}
+
+func skNewKey(t *testing.T) skFleetKey {
+ t.Helper()
+ priv, pub, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ fp, err := appconfig.PublicFingerprint(pub)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return skFleetKey{priv, pub, fp}
+}
+
+// skRegister registers k as fleet's key through the key door.
+func skRegister(t *testing.T, fx *consoleFixture, token, fleet string, k skFleetKey) {
+ t.Helper()
+ if status, body := putJSON(t, fskURL(fx, fx.sqid, fleet), map[string]string{"pubkey": k.pub}, token); status != http.StatusOK {
+ t.Fatalf("register %s's key = %d %v", fleet, status, body)
+ }
+}
+
+// skFleetShop is fskFixture with shop placed on home, and, when withKey,
+// home's key registered.
+func skFleetShop(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)
+ }
+ fskPlaceShop(t, fx, token, "home")
+ return fx, token, k
+}
+
+// skSeal seals plaintext for bab/shop to pubB64: v2 when bound, else v1.
+func skSeal(t *testing.T, fx *consoleFixture, pubB64 string, bound bool) string {
+ t.Helper()
+ pub, err := appconfig.ParsePublicKey(pubB64, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var env string
+ if bound {
+ env, err = appconfig.SealBound(pub, appconfig.Binding{Account: fx.sqid, App: "shop"}, []byte("value"))
+ } else {
+ env, err = appconfig.SealUnbound(pub, []byte("value"))
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return env
+}
+
+// skPutSecret sends one sealed var to shop's config door.
+func skPutSecret(t *testing.T, fx *consoleFixture, token, name, env, sealedTo string) (int, map[string]any) {
+ t.Helper()
+ v := map[string]string{"kind": "secret", "envelope": env}
+ if sealedTo != "" {
+ v["sealed_to"] = sealedTo
+ }
+ return putJSON(t, configURL(fx, "shop"), map[string]any{"set": map[string]any{name: v}}, token)
+}
+
+// skStored is shop's default bundle as stored.
+func skStored(t *testing.T, fx *consoleFixture) *appconfig.Manifest {
+ t.Helper()
+ m, err := appconfig.Get(context.Background(), fx.rel, fx.sqid, "shop")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return m
+}
+
+func TestSealKeyForFleetApp(t *testing.T) {
+ fx, _, k := skFleetShop(t, "code-sk-fleet", true)
+ appconfig.SetBoundSealing(false)
+ t.Cleanup(func() { appconfig.SetBoundSealing(false) })
+
+ sl, err := fx.srv.sealKeyFor(context.Background(), fx.sqid, "shop")
+ if err != nil {
+ t.Fatalf("sealKeyFor = %v", err)
+ }
+ if sl.Fingerprint() != k.fp || sl.PublicKeyB64() != k.pub {
+ t.Fatalf("sealer key = %s, want home's %s", sl.Fingerprint(), k.fp)
+ }
+ // Fleet-key envelopes are always v2, whatever the deployment switch says.
+ if !sl.Bound() {
+ t.Fatal("a fleet sealer is unbound with the deployment switch off")
+ }
+ b := appconfig.Binding{Account: fx.sqid, App: "shop"}
+ if sl.Binding() != b {
+ t.Fatalf("binding = %+v, want %+v", sl.Binding(), b)
+ }
+ v, err := sl.Seal(b, []byte("hunter2"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ priv, _ := appconfig.ParsePrivateKey(k.priv, "test")
+ if got, err := appconfig.Open(priv, b, v.Envelope); err != nil || string(got) != "hunter2" {
+ t.Fatalf("the fleet's private key does not open the value: %q %v", got, err)
+ }
+ if v.SealedTo != k.fp {
+ t.Fatalf("SealedTo = %q, want %q", v.SealedTo, k.fp)
+ }
+}
+
+func TestSealKeyForPlatformApp(t *testing.T) {
+ fx, _, _ := fskFixture(t, "code-sk-platform")
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ depPub, depFP := mustTestSecretsKey()
+ t.Cleanup(func() { appconfig.SetBoundSealing(false) })
+ for _, on := range []bool{false, true} {
+ appconfig.SetBoundSealing(on)
+ sl, err := fx.srv.sealKeyFor(context.Background(), fx.sqid, "shop")
+ if err != nil {
+ t.Fatalf("switch %v: sealKeyFor = %v", on, err)
+ }
+ if sl.Fingerprint() != depFP || sl.PublicKeyB64() != depPub {
+ t.Fatalf("switch %v: sealer = %s, want the deployment key %s", on, sl.Fingerprint(), depFP)
+ }
+ if sl.Bound() != on {
+ t.Fatalf("switch %v: Bound = %v, want the deployment switch", on, sl.Bound())
+ }
+ }
+
+ // Today's refusals: no deployment key, and one that does not parse.
+ fx.srv.cfg.SecretsPub = ""
+ if _, err := fx.srv.sealKeyFor(context.Background(), fx.sqid, "shop"); !errors.Is(err, errNoDeploymentKey) {
+ t.Fatalf("no deployment key: err = %v, want errNoDeploymentKey", err)
+ }
+ fx.srv.cfg.SecretsPub = "not a key"
+ if _, err := fx.srv.sealKeyFor(context.Background(), fx.sqid, "shop"); !errors.Is(err, errDeploymentKeyUnreadable) {
+ t.Fatalf("unreadable deployment key: err = %v, want errDeploymentKeyUnreadable", err)
+ }
+}
+
+func TestSealKeyForKeylessFleetRefuses(t *testing.T) {
+ fx, _, _ := skFleetShop(t, "code-sk-keyless", false)
+ _, depFP := mustTestSecretsKey()
+
+ sl, err := fx.srv.sealKeyFor(context.Background(), fx.sqid, "shop")
+ var keyless errFleetNoSecretsKey
+ if !errors.As(err, &keyless) || keyless.Fleet != "home" {
+ t.Fatalf("sealKeyFor = %v, want errFleetNoSecretsKey{home}", err)
+ }
+ if sl.Fingerprint() == depFP {
+ t.Fatal("a keyless fleet's app got the deployment key")
+ }
+ if sl.Fingerprint() != "" {
+ t.Fatalf("a refusal carried a sealer for %s", sl.Fingerprint())
+ }
+ want := "home has no secrets key, so apps placed on it cannot hold secrets. run carlos fleets secrets-key home <pubkey> with a key from carlos secrets genkey"
+ if err.Error() != want {
+ t.Fatalf("message = %q, want %q", err.Error(), want)
+ }
+}
+
+func TestSealKeyForSqidOnlyAccount(t *testing.T) {
+ fx, _, k := skFleetShop(t, "code-sk-sqid", true)
+
+ // The caller hands over the sqid alone, as rotateWebhookBudget does; the
+ // function resolves the account itself.
+ sl, err := fx.srv.sealKeyFor(context.Background(), fx.sqid, "shop")
+ if err != nil || sl.Fingerprint() != k.fp {
+ t.Fatalf("sealKeyFor(sqid) = %s %v, want home's key %s", sl.Fingerprint(), err, k.fp)
+ }
+ if _, err := fx.srv.sealKeyFor(context.Background(), "zzzz", "shop"); !errors.Is(err, errUnknownAccount) {
+ t.Fatalf("unknown sqid: err = %v, want errUnknownAccount", err)
+ }
+ // A missing app row is a refusal, never "not placed".
+ _, err = fx.srv.sealKeyFor(context.Background(), fx.sqid, "ghost")
+ var unknown errUnknownApp
+ if !errors.As(err, &unknown) {
+ t.Fatalf("unknown app: err = %v, want errUnknownApp", err)
+ }
+ if want := "no app called ghost in this account. check the name with carlos apps list"; err.Error() != want {
+ t.Fatalf("message = %q, want %q", err.Error(), want)
+ }
+}
+
+func TestSealKeyForOtherAccountsFleetRefuses(t *testing.T) {
+ fx, _, _ := fskFixture(t, "code-sk-other")
+ bob := fskAway(t, fx)
+ away := skNewKey(t)
+ if status, body := putJSON(t, fskURL(fx, "cdef", "away"), map[string]string{"pubkey": away.pub}, bob); status != http.StatusOK {
+ t.Fatalf("register away's key = %d %v", status, body)
+ }
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ // A placement row naming another account's fleet: no door writes one
+ // (placeAppTarget refuses), so it is written straight into the store.
+ if err := fx.st.SetAppPlacement(OpsAccountID, "shop", "fleet/away"); err != nil {
+ t.Fatal(err)
+ }
+ _, depFP := mustTestSecretsKey()
+
+ sl, err := fx.srv.sealKeyFor(context.Background(), fx.sqid, "shop")
+ if err == nil {
+ t.Fatalf("sealKeyFor sealed bab's shop to %s, want a refusal", sl.Fingerprint())
+ }
+ if sl.Fingerprint() == away.fp {
+ t.Fatal("bab's app got cdef's fleet key (I1)")
+ }
+ if sl.Fingerprint() == depFP {
+ t.Fatal("a refusal fell back to the deployment key")
+ }
+ var keyless errFleetNoSecretsKey
+ if errors.As(err, &keyless) {
+ t.Fatalf("err = %v names the fleet as keyless; another account's fleet must not be described", err)
+ }
+}
+
+func TestConfigGetServesTheFleetKey(t *testing.T) {
+ fx, token, k := skFleetShop(t, "code-sk-get", true)
+ appconfig.SetBoundSealing(false)
+ t.Cleanup(func() { appconfig.SetBoundSealing(false) })
+
+ status, out := getJSON(t, configURL(fx, "shop"), token)
+ if status != http.StatusOK {
+ t.Fatalf("GET = %d %v", status, out)
+ }
+ if out["secrets_pubkey"] != k.pub {
+ t.Fatalf("secrets_pubkey = %v, want home's %s", out["secrets_pubkey"], k.pub)
+ }
+ // Always for a fleet app: its envelopes are always v2.
+ if out["secrets_account"] != fx.sqid {
+ t.Fatalf("secrets_account = %v, want %s with the switch off", out["secrets_account"], fx.sqid)
+ }
+ if _, ok := out["secrets_keyless_fleet"]; ok {
+ t.Fatalf("secrets_keyless_fleet = %v on a fleet with a key", out["secrets_keyless_fleet"])
+ }
+
+ // A platform app in the same account still gets the deployment key.
+ depPub, _ := mustTestSecretsKey()
+ status, out = getJSON(t, configURL(fx, "kass"), token)
+ if status != http.StatusOK || out["secrets_pubkey"] != depPub {
+ t.Fatalf("platform GET = %d %v, want the deployment key", status, out)
+ }
+ if _, ok := out["secrets_account"]; ok {
+ t.Fatalf("platform secrets_account = %v with the switch off", out["secrets_account"])
+ }
+}
+
+func TestConfigGetOmitsKeyOnKeylessFleet(t *testing.T) {
+ fx, token, _ := skFleetShop(t, "code-sk-get-keyless", false)
+ appconfig.SetBoundSealing(true)
+ t.Cleanup(func() { appconfig.SetBoundSealing(false) })
+ if err := appconfig.SetEnv(context.Background(), fx.rel, fx.sqid, "shop", map[string]string{"PORT": "8080"}); err != nil {
+ t.Fatal(err)
+ }
+
+ status, out := getJSON(t, configURL(fx, "shop"), token)
+ if status != http.StatusOK {
+ t.Fatalf("GET = %d %v, want 200: the same GET serves env list", status, out)
+ }
+ for _, k := range []string{"secrets_pubkey", "secrets_account"} {
+ if _, ok := out[k]; ok {
+ t.Fatalf("%s = %v on a keyless fleet, want it absent", k, out[k])
+ }
+ }
+ if out["secrets_keyless_fleet"] != "home" {
+ t.Fatalf("secrets_keyless_fleet = %v, want home", out["secrets_keyless_fleet"])
+ }
+ if vars, _ := out["vars"].([]any); len(vars) != 1 {
+ t.Fatalf("vars = %v, want PORT", out["vars"])
+ }
+}
+
+func TestConfigPutRefusesMissingSealedToOnFleetApp(t *testing.T) {
+ fx, token, k := skFleetShop(t, "code-sk-put-missing", true)
+ status, out := skPutSecret(t, fx, token, "API_KEY", skSeal(t, fx, k.pub, true), "")
+ want := "API_KEY cannot be checked, because the carlos CLI that sealed it did not say which key it used, and shop is placed on home. upgrade the carlos CLI and set API_KEY again"
+ if status != http.StatusBadRequest || out["error"] != want {
+ t.Fatalf("PUT = %d %v, want 400 %q", status, out, want)
+ }
+ if m := skStored(t, fx); len(m.Vars) != 0 {
+ t.Fatalf("a refused PUT stored %v", m.Vars)
+ }
+}
+
+func TestConfigPutRefusesWrongKeyOnFleetApp(t *testing.T) {
+ fx, token, _ := skFleetShop(t, "code-sk-put-wrong", true)
+ // A terminal with CARLOS_SECRETS_PUBKEY set to the deployment key.
+ depPub, depFP := mustTestSecretsKey()
+ status, out := skPutSecret(t, fx, token, "API_KEY", skSeal(t, fx, depPub, true), depFP)
+ want := "API_KEY was sealed to a key that home's boxes do not hold. unset CARLOS_SECRETS_PUBKEY in your terminal and set API_KEY again"
+ if status != http.StatusBadRequest || out["error"] != want {
+ t.Fatalf("PUT = %d %v, want 400 %q", status, out, want)
+ }
+ if m := skStored(t, fx); len(m.Vars) != 0 {
+ t.Fatalf("a refused PUT stored %v", m.Vars)
+ }
+}
+
+func TestConfigPutRefusesV1OnFleetApp(t *testing.T) {
+ fx, token, k := skFleetShop(t, "code-sk-put-v1", true)
+ status, out := skPutSecret(t, fx, token, "API_KEY", skSeal(t, fx, k.pub, false), k.fp)
+ want := "API_KEY was sealed in an older format that home's boxes do not accept. upgrade the carlos CLI and set API_KEY again"
+ if status != http.StatusBadRequest || out["error"] != want {
+ t.Fatalf("PUT = %d %v, want 400 %q", status, out, want)
+ }
+ if m := skStored(t, fx); len(m.Vars) != 0 {
+ t.Fatalf("a refused PUT stored %v", m.Vars)
+ }
+}
+
+func TestConfigPutStoresSealedToOnFleetApp(t *testing.T) {
+ fx, token, k := skFleetShop(t, "code-sk-put-ok", true)
+ env := skSeal(t, fx, k.pub, true)
+ if status, out := skPutSecret(t, fx, token, "API_KEY", env, k.fp); status != http.StatusOK {
+ t.Fatalf("PUT = %d %v", status, out)
+ }
+ got := skStored(t, fx).Vars["API_KEY"]
+ if got.Kind != "secret" || got.Envelope != env || got.SealedTo != k.fp {
+ t.Fatalf("stored = %+v, want the envelope verbatim, sealed to %s", got, k.fp)
+ }
+}
+
+func TestConfigPutOnKeylessFleetRefuses(t *testing.T) {
+ fx, token, _ := skFleetShop(t, "code-sk-put-keyless", false)
+ depPub, depFP := mustTestSecretsKey()
+ status, out := skPutSecret(t, fx, token, "API_KEY", skSeal(t, fx, depPub, true), depFP)
+ want := "home has no secrets key, so apps placed on it cannot hold secrets. run carlos fleets secrets-key home <pubkey> with a key from carlos secrets genkey"
+ if status != http.StatusConflict || out["error"] != want {
+ t.Fatalf("PUT = %d %v, want 409 %q", status, out, want)
+ }
+ if m := skStored(t, fx); len(m.Vars) != 0 {
+ t.Fatalf("a refused PUT stored %v", m.Vars)
+ }
+ // A plain env var on the same app is not a seal and is not refused.
+ if status, out := putJSON(t, configURL(fx, "shop"), map[string]any{"set": map[string]any{"PORT": map[string]string{"kind": "env", "value": "8080"}}}, token); status != http.StatusOK {
+ t.Fatalf("env PUT = %d %v", status, out)
+ }
+}
+
+func TestConfigPutAcceptsOldCLIOnPlatformApp(t *testing.T) {
+ fx, token, _ := fskFixture(t, "code-sk-put-platform")
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ depPub, depFP := mustTestSecretsKey()
+
+ // An older CLI: no sealed_to. Accepted, and stored without one.
+ if status, out := skPutSecret(t, fx, token, "OLD", skSeal(t, fx, depPub, false), ""); status != http.StatusOK {
+ t.Fatalf("old CLI PUT = %d %v", status, out)
+ }
+ // This CLI: sealed_to the deployment key. Accepted and kept.
+ if status, out := skPutSecret(t, fx, token, "NEW", skSeal(t, fx, depPub, false), depFP); status != http.StatusOK {
+ t.Fatalf("new CLI PUT = %d %v", status, out)
+ }
+ m := skStored(t, fx)
+ if m.Vars["OLD"].SealedTo != "" || m.Vars["NEW"].SealedTo != depFP {
+ t.Fatalf("stored sealed_to = %q, %q; want \"\" and %s", m.Vars["OLD"].SealedTo, m.Vars["NEW"].SealedTo, depFP)
+ }
+ // Present and not the deployment key: refused.
+ other := skNewKey(t)
+ status, out := skPutSecret(t, fx, token, "WRONG", skSeal(t, fx, other.pub, false), other.fp)
+ want := "WRONG was sealed to a key that this app's boxes do not hold. unset CARLOS_SECRETS_PUBKEY in your terminal and set WRONG again"
+ if status != http.StatusBadRequest || out["error"] != want {
+ t.Fatalf("PUT = %d %v, want 400 %q", status, out, want)
+ }
+ if _, ok := skStored(t, fx).Vars["WRONG"]; ok {
+ t.Fatal("a refused PUT stored WRONG")
+ }
+
+ // A console with no deployment key has nothing to compare: accepted, as
+ // today (the terminal's own key is the only one there is).
+ fx.srv.cfg.SecretsPub = ""
+ if status, out := skPutSecret(t, fx, token, "TERMINAL", skSeal(t, fx, other.pub, false), other.fp); status != http.StatusOK {
+ t.Fatalf("no deployment key PUT = %d %v", status, out)
+ }
+}
+
+// acctLockHolders is how many requests hold or wait on sqid's account lock.
+func acctLockHolders(s *Server, sqid string) int {
+ s.acctLocks.mu.Lock()
+ defer s.acctLocks.mu.Unlock()
+ if e := s.acctLocks.m[sqid]; e != nil {
+ return e.refs
+ }
+ return 0
+}
+
+// TestConfigPutRacesReplacement: a key replacement that arrives between the
+// PUT's key check and its write waits on the account lock, then sees the new
+// sealed value and refuses (spec §5.2.1). Deterministic: the hook runs inside
+// the PUT's critical section and returns only once the replacement is
+// waiting on the lock (or, if the lock were missing, has finished).
+func TestConfigPutRacesReplacement(t *testing.T) {
+ fx, token, k := skFleetShop(t, "code-sk-race", true)
+ k2 := skNewKey(t)
+ replaced := make(chan skAnswer, 1)
+ configPutBeforeApply = func() {
+ go func() {
+ replaced <- skPutAsync(fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": k2.pub}, token)
+ }()
+ deadline := time.Now().Add(5 * time.Second)
+ for acctLockHolders(fx.srv, fx.sqid) < 2 && len(replaced) == 0 && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ }
+ t.Cleanup(func() { configPutBeforeApply = nil })
+
+ if status, out := skPutSecret(t, fx, token, "API_KEY", skSeal(t, fx, k.pub, true), k.fp); status != http.StatusOK {
+ t.Fatalf("PUT = %d %v", status, out)
+ }
+ var got skAnswer
+ select {
+ case got = <-replaced:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the replacement never answered")
+ }
+ want := "home already has a different secrets key, and these apps hold sealed values: shop. replacing the key would leave them unreadable. unset each app's secrets with carlos secrets unset --app <app> <var>, then run this again"
+ if got.status != http.StatusConflict || got.body["error"] != want {
+ t.Fatalf("replacement = %d %v, want 409 %q", got.status, got.body, want)
+ }
+ if row := fskFleetRow(t, fx, "home"); row.SecretsKeyFP != k.fp {
+ t.Fatalf("home's key = %s, want it unchanged at %s", row.SecretsKeyFP, k.fp)
+ }
+}
+
+// TestConfigPutWithPlansDoesNotDeadlock: with plans on, planLock is the
+// account lock too; the PUT takes the account lock and nothing it calls
+// takes it again.
+func TestConfigPutWithPlansDoesNotDeadlock(t *testing.T) {
+ fx, token, k := skFleetShop(t, "code-sk-plans", true)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ secret := func() map[string]string {
+ return map[string]string{"kind": "secret", "envelope": skSeal(t, fx, k.pub, true), "sealed_to": k.fp}
+ }
+ bodies := []map[string]any{
+ {"set": map[string]any{"API_KEY": secret()}},
+ {"environment": "staging", "set": map[string]any{"API_KEY": secret()}},
+ }
+ done := make(chan skAnswer, len(bodies))
+ for _, b := range bodies {
+ go func() { done <- skPutAsync(configURL(fx, "shop"), b, token) }()
+ }
+ for range bodies {
+ select {
+ case got := <-done:
+ if got.err != nil || got.status != http.StatusOK {
+ t.Fatalf("PUT = %d %v %v, want 200", got.status, got.body, got.err)
+ }
+ case <-time.After(5 * time.Second):
+ // Not t.Fatal, nor a panic: either runs the fixture's cleanup,
+ // which closes the listener and waits for the deadlocked
+ // handler, so the run would hang until the test timeout.
+ fmt.Fprintln(os.Stderr, "TestConfigPutWithPlansDoesNotDeadlock: a config PUT with plans on did not answer within 5 s: the account lock is taken twice")
+ os.Exit(1)
+ }
+ }
+}
+
+// skAnswer is one request's answer from a goroutine, which must not call
+// t.Fatal.
+type skAnswer struct {
+ status int
+ body map[string]any
+ err error
+}
+
+// skPutAsync is putJSON for a goroutine: its failures are returned.
+func skPutAsync(u string, body any, bearer string) skAnswer {
+ raw, err := json.Marshal(body)
+ if err != nil {
+ return skAnswer{err: err}
+ }
+ req, err := http.NewRequest(http.MethodPut, u, bytes.NewReader(raw))
+ if err != nil {
+ return skAnswer{err: err}
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+bearer)
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return skAnswer{err: err}
+ }
+ defer res.Body.Close()
+ out := map[string]any{}
+ err = json.NewDecoder(res.Body).Decode(&out)
+ return skAnswer{status: res.StatusCode, body: out, err: err}
+}
+
+func TestBackfillAppPlacementsFromRoutes(t *testing.T) {
+ fx := newConsoleFixture(t)
+ for _, app := range []string{"shop", "other", "placed"} {
+ if _, err := fx.st.CreateAppIn(OpsAccountID, app, "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := fx.st.SetAppPlacement(OpsAccountID, "placed", "fleet/away"); err != nil {
+ t.Fatal(err)
+ }
+ reg := openTestReg(t, fx)
+ for _, rt := range []registry.Route{
+ {Host: "shop.example.com", Kind: "instance", App: "shop", Account: fx.sqid, Region: "fleet/home"},
+ {Host: "other.example.com", Kind: "instance", App: "other", Account: fx.sqid},
+ {Host: "placed.example.com", Kind: "instance", App: "placed", Account: fx.sqid, Region: "fleet/home"},
+ } {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := fx.srv.backfillAppPlacements(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ for app, want := range map[string]string{"shop": "fleet/home", "other": "", "placed": "fleet/away"} {
+ got, err := fx.st.AppPlacement(OpsAccountID, app)
+ if err != nil || got != want {
+ t.Fatalf("%s placement = %q %v, want %q", app, got, err, want)
+ }
+ }
+}