Fleet secrets key door: PUT /api/cli/fleets/{account}/{fleet}/secrets-key, owner-only, fingerprint computed by the console, refusing the deployment's key, a key another fleet holds (409) and a replacement while any app on the fleet holds a sealed value; the bucket owner record gains an append-only secrets_key_fps written before the registry row, admitted by the hostops classifier as an If-Match append and nothing else; the registration and no-op answers list stale sealed values; fleets ls gains secrets_key_fp and stale_secrets; the BYO and fleet pages show the key (FSK-C01 to C11); SetFleetSecretsKey refuses a key without its fingerprint and the reverse
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
approved_fleet_secrets_copy_test.go+6 −2internal/console/authcli.go+4 −0internal/console/claim_invariant_fixtures_test.go+1 −0internal/console/claim_invariant_probes_nonapp_test.go+34 −0internal/console/claim_invariant_probes_world_test.go+17 −0internal/console/fleetowner.go+67 −2internal/console/fleets.go+37 −5internal/console/fleetsecretskey.go+369 −0internal/console/fleetsecretskey_test.go+524 −0internal/console/svcroutes_test.go+3 −0internal/console/templates/fleet_byo.html+3 −1internal/console/templates/fleetdetail.html+7 −0internal/console/testdata/claim-routes.txt+1 −0internal/hostops/fleetowner_classifier.go+69 −14internal/hostops/fleetowner_classifier_test.go+100 −5internal/hostops/mutation_classifier.go+2 −1internal/registry/fleets.go+6 −1internal/registry/fleets_secrets_key_test.go+31 −0internal/release/release.go+7 −0
Intent
<task-notification> <task-id>ad7c57d97fa9c5f53</task-id> <tool-use-id>toolu_012kRsUZUuCHnvfMPk118BTe</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/ad7c57d97fa9c5f53.output</output-file> <status>completed</status> <summary>Agent "Implement Task 2: registry fleet key" 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. The commit exists (224feb60); git printed the known `packed-refs.lock` error, but `git log -1` shows the commit and the tree is clean. - Commit: 224feb60. It touches `internal/registry/fleets.go`, `remote.go`, `remote_dispatch.go`, `internal/console/view.go`, and the new `fleets_secrets_key_test.go`. - Tests: the three `TestFleetSecretsKey*` tests failed first (compile error), then passed, and `-run 'Fleet|SecretsKey'` passes. With the unique index replaced by a DROP INDEX, `TestFleetSecretsKeyIsUniqueAcrossFleets` and `TestFleetSecretsKeyOverRemote` fail. Build, vet, gofmt and the darwin, windows and linux-arm64 builds are clean. - Census: `make census-card` shows changes (new `SetFleetSecretsKey` unit, `migrateFleets` sites, `GetFleet`, `ListFleets` and `dispatchRemote` reads). I did not propose them, because the plan defers that to Task 11. The card is a dry run and wrote nothing. - `SetFleetSecretsKey` doesn't validate the shape of `pub` or `fp`, so Tasks 3 and 5 should. - The Go cache was read-only in the sandbox, so I ran the go commands unsandboxed, as the common brief allows. - The report is in `.superpowers/`, which is gitignored, so it isn't in the commit. - Report: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-secrets-key/.superpowers/sdd/2026-10-29-fleet-secrets-key/task-2-report.md`</result> <usage><subagent_tokens>70019</subagent_tokens><tool_uses>19</tool_uses><duration_ms>226586</duration_ms></usage> </task-notification>
<task-notification> <task-id>ae395c629264c60d8</task-id> <tool-use-id>toolu_01CxPXUqpWNZKaBCiQojC6nN</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/ae395c629264c60d8.output</output-file> <status>completed</status> <summary>Agent "Review Task 2 (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:** ✅ Spec compliant. There are three items I could not verify from this diff: - Whether the Task 3/5 door makes re-setting the same key a true no-op. - Whether the door derives the fingerprint from the key in one fixed way. The registry stores whatever fingerprint it is given. - The census proposal is deferred. The plan does schedule it in Task 11. **Task quality:** Approved. **Critical:** none. **Important:** none. All four named risks hold: - **(a)** `UpsertFleet` and `CreateFleet` never write the key columns, and the round-trip test checks this. - **(b)** The migration is idempotent. I ran the existing test `TestProvisionedSeedMigratesFromPreChangeDB`, which opens the same database more than once, and it passed. - **(c)** The only `consoleRegistry` implementers are `*registry.Registry` and the `fleetFailReg` test fake, which embeds the interface, so both compile. - **(d)** The index skips empty fingerprints. The uniqueness test would fail at setup under a full index. There are four Minor findings. Two are worth settling before Task 3: - `SetFleetSecretsKey` on the same fingerprint overwrites who set the key and when (fleets.go:300). The spec calls that case a no-op. - `SetFleetSecretsKey` accepts an empty fingerprint with a real key (fleets.go:286). That row would bypass the uniqueness check. Review: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-secrets-key/.superpowers/sdd/2026-10-29-fleet-secrets-key/task-2-review.md</result> <usage><subagent_tokens>68325</subagent_tokens><tool_uses>17</tool_uses><duration_ms>156455</duration_ms></usage> </task-notification>
Attributed to this commit: 29.7 g CO₂e (3,801,004 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 ff45d7fbf..fe9c212d9 100644 |
| --- a/approved_fleet_secrets_copy_test.go |
| +++ b/approved_fleet_secrets_copy_test.go |
| @@ -54,8 +54,12 @@ 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. Nothing is built yet: Task 0 writes the deck only. |
| -var fleetSecretsCopyBuilt = []string{} |
| +// row is approved. Task 3 built the door, BYO page and fleet page rows. |
| +var fleetSecretsCopyBuilt = []string{ |
| + "FSK-C01", "FSK-C02", "FSK-C03", "FSK-C04", |
| + "FSK-C05", "FSK-C06", "FSK-C07", "FSK-C08", |
| + "FSK-C09", "FSK-C10", "FSK-C11", |
| +} |
| func mustParseFleetSecretsRecord(t *testing.T) []copyRow { |
| t.Helper() |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index ceb8daa3b..7917df39b 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -940,6 +940,10 @@ func (s *Server) registerCLIRoutes() { |
| s.cliRoute("POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/rotate", svcrole.Set{}, s.handleAPIFleetRotateBox) |
| s.cliRoute("POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/detach", svcrole.Set{}, s.handleAPIFleetDetachBox) |
| s.cliRoute("POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/tags", svcrole.Set{}, s.handleAPIFleetTagBox) |
| + // The fleet's secrets key (fleetsecretskey.go): whoever sets it decides |
| + // who can read the fleet's future secrets, so the zero Set here too, and |
| + // an owner check inside. |
| + s.cliRoute("PUT /api/cli/fleets/{account}/{fleet}/secrets-key", svcrole.Set{}, s.handleAPIFleetSecretsKey) |
| // The service-credential API (apiservices.go, issue #220) — the |
| // principal that is not an address. Every door here takes the ZERO role |
| // set: a credential may never mint, rotate or revoke a credential, |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 774ece49b..5cf9c73d4 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1371,6 +1371,7 @@ var claimFixtures = map[string]claimFixture{ |
| "route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/detach": claimNonApp("detaches a fleet box"), |
| "route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/rotate": claimNonApp("rotates a fleet box's credential"), |
| "route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/tags": claimNonApp("tags a fleet box"), |
| + "route PUT /api/cli/fleets/{account}/{fleet}/secrets-key": claimNonApp("registers a fleet's secrets key: the registry row and an append to the fleet owner record; names no app"), |
| "route POST /api/cli/ops/hosts/{host}/resolve": {refused: &claimRefusalFixture{ |
| apps: []claimAppRef{{Account: "bab", App: "jam"}}, |
| setup: func(t *testing.T, cx *claimCase) { |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index 3e718046e..f4d6b207f 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -17,6 +17,7 @@ import ( |
| "testing" |
| "time" |
| + "github.com/carlosframework/platform/internal/appconfig" |
| "github.com/carlosframework/platform/internal/billing" |
| "github.com/carlosframework/platform/internal/billing/billingtest" |
| "github.com/carlosframework/platform/internal/economics" |
| @@ -671,6 +672,39 @@ var claimNonAppProbes = map[string]claimProbe{ |
| return "" |
| }, |
| }, |
| + "route PUT /api/cli/fleets/{account}/{fleet}/secrets-key": { |
| + setup: func(t *testing.T, cx *claimCase) { |
| + cx.fleet(t) |
| + _, pub, err := appconfig.GenerateKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fp, err := appconfig.PublicFingerprint(pub) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cx.vars["fleetpub"], cx.vars["fleetfp"] = pub, fp |
| + }, |
| + do: func(t *testing.T, cx *claimCase) claimReply { |
| + return cx.apiReply(t, http.MethodPut, "/api/cli/fleets/bab/pi/secrets-key", `{"pubkey":"`+cx.vars["fleetpub"]+`"}`) |
| + }, |
| + body: []string{`"fingerprint"`, `"pi"`}, |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + f, ok := cx.fleetRow(t, "pi") |
| + if !ok || f.SecretsKeyFP != cx.vars["fleetfp"] { |
| + return "the registry row of fleet pi has no secrets key" |
| + } |
| + body, _, err := cx.rel.Get(context.Background(), release.FleetOwnerKey(f.Account, "pi")) |
| + if err != nil { |
| + return "fleet pi has no owner record: " + err.Error() |
| + } |
| + var rec release.FleetOwner |
| + if json.Unmarshal(body, &rec) != nil || len(rec.SecretsKeyFPs) != 1 || rec.SecretsKeyFPs[0] != cx.vars["fleetfp"] { |
| + return "fleet pi's owner record does not list the key" |
| + } |
| + return "" |
| + }, |
| + }, |
| // ---- object-storage entitlements ---- |
| "route POST /api/cli/accounts/{account}/store/apply": { |
diff --git a/internal/console/claim_invariant_probes_world_test.go b/internal/console/claim_invariant_probes_world_test.go| index 1abdbaec3..3ba051883 100644 |
| --- a/internal/console/claim_invariant_probes_world_test.go |
| +++ b/internal/console/claim_invariant_probes_world_test.go |
| @@ -58,6 +58,23 @@ func (cx *claimCase) fleetBox(t *testing.T, fleet, label string) (registry.Fleet |
| return registry.FleetBox{}, false |
| } |
| +// fleetRow reads one fleet's registry row. |
| +func (cx *claimCase) fleetRow(t *testing.T, name string) (registry.Fleet, bool) { |
| + t.Helper() |
| + reg, err := registry.Open(cx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f, err := reg.GetFleet(name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if f == nil { |
| + return registry.Fleet{}, false |
| + } |
| + return *f, true |
| +} |
| + |
| // fleetNamed reports whether the registry holds a fleet of that name. |
| func (cx *claimCase) fleetNamed(t *testing.T, name string) bool { |
| t.Helper() |
diff --git a/internal/console/fleetowner.go b/internal/console/fleetowner.go| index d5ffcf029..23b05176a 100644 |
| --- a/internal/console/fleetowner.go |
| +++ b/internal/console/fleetowner.go |
| @@ -7,8 +7,10 @@ package console |
| // the row's account. The console writes it from the fleet row: at create |
| // (handleAPIFleetNew), on the retry that repairs a failed create, and once |
| // per console start for every fleet (backfillFleetOwners). It is only ever |
| -// created, never replaced: hostops' fleet-owner family admits nothing else. |
| -// Removing it belongs to the fleet removal change, which does not exist yet. |
| +// created, and then only ever gains fleet secrets key fingerprints |
| +// (recordFleetKeyFP, plan ruling R-4): hostops' fleet-owner family admits a |
| +// create and that append, nothing else. Removing it belongs to the fleet |
| +// removal change, which does not exist yet. |
| import ( |
| "context" |
| @@ -17,6 +19,7 @@ import ( |
| "fmt" |
| "log" |
| "os" |
| + "slices" |
| "time" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -26,6 +29,10 @@ import ( |
| // fleetOwnerWriteTimeout bounds one record write: the read, and the Put. |
| const fleetOwnerWriteTimeout = 10 * time.Second |
| +// fleetKeyRecordAttempts bounds recordFleetKeyFP's read-append-Put loop |
| +// against concurrent writers of the same record. |
| +const fleetKeyRecordAttempts = 3 |
| + |
| // errFleetOwnerConflict is a record at the key that does not name this |
| // fleet and account. It is never overwritten. |
| var errFleetOwnerConflict = errors.New("the fleet owner record names another account or fleet") |
| @@ -101,6 +108,64 @@ func fleetOwnerRecorded(ctx context.Context, st release.Store, key string, f reg |
| return true, nil |
| } |
| +// recordFleetKeyFP lists fp on f's bucket owner record: it creates the |
| +// record, naming f and listing fp, when there is none, and otherwise appends |
| +// fp (when it is not already listed) with If-Match on the etag it read. |
| +// Nothing here ever removes a fingerprint, and a record naming another |
| +// fleet or account is never written over (errFleetOwnerConflict). |
| +func (s *Server) recordFleetKeyFP(ctx context.Context, f registry.Fleet, fp string) error { |
| + st := s.cfg.Releases |
| + if st == nil { |
| + return errors.New("fleet owner record: no deployment store") |
| + } |
| + if !release.ValidAccount(f.Account) || !registry.ValidTunnelName(f.Name) { |
| + return fmt.Errorf("fleet owner record: fleet %q of account %q is not a valid key", f.Name, f.Account) |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, fleetOwnerWriteTimeout) |
| + defer cancel() |
| + key := release.FleetOwnerKey(f.Account, f.Name) |
| + for range fleetKeyRecordAttempts { |
| + body, etag, err := st.Get(ctx, key) |
| + var rec release.FleetOwner |
| + switch { |
| + case errors.Is(err, os.ErrNotExist): |
| + createdAt := f.CreatedAt |
| + if createdAt == 0 { |
| + createdAt = time.Now().Unix() |
| + } |
| + rec, etag = release.FleetOwner{Fleet: f.Name, Account: f.Account, CreatedAt: createdAt}, "" |
| + case err != nil: |
| + return fmt.Errorf("read %s: %w", key, err) |
| + default: |
| + if err := json.Unmarshal(body, &rec); err != nil { |
| + return fmt.Errorf("read %s: %w", key, err) |
| + } |
| + if rec.Fleet != f.Name || rec.Account != f.Account { |
| + return fmt.Errorf("%s: %w", key, errFleetOwnerConflict) |
| + } |
| + if slices.Contains(rec.SecretsKeyFPs, fp) { |
| + return nil |
| + } |
| + } |
| + rec.SecretsKeyFPs = append(rec.SecretsKeyFPs, fp) |
| + next, err := json.Marshal(rec) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = st.Put(ctx, key, next, etag) |
| + if errors.Is(err, release.ErrCASConflict) { |
| + // Another writer moved the record between the read and the |
| + // Put: read it again and judge what it wrote. |
| + continue |
| + } |
| + if err != nil { |
| + return fmt.Errorf("fleet owner record %s: %w", key, err) |
| + } |
| + return nil |
| + } |
| + return fmt.Errorf("fleet owner record %s: still changing after %d attempts: %w", key, fleetKeyRecordAttempts, release.ErrCASConflict) |
| +} |
| + |
| // backfillFleetOwners writes the record for every fleet ListFleets returns. |
| // It runs once per console start, is idempotent (a record already in place |
| // costs one read and no write), logs and continues past one fleet's error, |
diff --git a/internal/console/fleets.go b/internal/console/fleets.go| index fba1e0ad0..722b9db37 100644 |
| --- a/internal/console/fleets.go |
| +++ b/internal/console/fleets.go |
| @@ -60,6 +60,13 @@ type fleetView struct { |
| Name string `json:"name"` |
| Bucket string `json:"bucket"` |
| Boxes []fleetBoxView `json:"boxes"` |
| + // SecretsKeyFP is the fleet's registered secrets key fingerprint, and |
| + // StaleSecrets how many sealed values of its apps are not sealed to it |
| + // (fleetStaleValues). Both are omitted for a fleet with no key, and the |
| + // count when nothing is stale, so a fleet listed before keys existed |
| + // reads as it always did. |
| + SecretsKeyFP string `json:"secrets_key_fp,omitempty"` |
| + StaleSecrets int `json:"stale_secrets,omitempty"` |
| } |
| // apiFleet resolves and authorizes one {account}/{fleet} CLI API request: |
| @@ -74,24 +81,36 @@ func (s *Server) apiFleet(w http.ResponseWriter, r *http.Request) (addr string, |
| if !ok { |
| return "", nil, nil, nil, false |
| } |
| + fleet, reg, ok = s.apiFleetOf(w, r, acct) |
| + if !ok { |
| + return "", nil, nil, nil, false |
| + } |
| + return addr, acct, fleet, reg, true |
| +} |
| + |
| +// apiFleetOf is apiFleet's fleet half for a door that has already resolved |
| +// the account its own way (the secrets key door's owner gate): the |
| +// {fleet} segment read from the registry, with an unknown fleet and one |
| +// owned by another account answering the same 404. |
| +func (s *Server) apiFleetOf(w http.ResponseWriter, r *http.Request, acct *Account) (*registry.Fleet, consoleRegistry, bool) { |
| reg, err := openRegistry(s.cfg.Registry) |
| if err != nil { |
| log.Printf("console: api fleet: open registry: %v", err) |
| jsonError(w, http.StatusInternalServerError, "could not reach the fleet registry") |
| - return "", nil, nil, nil, false |
| + return nil, nil, false |
| } |
| name := r.PathValue("fleet") |
| f, err := reg.GetFleet(name) |
| if err != nil { |
| log.Printf("console: api fleet %s/%s: %v", acct.Sqid, name, err) |
| jsonError(w, http.StatusInternalServerError, "could not read the fleet") |
| - return "", nil, nil, nil, false |
| + return nil, nil, false |
| } |
| if f == nil || f.Account != acct.Sqid { |
| http.NotFound(w, r) |
| - return "", nil, nil, nil, false |
| + return nil, nil, false |
| } |
| - return addr, acct, f, reg, true |
| + return f, reg, true |
| } |
| // findFleetBox looks up one box by label within a fleet already proven to |
| @@ -303,7 +322,20 @@ func (s *Server) handleAPIFleetList(w http.ResponseWriter, r *http.Request) { |
| jsonError(w, http.StatusInternalServerError, "could not list fleets") |
| return |
| } |
| - out = append(out, fleetView{Name: f.Name, Bucket: f.Bucket, Boxes: fleetBoxViews(boxes)}) |
| + view := fleetView{Name: f.Name, Bucket: f.Bucket, Boxes: fleetBoxViews(boxes), SecretsKeyFP: f.SecretsKeyFP} |
| + if f.SecretsKeyFP != "" { |
| + // The stale count repeats the key door's report until it is |
| + // zero (spec §5.1 B2). A bucket that cannot be read costs the |
| + // count, not the list. |
| + stale, err := s.fleetStaleValues(r.Context(), acct, f.Name, f.SecretsKeyFP) |
| + if err != nil { |
| + log.Printf("console: fleet list %s: stale values of %s: %v", acct.Sqid, f.Name, err) |
| + } |
| + for _, a := range stale { |
| + view.StaleSecrets += len(a.Vars) + len(a.Minted) |
| + } |
| + } |
| + out = append(out, view) |
| } |
| writeJSON(w, http.StatusOK, map[string]any{"fleets": out}) |
| } |
diff --git a/internal/console/fleetsecretskey.go b/internal/console/fleetsecretskey.go| new file mode 100644 |
| index 000000000..bdb95bb95 |
| --- /dev/null |
| +++ b/internal/console/fleetsecretskey.go |
| @@ -0,0 +1,369 @@ |
| +package console |
| + |
| +// The fleet secrets key door (fleet secrets key spec §5.1, §5.6; plan Task |
| +// 3): an account owner registers the public half of a fleet's own secrets |
| +// key, so apps placed on the fleet can be sealed to a key its boxes hold |
| +// instead of the deployment's. |
| +// |
| +// Three facts hold the security of it. Only an account OWNER may set the key |
| +// (apiOwnerAccountFor), because whoever sets it decides who can read the |
| +// fleet's future secrets. No two fleets share a key: the registry's unique |
| +// index on the fingerprint is the authority (ErrFleetKeyInUse), because a |
| +// fleet's boxes can read the whole account's app prefix and v2 binding does |
| +// not stop a holder of the private key (spec A3). And the fingerprint is |
| +// always the console's own, computed from the parsed key, never taken from |
| +// the request. |
| +// |
| +// The bucket owner record (release.FleetOwner) lists every fingerprint ever |
| +// registered for the fleet, append-only, and the door writes it BEFORE the |
| +// registry row commits: a failed record write fails the registration, and a |
| +// registration the registry then refuses still leaves the record listing |
| +// the key that stays registered (plan ruling R-4). Direct-bucket mode reads |
| +// that list; no box does. |
| + |
| +import ( |
| + "context" |
| + "encoding/base64" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "sort" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/mail" |
| + "github.com/carlosframework/platform/internal/objstore" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// fleetSecretsKeyTimeout bounds the door's bucket work: the sealed-value |
| +// reads of every app on the fleet, and the owner record write. |
| +const fleetSecretsKeyTimeout = 30 * time.Second |
| + |
| +// staleApp is one app's line of the key door's stale report: the sealed |
| +// vars, across every bundle, not sealed to the fleet's key. Minted holds the |
| +// ones the console minted (store, mail, relay credentials), Vars the rest. |
| +type staleApp struct { |
| + App string `json:"app"` |
| + Vars []string `json:"vars"` |
| + Minted []string `json:"minted"` |
| +} |
| + |
| +// handleAPIFleetSecretsKey answers `carlos fleets secrets-key`: PUT |
| +// /api/cli/fleets/{account}/{fleet}/secrets-key with {"pubkey": "<base64>"}. |
| +// It answers {"fleet", "fingerprint", "changed", "stale"}; changed is false |
| +// for the same key registered again, which writes nothing. stale is absent |
| +// only when the sealed values could not be read after a registration that |
| +// did commit; running the door again reports it. |
| +// |
| +// Every refusal comes before the first write. The replacement check runs |
| +// under the account lock, which every seal of an app's config also takes |
| +// (spec §5.2.1), so no value can be sealed to the old key between the check |
| +// and the registry commit. |
| +func (s *Server) handleAPIFleetSecretsKey(w http.ResponseWriter, r *http.Request) { |
| + p, acct, ok := s.apiOwnerAccountFor(w, r, "set a fleet's secrets key") |
| + if !ok { |
| + return |
| + } |
| + fleet, reg, ok := s.apiFleetOf(w, r, acct) |
| + if !ok { |
| + return |
| + } |
| + if !s.allowWrite(p, time.Now()) { |
| + jsonError(w, http.StatusTooManyRequests, textTooManyRequests) |
| + return |
| + } |
| + var req struct { |
| + Pubkey string `json:"pubkey"` |
| + } |
| + if !readJSON(w, r, &req) { |
| + return |
| + } |
| + key, err := appconfig.ParsePublicKey(req.Pubkey, "pubkey") |
| + if err != nil { |
| + jsonError(w, http.StatusBadRequest, "that is not a public secrets key. use the CARLOS_SECRETS_PUBKEY value that carlos secrets genkey prints") |
| + return |
| + } |
| + // The console's own reading of the key, never the request's bytes. |
| + fp := appconfig.KeyFingerprint(key) |
| + pub := base64.StdEncoding.EncodeToString(key.Bytes()) |
| + if fp == s.expectedSecretsFP() { |
| + jsonError(w, http.StatusBadRequest, "that is the platform's own secrets key, and a fleet needs its own. mint a new pair with carlos secrets genkey and register its public half") |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), fleetSecretsKeyTimeout) |
| + defer cancel() |
| + actor := auditActor(p, acct) |
| + |
| + unlock := s.lockAccount(acct.Sqid) |
| + locked := true |
| + defer func() { |
| + if locked { |
| + unlock() |
| + } |
| + }() |
| + notRecorded := func(status int) { |
| + jsonError(w, status, fmt.Sprintf("the key was not recorded for %s and nothing was changed. run carlos fleets secrets-key %s %s again", fleet.Name, fleet.Name, pub)) |
| + } |
| + // The row as it is now, under the lock: the key it holds decides between |
| + // a first key, a replacement and the no-op. |
| + row, err := reg.GetFleet(fleet.Name) |
| + if err != nil || row == nil || row.Account != acct.Sqid { |
| + log.Printf("console: fleet secrets key %s/%s: reread: %+v, %v", acct.Sqid, fleet.Name, row, err) |
| + notRecorded(http.StatusInternalServerError) |
| + return |
| + } |
| + changed := row.SecretsKeyFP != fp |
| + if changed { |
| + if row.SecretsKeyFP != "" { |
| + // §5.6: no replacement while any app on the fleet holds a sealed |
| + // value, whatever key it says it is sealed to. |
| + apps, err := s.fleetHasSealedValues(ctx, acct, row.Name) |
| + if err != nil { |
| + log.Printf("console: fleet secrets key %s/%s: sealed values: %v", acct.Sqid, row.Name, err) |
| + notRecorded(http.StatusBadGateway) |
| + return |
| + } |
| + if len(apps) > 0 { |
| + jsonError(w, http.StatusConflict, fmt.Sprintf("%s already has a different secrets key, and these apps hold sealed values: %s. replacing the key would leave them unreadable. unset each app's secrets with carlos secrets unset --app <app> <var>, then run this again", row.Name, strings.Join(apps, ", "))) |
| + return |
| + } |
| + } |
| + if err := s.recordFleetKeyFP(ctx, *row, fp); err != nil { |
| + log.Printf("console: fleet secrets key %s/%s: owner record: %v", acct.Sqid, row.Name, err) |
| + notRecorded(http.StatusBadGateway) |
| + return |
| + } |
| + if err := reg.SetFleetSecretsKey(row.Name, pub, fp, actor, time.Now().Unix()); err != nil { |
| + if errors.Is(err, registry.ErrFleetKeyInUse) { |
| + jsonError(w, http.StatusConflict, "another fleet already uses this secrets key, and every fleet needs its own. mint a new pair with carlos secrets genkey and register its public half") |
| + return |
| + } |
| + log.Printf("console: fleet secrets key %s/%s: registry: %v", acct.Sqid, row.Name, err) |
| + notRecorded(http.StatusInternalServerError) |
| + return |
| + } |
| + } |
| + unlock() |
| + locked = false |
| + if changed { |
| + s.audit(acct, row.Name, actor, "fleet-secrets-key", "registered secrets key "+fp+" for fleet "+row.Name+" (cli)") |
| + } |
| + |
| + answer := map[string]any{"fleet": row.Name, "fingerprint": fp, "changed": changed} |
| + stale, err := s.fleetStaleValues(ctx, acct, row.Name, fp) |
| + if err != nil { |
| + log.Printf("console: fleet secrets key %s/%s: stale values: %v", acct.Sqid, row.Name, err) |
| + } else { |
| + answer["stale"] = stale |
| + } |
| + writeJSON(w, http.StatusOK, answer) |
| +} |
| + |
| +// fleetHasSealedValues lists, sorted, the apps placed on fleet that hold any |
| +// sealed var in any bundle, whatever key it says it is sealed to (§5.6: a |
| +// value with no sealed_to may still be sealed to the current key). |
| +func (s *Server) fleetHasSealedValues(ctx context.Context, acct *Account, fleet string) ([]string, error) { |
| + apps, err := s.fleetPlacedApps(acct, fleet) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var out []string |
| + for _, app := range apps { |
| + vars, _, err := s.appSealedVars(ctx, acct.Sqid, app) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if len(vars) > 0 { |
| + out = append(out, app) |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +// fleetStaleValues reports, for every app placed on fleet, the sealed vars |
| +// in any bundle (default, named environments, instance overlays) whose |
| +// sealed_to is not fp, an absent sealed_to included: values the fleet's boxes |
| +// cannot open. Each app's names are split into those the console minted |
| +// (store, mail and relay credentials) and the rest, each list sorted and |
| +// never nil. Apps with nothing stale are left out. It is the stale report of |
| +// the key door and of the fleet list, and nothing else: it refuses nothing. |
| +func (s *Server) fleetStaleValues(ctx context.Context, acct *Account, fleet, fp string) ([]staleApp, error) { |
| + apps, err := s.fleetPlacedApps(acct, fleet) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out := make([]staleApp, 0) |
| + for _, app := range apps { |
| + vars, envs, err := s.appSealedVars(ctx, acct.Sqid, app) |
| + if err != nil { |
| + return nil, err |
| + } |
| + stale := map[string]bool{} |
| + for _, v := range vars { |
| + if v.sealedTo != fp { |
| + stale[v.name] = true |
| + } |
| + } |
| + if len(stale) == 0 { |
| + continue |
| + } |
| + minted, err := s.mintedVarNames(ctx, acct.Sqid, app, envs) |
| + if err != nil { |
| + return nil, err |
| + } |
| + line := staleApp{App: app, Vars: []string{}, Minted: []string{}} |
| + for name := range stale { |
| + if minted[name] { |
| + line.Minted = append(line.Minted, name) |
| + } else { |
| + line.Vars = append(line.Vars, name) |
| + } |
| + } |
| + sort.Strings(line.Vars) |
| + sort.Strings(line.Minted) |
| + out = append(out, line) |
| + } |
| + return out, nil |
| +} |
| + |
| +// fleetPlacedApps lists, sorted, the account's live apps placed on fleet, |
| +// read as appPlacement reads one: the store's placement column, then the |
| +// routes for an app placed before the column existed (one route listing for |
| +// all of them). |
| +func (s *Server) fleetPlacedApps(acct *Account, fleet string) ([]string, error) { |
| + apps, err := s.store.AppsIn(acct.ID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + target := registry.PlacementTarget(fleet) |
| + var routes []registry.Route |
| + listed := false |
| + var out []string |
| + for _, app := range apps { |
| + placed, err := s.store.AppPlacement(acct.ID, app) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if placed == "" { |
| + if !listed { |
| + reg, err := openRegistry(s.cfg.Registry) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if routes, err = reg.List(); err != nil { |
| + return nil, err |
| + } |
| + listed = true |
| + } |
| + placed = fleetFromRoutes(routes, acct.Sqid, app) |
| + } |
| + if placed == target { |
| + out = append(out, app) |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +// sealedVar is one sealed var of one bundle. |
| +type sealedVar struct{ name, sealedTo string } |
| + |
| +// appSealedVars reads every sealed var of app: its default bundle, each |
| +// named environment and each instance overlay. It also returns the named |
| +// environments it read. A console with no deployment store has none. |
| +func (s *Server) appSealedVars(ctx context.Context, sqid, app string) ([]sealedVar, []string, error) { |
| + st := s.cfg.Releases |
| + if st == nil { |
| + return nil, nil, nil |
| + } |
| + var out []sealedVar |
| + add := func(m *appconfig.Manifest) { |
| + if m == nil { |
| + return |
| + } |
| + for name, v := range m.Vars { |
| + if v.Kind == "secret" { |
| + out = append(out, sealedVar{name, v.SealedTo}) |
| + } |
| + } |
| + } |
| + def, err := appconfig.Get(ctx, st, sqid, app) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + add(def) |
| + envs, err := appconfig.ListEnvironments(ctx, st, sqid, app) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + for _, env := range envs { |
| + if !appconfig.ValidEnvironmentName(env) { |
| + continue |
| + } |
| + m, _, found, err := appconfig.GetEnvironment(ctx, st, sqid, app, env) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + if found { |
| + add(m) |
| + } |
| + } |
| + prefix := appconfig.InstancesConfigPrefix(sqid, app) |
| + keys, err := st.List(ctx, prefix) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + for _, k := range keys { |
| + host, ok := strings.CutSuffix(strings.TrimPrefix(k, prefix), ".json") |
| + if !ok || !appconfig.ValidInstanceHost(host) { |
| + continue |
| + } |
| + m, _, found, err := appconfig.LoadInstanceConfig(ctx, st, sqid, app, host) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + if found { |
| + add(m) |
| + } |
| + } |
| + return out, envs, nil |
| +} |
| + |
| +// mintedVarNames is the set of sealed var names the console mints for app: |
| +// the store's key halves and scan callback secret under each of its store |
| +// prefixes (the app's and each named environment's, and the default), the |
| +// SMTP password under each sender's prefix (and the default), and the relay |
| +// credential. |
| +func (s *Server) mintedVarNames(ctx context.Context, sqid, app string, envs []string) (map[string]bool, error) { |
| + st := s.cfg.Releases |
| + names := map[string]bool{relayVar: true} |
| + storePrefixes := []string{objstore.DefaultEnvPrefix} |
| + for _, env := range append([]string{""}, envs...) { |
| + rec, _, err := objstore.GetIn(ctx, st, sqid, app, env) |
| + if err != nil { |
| + return nil, err |
| + } |
| + storePrefixes = append(storePrefixes, storeEffectivePrefix(rec)) |
| + } |
| + for _, p := range storePrefixes { |
| + _, _, _, accessKey, secretKey := objstore.EnvNames(p) |
| + names[accessKey], names[secretKey], names[p+"_SCAN_CALLBACK_SECRET"] = true, true, true |
| + } |
| + mailPrefixes := []string{mail.DefaultEnvPrefix} |
| + senders, err := mail.ListSenders(ctx, st, sqid, app) |
| + if err != nil { |
| + return nil, err |
| + } |
| + for _, sn := range senders { |
| + if sn != nil && sn.Declared != nil && sn.Declared.EnvPrefix != "" { |
| + mailPrefixes = append(mailPrefixes, sn.Declared.EnvPrefix) |
| + } |
| + } |
| + for _, p := range mailPrefixes { |
| + _, _, _, pass, _ := mail.EnvNames(p) |
| + names[pass] = true |
| + } |
| + return names, nil |
| +} |
diff --git a/internal/console/fleetsecretskey_test.go b/internal/console/fleetsecretskey_test.go| new file mode 100644 |
| index 000000000..d4f90ee43 |
| --- /dev/null |
| +++ b/internal/console/fleetsecretskey_test.go |
| @@ -0,0 +1,524 @@ |
| +package console |
| + |
| +// The fleet secrets key door (fleet secrets key spec §5.1, §5.6; plan Task |
| +// 3): PUT /api/cli/fleets/{account}/{fleet}/secrets-key. The properties that |
| +// matter, in the order they would hurt if lost: only an account owner sets a |
| +// fleet's key (whoever sets it decides who can read the fleet's future |
| +// secrets), no two fleets share a key, the deployment's own key is never a |
| +// fleet's, the bucket owner record lists every key ever registered before |
| +// the registry row commits, and a key is not replaced while an app on the |
| +// fleet holds sealed values. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/hostops" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// fskKey mints a fresh fleet keypair's public half and its fingerprint. |
| +func fskKey(t *testing.T) (pub, fp string) { |
| + t.Helper() |
| + _, pub, err := appconfig.GenerateKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fp, err = appconfig.PublicFingerprint(pub) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return pub, fp |
| +} |
| + |
| +// fskURL is the key door of one fleet under one account segment. |
| +func fskURL(fx *consoleFixture, acct, fleet string) string { |
| + return fleetsURL(fx, acct) + "/" + fleet + "/secrets-key" |
| +} |
| + |
| +// fskFixture is fleetOwnerFixture with a deployment secrets key and the |
| +// owner's fleet home created through its door. |
| +func fskFixture(t *testing.T, code string) (*consoleFixture, string, *fleetOwnerSpy) { |
| + t.Helper() |
| + fx, token, spy := fleetOwnerFixture(t, code) |
| + fx.srv.cfg.SecretsPub, _ = mustTestSecretsKey() |
| + if status, body := postJSON(t, fleetsURL(fx, fx.sqid)+"/new", map[string]string{"name": "home", "bucket": "home-data"}, token); status != http.StatusOK { |
| + t.Fatalf("create home = %d %v", status, body) |
| + } |
| + return fx, token, spy |
| +} |
| + |
| +// fskFleetRow reads a fleet's registry row through a second handle. |
| +func fskFleetRow(t *testing.T, fx *consoleFixture, name string) registry.Fleet { |
| + t.Helper() |
| + reg, err := registry.Open(fx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f, err := reg.GetFleet(name) |
| + if err != nil || f == nil { |
| + t.Fatalf("fleet %s: %+v, %v", name, f, err) |
| + } |
| + return *f |
| +} |
| + |
| +// fskAway gives bob his own account cdef with a fleet away, through the |
| +// doors, and returns his token. |
| +func fskAway(t *testing.T, fx *consoleFixture) string { |
| + t.Helper() |
| + if err := fx.st.CreateAccount(42, "cdef", "widgets", "bob@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + bob := cliToken(t, fx, "bob@keymail.dev", "code-fsk-bob") |
| + if status, body := postJSON(t, fleetsURL(fx, "cdef")+"/new", map[string]string{"name": "away", "bucket": "away-data"}, bob); status != http.StatusOK { |
| + t.Fatalf("create away = %d %v", status, body) |
| + } |
| + return bob |
| +} |
| + |
| +// fskPlaceShop claims app shop in the fixture account and places it on |
| +// fleet through the place door. |
| +func fskPlaceShop(t *testing.T, fx *consoleFixture, token, fleet string) { |
| + t.Helper() |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status, body := postJSON(t, placeURL(fx, "shop"), map[string]string{"target": "fleet/" + fleet}, token); status != http.StatusOK { |
| + t.Fatalf("place shop = %d %v", status, body) |
| + } |
| +} |
| + |
| +// fskSeal is a real envelope for shop, sealed to the deployment key, marked |
| +// sealed to sealedTo ("" for a value written before sealed_to existed). |
| +func fskSeal(t *testing.T, fx *consoleFixture, sealedTo string) appconfig.Var { |
| + t.Helper() |
| + pub, err := appconfig.ParsePublicKey(fx.srv.cfg.SecretsPub, "test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + env, err := appconfig.Seal(pub, appconfig.Binding{Account: fx.sqid, App: "shop"}, []byte("value")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return appconfig.Var{Kind: "secret", Envelope: env, SealedTo: sealedTo} |
| +} |
| + |
| +// fskSetSecrets writes sealed vars into shop's default bundle. |
| +func fskSetSecrets(t *testing.T, fx *consoleFixture, vars map[string]appconfig.Var) { |
| + t.Helper() |
| + if err := appconfig.SetSecret(context.Background(), fx.rel, fx.sqid, "shop", vars); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// fskOwnerFPs is the secrets_key_fps of home's owner record. |
| +func fskOwnerFPs(t *testing.T, fx *consoleFixture) []string { |
| + t.Helper() |
| + rec, err := readFleetOwner(t, fx.rel, fx.sqid, "home") |
| + if err != nil { |
| + t.Fatalf("owner record: %v", err) |
| + } |
| + return rec.SecretsKeyFPs |
| +} |
| + |
| +// fskStale decodes the door's stale answer. |
| +func fskStale(t *testing.T, body map[string]any) []staleApp { |
| + t.Helper() |
| + raw, err := json.Marshal(body["stale"]) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var out []staleApp |
| + if err := json.Unmarshal(raw, &out); err != nil { |
| + t.Fatalf("stale = %v: %v", body["stale"], err) |
| + } |
| + return out |
| +} |
| + |
| +func TestFleetSecretsKeyOwnerOnly(t *testing.T) { |
| + fx, owner, _ := fskFixture(t, "code-fsk-owner") |
| + if err := fx.st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + member := cliToken(t, fx, "alice@keymail.dev", "code-fsk-member") |
| + stranger := cliToken(t, fx, "eve@keymail.dev", "code-fsk-stranger") |
| + pub, fp := fskKey(t) |
| + |
| + status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pub}, member) |
| + if status != http.StatusForbidden || body["error"] != "only an account owner can set a fleet's secrets key" { |
| + t.Fatalf("member = %d %v, want 403 with the owner sentence", status, body) |
| + } |
| + if row := fskFleetRow(t, fx, "home"); row.SecretsKeyFP != "" || row.SecretsPub != "" { |
| + t.Fatalf("a member's request set the key: %+v", row) |
| + } |
| + if fps := fskOwnerFPs(t, fx); len(fps) != 0 { |
| + t.Fatalf("a member's request wrote the owner record: %v", fps) |
| + } |
| + want := canonicalNotFound(t) |
| + st, h, out := rawReq(t, http.MethodPut, fskURL(fx, fx.sqid, "home"), stranger, `{"pubkey":"`+pub+`"}`) |
| + assertNotFound(t, "a non-member", want, st, h, out) |
| + |
| + if status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pub}, owner); status != http.StatusOK || body["fingerprint"] != fp || body["fleet"] != "home" { |
| + t.Fatalf("owner = %d %v, want 200 naming home and %s", status, body, fp) |
| + } |
| + if row := fskFleetRow(t, fx, "home"); row.SecretsKeyFP != fp || row.SecretsPub != pub || row.SecretsKeySetBy != "paul@keymail.dev" || row.SecretsKeySetAt == 0 { |
| + t.Fatalf("registry row = %+v, want the key, set by paul", row) |
| + } |
| +} |
| + |
| +func TestFleetSecretsKeyRefusals(t *testing.T) { |
| + fx, token, _ := fskFixture(t, "code-fsk-refusals") |
| + bob := fskAway(t, fx) |
| + pub, _ := fskKey(t) |
| + |
| + // Unknown, and another account's: the same bytes. |
| + want := canonicalNotFound(t) |
| + for _, c := range []struct{ what, fleet string }{ |
| + {"an unknown fleet", "ghost"}, |
| + {"another account's fleet", "away"}, |
| + } { |
| + st, h, out := rawReq(t, http.MethodPut, fskURL(fx, fx.sqid, c.fleet), token, `{"pubkey":"`+pub+`"}`) |
| + assertNotFound(t, c.what, want, st, h, out) |
| + } |
| + |
| + deployment, _ := mustTestSecretsKey() |
| + notAKey := "that is not a public secrets key. use the CARLOS_SECRETS_PUBKEY value that carlos secrets genkey prints" |
| + for _, c := range []struct { |
| + what, pubkey string |
| + status int |
| + err string |
| + }{ |
| + {"no key at all", "", http.StatusBadRequest, notAKey}, |
| + {"bad base64", "not base64!", http.StatusBadRequest, notAKey}, |
| + {"base64 that is not a point", "aGVsbG8=", http.StatusBadRequest, notAKey}, |
| + {"the deployment's own key", deployment, http.StatusBadRequest, |
| + "that is the platform's own secrets key, and a fleet needs its own. mint a new pair with carlos secrets genkey and register its public half"}, |
| + } { |
| + status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": c.pubkey}, token) |
| + if status != c.status || body["error"] != c.err { |
| + t.Errorf("%s = %d %v, want %d %q", c.what, status, body, c.status, c.err) |
| + } |
| + } |
| + |
| + // A key another account's fleet already holds. |
| + if status, body := putJSON(t, fskURL(fx, "cdef", "away"), map[string]string{"pubkey": pub}, bob); status != http.StatusOK { |
| + t.Fatalf("bob registers away = %d %v", status, body) |
| + } |
| + status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pub}, token) |
| + if status != http.StatusConflict || body["error"] != "another fleet already uses this secrets key, and every fleet needs its own. mint a new pair with carlos secrets genkey and register its public half" { |
| + t.Fatalf("a key on another account's fleet = %d %v, want 409 with the in-use sentence", status, body) |
| + } |
| + if row := fskFleetRow(t, fx, "home"); row.SecretsKeyFP != "" { |
| + t.Fatalf("home took a key another fleet holds: %+v", row) |
| + } |
| + if row := fskFleetRow(t, fx, "away"); row.SecretsPub != pub { |
| + t.Fatalf("away lost its key: %+v", row) |
| + } |
| +} |
| + |
| +func TestFleetSecretsKeyIdempotent(t *testing.T) { |
| + fx, token, spy := fskFixture(t, "code-fsk-idempotent") |
| + fskPlaceShop(t, fx, token, "home") |
| + fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": fskSeal(t, fx, "")}) |
| + pub, fp := fskKey(t) |
| + status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pub}, token) |
| + if status != http.StatusOK || body["changed"] != true { |
| + t.Fatalf("first registration = %d %v, want 200 changed", status, body) |
| + } |
| + // Stamp the row with an earlier writer, so a second write would show. |
| + reg, err := registry.Open(fx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.SetFleetSecretsKey("home", pub, fp, "earlier@keymail.dev", 1000); err != nil { |
| + t.Fatal(err) |
| + } |
| + spy.reset() |
| + status, body = putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pub}, token) |
| + if status != http.StatusOK || body["changed"] != false || body["fingerprint"] != fp || body["fleet"] != "home" { |
| + t.Fatalf("the same key again = %d %v, want 200 unchanged", status, body) |
| + } |
| + if row := fskFleetRow(t, fx, "home"); row.SecretsKeySetBy != "earlier@keymail.dev" || row.SecretsKeySetAt != 1000 { |
| + t.Fatalf("the no-op rewrote the row: %+v", row) |
| + } |
| + if _, puts := spy.counts(); puts != 0 { |
| + t.Fatalf("the no-op made %d owner record puts, want none", puts) |
| + } |
| + // The no-op still says what is left to fix. |
| + stale := fskStale(t, body) |
| + if len(stale) != 1 || stale[0].App != "shop" || strings.Join(stale[0].Vars, ",") != "API_KEY" { |
| + t.Fatalf("no-op stale = %+v, want shop's API_KEY", stale) |
| + } |
| +} |
| + |
| +func TestFleetSecretsKeyWritesTheOwnerRecordFirst(t *testing.T) { |
| + ctx := context.Background() |
| + fx, token, spy := fskFixture(t, "code-fsk-record-first") |
| + pub, fp := fskKey(t) |
| + key := release.FleetOwnerKey(fx.sqid, "home") |
| + before, _, err := fx.rel.Get(ctx, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // A failed record write fails the registration, and the registry row |
| + // stays keyless. |
| + spy.mu.Lock() |
| + spy.failPuts = 1 |
| + spy.mu.Unlock() |
| + status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pub}, token) |
| + wantErr := "the key was not recorded for home and nothing was changed. run carlos fleets secrets-key home " + pub + " again" |
| + if status != http.StatusBadGateway || body["error"] != wantErr { |
| + t.Fatalf("failed record write = %d %v, want 502 %q", status, body, wantErr) |
| + } |
| + if row := fskFleetRow(t, fx, "home"); row.SecretsKeyFP != "" || row.SecretsPub != "" { |
| + t.Fatalf("the registry took the key without the record: %+v", row) |
| + } |
| + |
| + // The retry appends to the existing record, in a shape the claim |
| + // boundary's classifier admits. |
| + if status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pub}, token); status != http.StatusOK { |
| + t.Fatalf("retry = %d %v", status, body) |
| + } |
| + after, _, err := fx.rel.Get(ctx, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if fps := fskOwnerFPs(t, fx); len(fps) != 1 || fps[0] != fp { |
| + t.Fatalf("owner record fps = %v, want [%s]", fps, fp) |
| + } |
| + if c, err := hostops.ClassifyMutation(ctx, nil, nil, hostops.MutationTarget{Surface: "bucket", Method: "Put", Key: key, ETag: "e", Before: before, After: after}); err != nil || c.Family != "fleet-owner" { |
| + t.Fatalf("classifier on the append = %+v, %v", c, err) |
| + } |
| + if ok, err := boxOwns(fx.rel, "home", fx.sqid); !ok || err != nil { |
| + t.Fatalf("the box no longer reads the record: %v, %v", ok, err) |
| + } |
| + |
| + // A fleet whose record is missing gets one, created listing the key. |
| + reg, err := registry.Open(fx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if created, err := reg.CreateFleet(registry.Fleet{Name: "bare", Account: fx.sqid, Bucket: "bare-data", CreatedAt: 1761000000}); err != nil || !created { |
| + t.Fatalf("seed bare: %v, %v", created, err) |
| + } |
| + pub2, fp2 := fskKey(t) |
| + if status, body := putJSON(t, fskURL(fx, fx.sqid, "bare"), map[string]string{"pubkey": pub2}, token); status != http.StatusOK { |
| + t.Fatalf("register on a fleet with no record = %d %v", status, body) |
| + } |
| + rec, err := readFleetOwner(t, fx.rel, fx.sqid, "bare") |
| + if err != nil { |
| + t.Fatalf("no record was created: %v", err) |
| + } |
| + if rec.Fleet != "bare" || rec.Account != fx.sqid || rec.CreatedAt != 1761000000 || len(rec.SecretsKeyFPs) != 1 || rec.SecretsKeyFPs[0] != fp2 { |
| + t.Fatalf("created record = %+v, want bare, %s, the row's creation time and [%s]", rec, fx.sqid, fp2) |
| + } |
| + stored, _, _ := fx.rel.Get(ctx, release.FleetOwnerKey(fx.sqid, "bare")) |
| + if c, err := hostops.ClassifyMutation(ctx, nil, nil, hostops.MutationTarget{Surface: "bucket", Method: "Put", Key: release.FleetOwnerKey(fx.sqid, "bare"), After: stored}); err != nil || c.Family != "fleet-owner" { |
| + t.Fatalf("classifier on the create = %+v, %v", c, err) |
| + } |
| +} |
| + |
| +func TestFleetSecretsKeyListsStaleValues(t *testing.T) { |
| + ctx := context.Background() |
| + fx, token, _ := fskFixture(t, "code-fsk-stale") |
| + fskPlaceShop(t, fx, token, "home") |
| + pub, fp := fskKey(t) |
| + fskSetSecrets(t, fx, map[string]appconfig.Var{ |
| + "API_KEY": fskSeal(t, fx, ""), |
| + "CARLOS_STORE_SECRET_KEY": fskSeal(t, fx, ""), |
| + "CARLOS_RELAY": fskSeal(t, fx, "sha256:"+strings.Repeat("e", 64)), |
| + "ALREADY_RIGHT": fskSeal(t, fx, fp), |
| + }) |
| + if err := appconfig.SetEnv(ctx, fx.rel, fx.sqid, "shop", map[string]string{"PLAIN": "x"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := appconfig.ApplyEnvironment(ctx, fx.rel, fx.sqid, "shop", "staging", map[string]appconfig.Var{ |
| + "DB_PASSWORD": fskSeal(t, fx, "sha256:"+strings.Repeat("d", 64)), |
| + "CARLOS_SMTP_PASS": fskSeal(t, fx, ""), |
| + }, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, _, err := appconfig.ApplyInstance(ctx, fx.rel, fx.sqid, "shop", "a.shop.example.com", map[string]appconfig.Var{ |
| + "TENANT_TOKEN": fskSeal(t, fx, ""), |
| + }, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + // An app of the account that is not on home is not listed. |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "blog", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := appconfig.SetSecret(ctx, fx.rel, fx.sqid, "blog", map[string]appconfig.Var{"API_KEY": {Kind: "secret", Envelope: fskSeal(t, fx, "").Envelope}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pub}, token) |
| + if status != http.StatusOK || body["changed"] != true { |
| + t.Fatalf("register = %d %v", status, body) |
| + } |
| + stale := fskStale(t, body) |
| + if len(stale) != 1 || stale[0].App != "shop" { |
| + t.Fatalf("stale = %+v, want shop alone", stale) |
| + } |
| + if got := strings.Join(stale[0].Vars, ","); got != "API_KEY,DB_PASSWORD,TENANT_TOKEN" { |
| + t.Errorf("user-set stale vars = %s, want API_KEY,DB_PASSWORD,TENANT_TOKEN", got) |
| + } |
| + if got := strings.Join(stale[0].Minted, ","); got != "CARLOS_RELAY,CARLOS_SMTP_PASS,CARLOS_STORE_SECRET_KEY" { |
| + t.Errorf("minted stale vars = %s, want CARLOS_RELAY,CARLOS_SMTP_PASS,CARLOS_STORE_SECRET_KEY", got) |
| + } |
| +} |
| + |
| +func TestFleetSecretsKeyReplacementRefusedWhileSealed(t *testing.T) { |
| + _, fpThird := fskKey(t) |
| + for _, c := range []struct{ name, sealedTo string }{ |
| + {"sealed to the old key", "old"}, |
| + {"sealed before sealed_to existed", ""}, |
| + {"sealed to a third key", fpThird}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + fx, token, _ := fskFixture(t, "code-fsk-replace") |
| + pubA, fpA := fskKey(t) |
| + if status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pubA}, token); status != http.StatusOK { |
| + t.Fatalf("first key = %d %v", status, body) |
| + } |
| + fskPlaceShop(t, fx, token, "home") |
| + sealedTo := c.sealedTo |
| + if sealedTo == "old" { |
| + sealedTo = fpA |
| + } |
| + fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": fskSeal(t, fx, sealedTo)}) |
| + pubB, _ := fskKey(t) |
| + status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pubB}, token) |
| + 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 status != http.StatusConflict || body["error"] != want { |
| + t.Fatalf("replacement = %d %v, want 409 %q", status, body, want) |
| + } |
| + if row := fskFleetRow(t, fx, "home"); row.SecretsKeyFP != fpA || row.SecretsPub != pubA { |
| + t.Fatalf("the refused replacement changed the row: %+v", row) |
| + } |
| + if fps := fskOwnerFPs(t, fx); len(fps) != 1 || fps[0] != fpA { |
| + t.Fatalf("the refused replacement wrote the record: %v", fps) |
| + } |
| + }) |
| + } |
| + // With no sealed value on the fleet the replacement goes through, and |
| + // the record keeps the old key listed. |
| + fx, token, _ := fskFixture(t, "code-fsk-replace-ok") |
| + pubA, fpA := fskKey(t) |
| + pubB, fpB := fskKey(t) |
| + for _, pub := range []string{pubA, pubB} { |
| + if status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pub}, token); status != http.StatusOK || body["changed"] != true { |
| + t.Fatalf("register = %d %v", status, body) |
| + } |
| + } |
| + if row := fskFleetRow(t, fx, "home"); row.SecretsKeyFP != fpB { |
| + t.Fatalf("row = %+v, want the second key", row) |
| + } |
| + if fps := fskOwnerFPs(t, fx); strings.Join(fps, ",") != fpA+","+fpB { |
| + t.Fatalf("record fps = %v, want both, oldest first", fps) |
| + } |
| +} |
| + |
| +func TestFleetSecretsKeyFailedReplacementKeepsTheOldFingerprintListed(t *testing.T) { |
| + fx, token, _ := fskFixture(t, "code-fsk-failed-replace") |
| + bob := fskAway(t, fx) |
| + pubA, fpA := fskKey(t) |
| + pubB, fpB := fskKey(t) |
| + if status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pubA}, token); status != http.StatusOK { |
| + t.Fatalf("home = %d %v", status, body) |
| + } |
| + if status, body := putJSON(t, fskURL(fx, "cdef", "away"), map[string]string{"pubkey": pubB}, bob); status != http.StatusOK { |
| + t.Fatalf("away = %d %v", status, body) |
| + } |
| + // The registry refuses the replacement after the record write (the key |
| + // is away's): the registry keeps home's old key, and the record still |
| + // lists it beside the new one. |
| + if status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pubB}, token); status != http.StatusConflict { |
| + t.Fatalf("replacement with away's key = %d %v, want 409", status, body) |
| + } |
| + if row := fskFleetRow(t, fx, "home"); row.SecretsKeyFP != fpA || row.SecretsPub != pubA { |
| + t.Fatalf("registry row = %+v, want the old key", row) |
| + } |
| + if fps := fskOwnerFPs(t, fx); strings.Join(fps, ",") != fpA+","+fpB { |
| + t.Fatalf("record fps = %v, want the old key still listed, then the new", fps) |
| + } |
| +} |
| + |
| +func TestFleetListShowsKeyFingerprint(t *testing.T) { |
| + fx, token, _ := fskFixture(t, "code-fsk-list") |
| + fskPlaceShop(t, fx, token, "home") |
| + fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": fskSeal(t, fx, ""), "DB_PASSWORD": fskSeal(t, fx, "")}) |
| + listed := func() map[string]any { |
| + t.Helper() |
| + status, body := getJSON(t, fleetsURL(fx, fx.sqid), token) |
| + list, _ := body["fleets"].([]any) |
| + if status != http.StatusOK || len(list) != 1 { |
| + t.Fatalf("list = %d %v", status, body) |
| + } |
| + return list[0].(map[string]any) |
| + } |
| + page := func() string { |
| + t.Helper() |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-fsk-list-browser-"+time.Now().Format("150405.000000000")) |
| + status, _, body := get(t, c, fx.u("/fleets/home")) |
| + if status != http.StatusOK { |
| + t.Fatalf("fleet page = %d:\n%s", status, body) |
| + } |
| + return body |
| + } |
| + if f := listed(); f["secrets_key_fp"] != nil || f["stale_secrets"] != nil { |
| + t.Fatalf("keyless fleet listed as %v, want no key fields", f) |
| + } |
| + body := page() |
| + for _, want := range []string{"<h2>Secrets key</h2>", "No secrets key yet. Apps on this fleet cannot hold secrets until you run carlos fleets secrets-key home <pubkey> from a terminal signed in to this console."} { |
| + if !strings.Contains(body, want) { |
| + t.Fatalf("keyless fleet page missing %q:\n%s", want, body) |
| + } |
| + } |
| + |
| + pub, fp := fskKey(t) |
| + if status, body := putJSON(t, fskURL(fx, fx.sqid, "home"), map[string]string{"pubkey": pub}, token); status != http.StatusOK { |
| + t.Fatalf("register = %d %v", status, body) |
| + } |
| + if f := listed(); f["secrets_key_fp"] != fp || f["stale_secrets"] != float64(2) { |
| + t.Fatalf("keyed fleet listed as %v, want %s and 2 stale", f, fp) |
| + } |
| + if body := page(); !strings.Contains(body, "Secrets for apps on this fleet are sealed to <code>"+fp+"</code>. Every box needs the matching private key as CARLOS_SECRETS_KEY in its host.env.") { |
| + t.Fatalf("keyed fleet page missing the fingerprint line:\n%s", body) |
| + } |
| + |
| + // Setting the two secrets again, sealed to the fleet's key, clears the |
| + // count. |
| + fskSetSecrets(t, fx, map[string]appconfig.Var{"API_KEY": fskSeal(t, fx, fp), "DB_PASSWORD": fskSeal(t, fx, fp)}) |
| + if f := listed(); f["secrets_key_fp"] != fp || f["stale_secrets"] != nil { |
| + t.Fatalf("after re-sealing, listed as %v, want no stale count", f) |
| + } |
| +} |
| + |
| +// TestFleetBYOPageNamesTheSecretsKey: the host.env block carries the |
| +// CARLOS_SECRETS_KEY line, and the sentence after it says where it comes |
| +// from. |
| +func TestFleetBYOPageNamesTheSecretsKey(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-fsk-byo") |
| + status, _, body := get(t, c, fx.u("/fleet/byo")) |
| + if status != http.StatusOK { |
| + t.Fatalf("byo page = %d:\n%s", status, body) |
| + } |
| + for _, want := range []string{ |
| + "CARLOS_SECRETS_KEY=<private key from carlos secrets genkey, on your boxes only>", |
| + "CARLOS_SECRETS_KEY is the private half of your fleet's secrets key. Make the pair with carlos secrets genkey, put the private half on every box and nowhere else, then run systemctl restart carlos-edge. Register the public half with carlos fleets secrets-key <name> <pubkey>. Until you do, apps on this fleet cannot hold secrets.", |
| + } { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("byo page missing %q", want) |
| + } |
| + } |
| +} |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index 320dde688..707108d16 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -164,6 +164,9 @@ var closedDoors = []string{ |
| "POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/rotate", |
| "POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/detach", |
| "POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/tags", |
| + // Setting a fleet's secrets key decides who can read the fleet's future |
| + // secrets. Same cut, and owner-gated inside. |
| + "PUT /api/cli/fleets/{account}/{fleet}/secrets-key", |
| // Minting, rotating and revoking a SERVICE credential is the same cut |
| // seen from the other side: these are the doors that hand out authority, |
| // so a credential must never reach them — not even the admin one, and |
diff --git a/internal/console/templates/fleet_byo.html b/internal/console/templates/fleet_byo.html| index daf5eb678..52a05cb23 100644 |
| --- a/internal/console/templates/fleet_byo.html |
| +++ b/internal/console/templates/fleet_byo.html |
| @@ -34,7 +34,9 @@ CARLOS_REGION=fleet/<name> |
| CARLOS_RELEASE_PUBKEY=<this deployment's release public key> |
| CARLOS_TUNNEL_URL=<this deployment's tunnel address> |
| CARLOS_TUNNEL_TOKEN=<from carlos fleets add-box <name> <label> — shown once> |
| -CARLOS_TUNNEL_NAME=<name>/<label></code></pre> |
| +CARLOS_TUNNEL_NAME=<name>/<label> |
| +CARLOS_SECRETS_KEY=<private key from carlos secrets genkey, on your boxes only></code></pre> |
| +<p class="small">CARLOS_SECRETS_KEY is the private half of your fleet's secrets key. Make the pair with carlos secrets genkey, put the private half on every box and nowhere else, then run systemctl restart carlos-edge. Register the public half with carlos fleets secrets-key <name> <pubkey>. Until you do, apps on this fleet cannot hold secrets.</p> |
| <p class="small">Release pointers are Ed25519-signed; without <code>CARLOS_RELEASE_PUBKEY</code> the |
| box has no key to verify against and refuses to adopt anything.</p> |
| <p class="small"><code>CARLOS_FLEET_BOX</code> is optional and defaults from |
diff --git a/internal/console/templates/fleetdetail.html b/internal/console/templates/fleetdetail.html| index a9f0f774b..49af19561 100644 |
| --- a/internal/console/templates/fleetdetail.html |
| +++ b/internal/console/templates/fleetdetail.html |
| @@ -71,6 +71,13 @@ |
| not evict a channel it already holds; a compromised box needs Detach instead.</p> |
| {{else}}<p class="small">No boxes registered to this fleet yet — add one with <code>carlos fleets add-box</code>.</p>{{end}} |
| +<h2>Secrets key</h2> |
| +{{if .FleetDetail.SecretsKeyFP}} |
| +<p class="small">Secrets for apps on this fleet are sealed to <code>{{.FleetDetail.SecretsKeyFP}}</code>. Every box needs the matching private key as CARLOS_SECRETS_KEY in its host.env.</p> |
| +{{else}} |
| +<p class="small">No secrets key yet. Apps on this fleet cannot hold secrets until you run carlos fleets secrets-key {{.FleetDetail.Name}} <pubkey> from a terminal signed in to this console.</p> |
| +{{end}} |
| + |
| <h2>Placed apps</h2> |
| {{if .FleetApps}} |
| <div class="tablewrap"> |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 67a46d5c7..42ed28025 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -323,6 +323,7 @@ route PUT /api/cli/apps/{account}/{app}/swap |
| route PUT /api/cli/apps/{account}/{app}/telemetry |
| route PUT /api/cli/apps/{account}/{app}/updates |
| route PUT /api/cli/apps/{account}/{app}/version-target |
| +route PUT /api/cli/fleets/{account}/{fleet}/secrets-key |
| route PUT /api/cli/system/geoip |
| route PUT /api/cli/system/upload |
| worker LogPlacementDiscrepancies |
diff --git a/internal/hostops/fleetowner_classifier.go b/internal/hostops/fleetowner_classifier.go| index 6c45b95e1..ced088c26 100644 |
| --- a/internal/hostops/fleetowner_classifier.go |
| +++ b/internal/hostops/fleetowner_classifier.go |
| @@ -2,6 +2,8 @@ package hostops |
| import ( |
| "fmt" |
| + "regexp" |
| + "slices" |
| "strings" |
| "github.com/carlosframework/platform/internal/controlname" |
| @@ -17,14 +19,23 @@ func isFleetOwnerShape(p []string) bool { |
| // classifyFleetOwner admits the fleet owner record (rootfs apps Plan 4 D7, |
| // release.FleetOwnerKey): the console's record of which account owns a |
| -// fleet, which a fleet box reads before it starts any rootfs app. The |
| -// console only ever creates it, so the one admitted shape is a create-only |
| -// Put (no ETag, no existing object) of exactly |
| -// accounts/<acct>/fleets/<fleet>.json, whose body decodes strictly as a |
| -// release.FleetOwner naming that same account and fleet. A record naming |
| -// another account, a replacement, and every delete are refused: no fleet |
| -// removal door exists yet, and the change that adds one reviews its own |
| -// Delete arm. |
| +// fleet, which a fleet box reads before it starts any rootfs app. Two shapes |
| +// are admitted, both Puts of exactly accounts/<acct>/fleets/<fleet>.json |
| +// whose body decodes strictly as a release.FleetOwner naming that same |
| +// account and fleet: |
| +// |
| +// - a create (no ETag, no existing object); |
| +// - the fleet secrets key append (spec §5.1, plan ruling R-4): an If-Match |
| +// Put over an existing record that also decodes strictly and names the |
| +// same account and fleet, where the new body keeps created_at and keeps |
| +// the old secrets_key_fps as its prefix, adding at least one |
| +// fingerprint at the end. |
| +// |
| +// Every fingerprint listed is "sha256:" and 64 lowercase hex characters, |
| +// listed once. A record naming another account, any other replacement (a |
| +// fingerprint removed, replaced or reordered, created_at moved), and every |
| +// delete are refused: no fleet removal door exists yet, and the change that |
| +// adds one reviews its own Delete arm. |
| func classifyFleetOwner(t MutationTarget) (Classification, error) { |
| p := strings.Split(t.Key, "/") |
| if !isFleetOwnerShape(p) { |
| @@ -35,15 +46,59 @@ func classifyFleetOwner(t MutationTarget) (Classification, error) { |
| if !ok || !controlname.ValidAccount(acct) || !registry.ValidTunnelName(fleet) || t.Key != release.FleetOwnerKey(acct, fleet) { |
| return Classification{}, fmt.Errorf("%w: %s", ErrUnclassified, t.Key) |
| } |
| - if t.Method != "Put" || t.ETag != "" || len(t.Before) != 0 { |
| - return Classification{}, fmt.Errorf("%w: %s is create-only", ErrUnclassified, t.Key) |
| + if t.Method != "Put" { |
| + return Classification{}, fmt.Errorf("%w: %s refuses deletes", ErrUnclassified, t.Key) |
| } |
| + create := t.ETag == "" && len(t.Before) == 0 |
| + update := t.ETag != "" && len(t.Before) != 0 |
| + if !create && !update { |
| + return Classification{}, fmt.Errorf("%w: %s is a create or a key append", ErrUnclassified, t.Key) |
| + } |
| + rec, err := fleetOwnerBody(t.Key, t.After, acct, fleet) |
| + if err != nil { |
| + return Classification{}, err |
| + } |
| + if update { |
| + old, err := fleetOwnerBody(t.Key, t.Before, acct, fleet) |
| + if err != nil { |
| + return Classification{}, err |
| + } |
| + if !fleetOwnerKeyAppend(old, rec) { |
| + return Classification{}, fmt.Errorf("%w: %s: an update may only append secrets key fingerprints", ErrUnclassified, t.Key) |
| + } |
| + } |
| + return Classification{Family: "fleet-owner", NonApp: "the console's record of which account owns a fleet; holds no app record"}, nil |
| +} |
| + |
| +// fleetOwnerFPRe is a secrets key fingerprint as appconfig.KeyFingerprint |
| +// renders it. |
| +var fleetOwnerFPRe = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`) |
| + |
| +// fleetOwnerBody decodes one owner record strictly and checks it names acct |
| +// and fleet and lists well-formed fingerprints, each once. |
| +func fleetOwnerBody(key string, b []byte, acct, fleet string) (release.FleetOwner, error) { |
| var rec release.FleetOwner |
| - if err := strictJSON(t.After, &rec); err != nil { |
| - return Classification{}, fmt.Errorf("%w: %s: %v", ErrUnclassified, t.Key, err) |
| + if err := strictJSON(b, &rec); err != nil { |
| + return rec, fmt.Errorf("%w: %s: %v", ErrUnclassified, key, err) |
| } |
| if rec.Account != acct || rec.Fleet != fleet { |
| - return Classification{}, fmt.Errorf("%w: %s: the record names another account or fleet", ErrUnclassified, t.Key) |
| + return rec, fmt.Errorf("%w: %s: the record names another account or fleet", ErrUnclassified, key) |
| } |
| - return Classification{Family: "fleet-owner", NonApp: "the console's record of which account owns a fleet; holds no app record"}, nil |
| + seen := make(map[string]bool, len(rec.SecretsKeyFPs)) |
| + for _, fp := range rec.SecretsKeyFPs { |
| + if !fleetOwnerFPRe.MatchString(fp) || seen[fp] { |
| + return rec, fmt.Errorf("%w: %s: a secrets key fingerprint is malformed or listed twice", ErrUnclassified, key) |
| + } |
| + seen[fp] = true |
| + } |
| + return rec, nil |
| +} |
| + |
| +// fleetOwnerKeyAppend reports whether next is old with one or more |
| +// fingerprints appended and nothing else changed. |
| +func fleetOwnerKeyAppend(old, next release.FleetOwner) bool { |
| + if next.CreatedAt != old.CreatedAt || len(next.SecretsKeyFPs) <= len(old.SecretsKeyFPs) { |
| + return false |
| + } |
| + return slices.Equal(next.SecretsKeyFPs[:len(old.SecretsKeyFPs)], old.SecretsKeyFPs) |
| } |
diff --git a/internal/hostops/fleetowner_classifier_test.go b/internal/hostops/fleetowner_classifier_test.go| index 2bfa9a1e5..e51e08ec8 100644 |
| --- a/internal/hostops/fleetowner_classifier_test.go |
| +++ b/internal/hostops/fleetowner_classifier_test.go |
| @@ -3,6 +3,7 @@ package hostops |
| import ( |
| "context" |
| "errors" |
| + "strconv" |
| "strings" |
| "testing" |
| @@ -10,11 +11,12 @@ import ( |
| ) |
| // TestFleetOwnerClassifier: the fleet owner record (rootfs apps Plan 4 D7) |
| -// is a reviewed non-app family. The console only ever creates it, so the |
| -// family admits exactly one shape: a create-only Put of |
| -// accounts/<acct>/fleets/<fleet>.json whose body names that account and |
| -// that fleet. A record a fleet box trusts as its ownership proof must never |
| -// be replaced, deleted, or written for another account through this door. |
| +// is a reviewed non-app family. The console creates it, so the family admits |
| +// a create-only Put of accounts/<acct>/fleets/<fleet>.json whose body names |
| +// that account and that fleet. A record a fleet box trusts as its ownership |
| +// proof must never be replaced, deleted, or written for another account |
| +// through this door; the one update admitted, the secrets key append, is |
| +// TestFleetOwnerClassifierAdmitsTheKeyUpdate's. |
| func TestFleetOwnerClassifier(t *testing.T) { |
| ctx := context.Background() |
| key := release.FleetOwnerKey("bab", "home") |
| @@ -82,3 +84,96 @@ func TestFleetOwnerClassifier(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// The fleet secrets key (spec §5.1, plan ruling R-4): the console appends a |
| +// registered key's fingerprint to the owner record, under If-Match on the |
| +// record it read. Fingerprints used below are the real shape, "sha256:" and |
| +// 64 lowercase hex characters. |
| +var ( |
| + ownerFPA = "sha256:" + strings.Repeat("a", 64) |
| + ownerFPB = "sha256:" + strings.Repeat("b", 64) |
| + ownerFPC = "sha256:" + strings.Repeat("c", 64) |
| +) |
| + |
| +func ownerRecord(fleet, acct string, createdAt int64, fps ...string) []byte { |
| + b := `{"fleet":"` + fleet + `","account":"` + acct + `"` |
| + if createdAt != 0 { |
| + b += `,"created_at":` + strconv.FormatInt(createdAt, 10) |
| + } |
| + if len(fps) > 0 { |
| + b += `,"secrets_key_fps":["` + strings.Join(fps, `","`) + `"]` |
| + } |
| + return []byte(b + "}") |
| +} |
| + |
| +// TestFleetOwnerClassifierAdmitsTheKeyUpdate: the two shapes the key door |
| +// writes. A missing record is created already listing the key, and an |
| +// existing one gains the key at the end of its list, everything else equal. |
| +func TestFleetOwnerClassifierAdmitsTheKeyUpdate(t *testing.T) { |
| + ctx := context.Background() |
| + key := release.FleetOwnerKey("bab", "home") |
| + for _, c := range []struct { |
| + name string |
| + target MutationTarget |
| + }{ |
| + {"a create listing the key", MutationTarget{Surface: "bucket", Method: "Put", Key: key, After: ownerRecord("home", "bab", 1761500000, ownerFPA)}}, |
| + {"the first key on a record from before keys", MutationTarget{Surface: "bucket", Method: "Put", Key: key, ETag: "e1", Before: ownerRecord("home", "bab", 1761500000), After: ownerRecord("home", "bab", 1761500000, ownerFPA)}}, |
| + {"a second key appended", MutationTarget{Surface: "bucket", Method: "Put", Key: key, ETag: "e2", Before: ownerRecord("home", "bab", 1761500000, ownerFPA), After: ownerRecord("home", "bab", 1761500000, ownerFPA, ownerFPB)}}, |
| + {"a record with no created_at", MutationTarget{Surface: "bucket", Method: "Put", Key: key, ETag: "e3", Before: ownerRecord("home", "bab", 0, ownerFPA), After: ownerRecord("home", "bab", 0, ownerFPA, ownerFPB)}}, |
| + } { |
| + got, err := ClassifyMutation(ctx, nil, nil, c.target) |
| + if err != nil { |
| + t.Errorf("%s: %v", c.name, err) |
| + continue |
| + } |
| + if got.Family != "fleet-owner" || got.NonApp == "" || len(got.Scopes) != 0 || got.MailGate { |
| + t.Errorf("%s: classified %+v, want non-app family fleet-owner with no scopes", c.name, got) |
| + } |
| + } |
| +} |
| + |
| +// TestFleetOwnerClassifierRefusesOtherChanges: an update that does anything |
| +// but append fingerprints is refused, so the record a fleet box trusts for |
| +// its ownership still never changes owner, and a registered key is never |
| +// dropped from the list direct mode checks. |
| +func TestFleetOwnerClassifierRefusesOtherChanges(t *testing.T) { |
| + ctx := context.Background() |
| + key := release.FleetOwnerKey("bab", "home") |
| + old := ownerRecord("home", "bab", 1761500000, ownerFPA, ownerFPB) |
| + put := func(before, after []byte) MutationTarget { |
| + return MutationTarget{Surface: "bucket", Method: "Put", Key: key, ETag: "e", Before: before, After: after} |
| + } |
| + for _, c := range []struct { |
| + name string |
| + target MutationTarget |
| + }{ |
| + {"the same list again", put(old, old)}, |
| + {"a key removed", put(old, ownerRecord("home", "bab", 1761500000, ownerFPA))}, |
| + {"every key removed", put(old, ownerRecord("home", "bab", 1761500000))}, |
| + {"a key replaced", put(old, ownerRecord("home", "bab", 1761500000, ownerFPA, ownerFPC))}, |
| + {"the list reordered", put(old, ownerRecord("home", "bab", 1761500000, ownerFPB, ownerFPA))}, |
| + {"a key inserted before the others", put(old, ownerRecord("home", "bab", 1761500000, ownerFPC, ownerFPA, ownerFPB))}, |
| + {"a key listed twice", put(old, ownerRecord("home", "bab", 1761500000, ownerFPA, ownerFPB, ownerFPA))}, |
| + {"a fingerprint of the wrong shape", put(old, ownerRecord("home", "bab", 1761500000, ownerFPA, ownerFPB, "sha256:abc"))}, |
| + {"an upper-case fingerprint", put(old, ownerRecord("home", "bab", 1761500000, ownerFPA, ownerFPB, "sha256:"+strings.Repeat("C", 64)))}, |
| + {"an empty fingerprint", put(old, ownerRecord("home", "bab", 1761500000, ownerFPA, ownerFPB, ""))}, |
| + {"the account changed", put(old, ownerRecord("home", "cdef", 1761500000, ownerFPA, ownerFPB, ownerFPC))}, |
| + {"the fleet changed", put(old, ownerRecord("away", "bab", 1761500000, ownerFPA, ownerFPB, ownerFPC))}, |
| + {"created_at changed", put(old, ownerRecord("home", "bab", 1761500001, ownerFPA, ownerFPB, ownerFPC))}, |
| + {"created_at dropped", put(old, ownerRecord("home", "bab", 0, ownerFPA, ownerFPB, ownerFPC))}, |
| + {"an old record naming another account", put(ownerRecord("home", "cdef", 1761500000, ownerFPA), ownerRecord("home", "bab", 1761500000, ownerFPA, ownerFPB))}, |
| + {"an old record that is not a record", put([]byte(`nope`), ownerRecord("home", "bab", 1761500000, ownerFPA))}, |
| + {"an old record with an unknown field", put([]byte(`{"fleet":"home","account":"bab","apps":["shop"]}`), ownerRecord("home", "bab", 0, ownerFPA))}, |
| + {"a new record with an unknown field", put(old, []byte(`{"fleet":"home","account":"bab","created_at":1761500000,"secrets_key_fps":["`+ownerFPA+`","`+ownerFPB+`","`+ownerFPC+`"],"apps":["shop"]}`))}, |
| + {"an update with no ETag", MutationTarget{Surface: "bucket", Method: "Put", Key: key, Before: old, After: ownerRecord("home", "bab", 1761500000, ownerFPA, ownerFPB, ownerFPC)}}, |
| + {"an ETag with no old record", MutationTarget{Surface: "bucket", Method: "Put", Key: key, ETag: "e", After: ownerRecord("home", "bab", 1761500000, ownerFPA)}}, |
| + {"a create listing a bad fingerprint", MutationTarget{Surface: "bucket", Method: "Put", Key: key, After: ownerRecord("home", "bab", 1761500000, "fp-a")}}, |
| + {"a create listing a key twice", MutationTarget{Surface: "bucket", Method: "Put", Key: key, After: ownerRecord("home", "bab", 1761500000, ownerFPA, ownerFPA)}}, |
| + {"a delete of a record with keys", MutationTarget{Surface: "bucket", Method: "Delete", Key: key, ETag: "e", Before: old}}, |
| + {"a delete if match of a record with keys", MutationTarget{Surface: "bucket", Method: "DeleteIfMatch", Key: key, ETag: "e", Before: old}}, |
| + } { |
| + if got, err := ClassifyMutation(ctx, nil, nil, c.target); !errors.Is(err, ErrUnclassified) { |
| + t.Errorf("%s: classified %+v, err %v; want ErrUnclassified", c.name, got, err) |
| + } |
| + } |
| +} |
diff --git a/internal/hostops/mutation_classifier.go b/internal/hostops/mutation_classifier.go| index dc69e7b61..22846a64d 100644 |
| --- a/internal/hostops/mutation_classifier.go |
| +++ b/internal/hostops/mutation_classifier.go |
| @@ -151,7 +151,8 @@ func ClassifyMutation(ctx context.Context, raw release.Store, w *ControlWriter, |
| } |
| return Classification{Family: "account-limits", NonApp: "account limits record published from the plan catalog; no app state"}, nil |
| case isFleetOwnerShape(p): |
| - // rootfs apps Plan 4 D7: create-only, body names the key's account and fleet. |
| + // rootfs apps Plan 4 D7: a create, or the fleet secrets key append; the |
| + // body names the key's account and fleet. |
| return classifyFleetOwner(t) |
| case t.Key == RelayAuthorityKey: |
| return classifyRelayAuthority(t) |
diff --git a/internal/registry/fleets.go b/internal/registry/fleets.go| index 6908e49cd..870678f50 100644 |
| --- a/internal/registry/fleets.go |
| +++ b/internal/registry/fleets.go |
| @@ -286,8 +286,13 @@ func (r *Registry) ListFleets() ([]Fleet, error) { |
| // SetFleetSecretsKey records fleet name's secrets key: the public half, its |
| // fingerprint, who set it and when. Re-setting the same fingerprint on the same |
| // fleet succeeds. A fingerprint another fleet already holds returns |
| -// ErrFleetKeyInUse and changes nothing. A missing fleet is an error. |
| +// ErrFleetKeyInUse and changes nothing. A missing fleet is an error. The |
| +// key and its fingerprint travel together: one without the other is refused |
| +// before anything is written (both empty clears the key). |
| func (r *Registry) SetFleetSecretsKey(name, pub, fp, by string, at int64) error { |
| + if (pub == "") != (fp == "") { |
| + return fmt.Errorf("fleet %q: a secrets key and its fingerprint are set together", name) |
| + } |
| if r.remote != nil { |
| _, err := r.remote.call(nil, remoteRequest{Method: "SetFleetSecretsKey", Name: name, Pub: pub, KeyFP: fp, By: by, At: at}, nil) |
| return err |
diff --git a/internal/registry/fleets_secrets_key_test.go b/internal/registry/fleets_secrets_key_test.go| index 51cf41e6f..f20541ef0 100644 |
| --- a/internal/registry/fleets_secrets_key_test.go |
| +++ b/internal/registry/fleets_secrets_key_test.go |
| @@ -97,3 +97,34 @@ func TestFleetSecretsKeyOverRemote(t *testing.T) { |
| t.Fatalf("duplicate fingerprint over remote = %v, want ErrFleetKeyInUse", err) |
| } |
| } |
| + |
| +// TestFleetSecretsKeyPubAndFPTravelTogether: a public key with no fingerprint, |
| +// or a fingerprint with no key, is refused and changes nothing, locally and |
| +// over the remote transport. Both empty is the one way to clear. |
| +func TestFleetSecretsKeyPubAndFPTravelTogether(t *testing.T) { |
| + local := openTestRegistry(t) |
| + remote, _ := remoteTestRegistry(t) |
| + for name, reg := range map[string]*Registry{"local": local, "remote": remote} { |
| + if _, err := reg.CreateFleet(Fleet{Name: "home", Account: "bab", Bucket: "home-data"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.SetFleetSecretsKey("home", secretsPubA, secretsFPA, "p", 1); err != nil { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + for _, c := range []struct{ what, pub, fp string }{ |
| + {"a key with no fingerprint", secretsPubA, ""}, |
| + {"a fingerprint with no key", "", secretsFPB}, |
| + } { |
| + if err := reg.SetFleetSecretsKey("home", c.pub, c.fp, "q", 2); err == nil { |
| + t.Errorf("%s: %s = nil, want an error", name, c.what) |
| + } |
| + got, _ := reg.GetFleet("home") |
| + if got == nil || got.SecretsPub != secretsPubA || got.SecretsKeyFP != secretsFPA || got.SecretsKeySetBy != "p" { |
| + t.Errorf("%s: after %s the row is %+v, want the first key untouched", name, c.what, got) |
| + } |
| + } |
| + if err := reg.SetFleetSecretsKey("home", "", "", "q", 3); err != nil { |
| + t.Errorf("%s: clearing both = %v, want nil", name, err) |
| + } |
| + } |
| +} |
diff --git a/internal/release/release.go b/internal/release/release.go| index da9b44b99..de213dcdf 100644 |
| --- a/internal/release/release.go |
| +++ b/internal/release/release.go |
| @@ -182,6 +182,13 @@ type FleetOwner struct { |
| Fleet string `json:"fleet"` |
| Account string `json:"account"` |
| CreatedAt int64 `json:"created_at,omitempty"` |
| + // SecretsKeyFPs is every secrets key fingerprint ever registered for the |
| + // fleet (fleet secrets key spec §5.1, plan ruling R-4), oldest first. It |
| + // is append-only: the console writes a key's fingerprint here before the |
| + // registry row commits, and nothing ever removes one, so a replacement |
| + // that fails in the registry still leaves the registered key listed. |
| + // Direct-bucket mode reads it; nothing on a box does. |
| + SecretsKeyFPs []string `json:"secrets_key_fps,omitempty"` |
| } |
| // ChannelPointer says which version a channel currently serves. This is the |