carlos / platform Public

Fleet secrets key CLI: carlos fleets secrets-key (bare key or --file, parsed locally, fingerprint then the stale list), SECRETS KEY and STALE columns in fleets ls, and carlos secrets fingerprint reading CARLOS_SECRETS_KEY from a host.env without printing it (FSK-C12 to C36)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev ec8935560d7248d8f0f2bfeafe380708af750207 parent 8c5f844
5 files changed, +639 −10
  • apimode.go +55 −0
  • appconfig_cli.go +49 −2
  • approved_fleet_secrets_copy_test.go +8 −2
  • fleets.go +155 −6
  • fleets_secrets_key_cli_test.go +372 −0

Intent

Human

<task-notification> <task-id>aa60dd07600c82fc3</task-id> <tool-use-id>toolu_01VqfQdAv7noyq6nRew5gttT</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/aa60dd07600c82fc3.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3: key registration door" 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. The fleet secrets key door, the owner record's `secrets_key_fps` list and its hostops classifier change, the list fields and both page lines are in. Copy rows FSK-C01 to C11 are built. Commit: 8c5f8446 on design-fleet-secrets-key. Tests: the 12 new tests failed first, then passed. Eight mutations, including dropping the owner check and swallowing the key-in-use error, each made a test fail. The full claim invariant test passes with its new probe, and the copy gate, build, vet, gofmt and darwin/windows/arm64 builds are clean. Concerns: - **Census fails, left for Task 11:** `classifyFleetOwner` and `registerCLIRoutes` changed, and `recordFleetKeyFP` is a new unlisted Put. - **Ordering:** I run the replacement and same-key checks under the account lock, against the fleet row read again there. That closes a race with Task 5's sealing; every refusal still comes before the first write. - **In-use refusal:** a replacement the registry refuses because another fleet holds the key still leaves that key in this fleet's record (R-4 by design). It only widens direct mode's exclusion list, but Task 8 should know. - **Missing `stale`:** if the stale read fails after a registration commits, `stale` is left out of the answer. Task 4 should read that as "unknown", not "none". - **Extra `changed` key:** added to the answer so Task 4 can tell FSK-C15 from FSK-C16. - **Not in the deck:** the audit line has no copy row. - **Trashed apps:** they are not counted, so they don't block a key replacement. - **Unrelated failure:** `TestPlan14GenerationPinsPrivateMount` in internal/release fails on a permission check. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-secrets-key/.superpowers/sdd/2026-10-29-fleet-secrets-key/task-3-report.md</result> <usage><subagent_tokens>291870</subagent_tokens><tool_uses>124</tool_uses><duration_ms>2052688</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a4987f7d46dd2a94e</task-id> <tool-use-id>toolu_01TCcxHrhiQULX3ahqq7ArMi</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/a4987f7d46dd2a94e.output</output-file> <status>completed</status> <summary>Agent "Review Task 3 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Spec compliance:** ✅ compliant. All five named risks (a) to (e) checked out clean against the code. **Task quality:** Approved. **Critical and Important findings:** none. There is one cross-task item for Task 5. The handler says every seal of an app's config takes the account lock, but no seal path takes `lockAccount` today. That claim only becomes true once Task 5 adds the lock to every seal path. It must be taken before any app lock and never inside a door that already holds `planLock`, because the lock is not re-entrant. The review also lists five minor issues. Review: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-secrets-key/.superpowers/sdd/2026-10-29-fleet-secrets-key/task-3-review.md</result> <usage><subagent_tokens>115829</subagent_tokens><tool_uses>16</tool_uses><duration_ms>191810</duration_ms></usage> </task-notification>

Attributed to this commit: 13.8 g CO₂e (1,721,223 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 4b3f49744..dd5222cd1 100644
--- a/apimode.go
+++ b/apimode.go
@@ -4915,6 +4915,61 @@ type apiFleetView struct {
Name string `json:"name"`
Bucket string `json:"bucket"`
Boxes []apiFleetBox `json:"boxes"`
+ // SecretsKeyFP is the fleet's registered secrets key fingerprint and
+ // StaleSecrets the count of its apps' sealed values that key cannot
+ // open; both are absent from the wire for a fleet with no key, and the
+ // count when nothing is stale.
+ SecretsKeyFP string `json:"secrets_key_fp,omitempty"`
+ StaleSecrets int `json:"stale_secrets,omitempty"`
+}
+
+// fleetKeyStale is one app's line of the secrets key door's stale report:
+// the sealed vars the fleet's key cannot open, Minted being the ones the
+// console minted (internal/console's staleApp).
+type fleetKeyStale struct {
+ App string `json:"app"`
+ Vars []string `json:"vars"`
+ Minted []string `json:"minted"`
+}
+
+// fleetKeyAnswer is the secrets key door's answer. Changed is false for the
+// same key registered again. Stale is nil when the console could not list it
+// after a registration that did commit (the key is registered; running the
+// verb again reports it).
+type fleetKeyAnswer struct {
+ Fleet string `json:"fleet"`
+ Fingerprint string `json:"fingerprint"`
+ Changed bool `json:"changed"`
+ Stale []fleetKeyStale `json:"stale"`
+}
+
+// errFleetKeyNoFleet is setFleetSecretsKey's answer to the door's bare 404:
+// the fleet is not one of this account's.
+var errFleetKeyNoFleet = errors.New("no such fleet")
+
+// setFleetSecretsKey registers pub (base64, already parsed by the caller) as
+// fleet's secrets key — `carlos fleets secrets-key`. The console computes the
+// fingerprint itself and the answer carries it.
+func (s *apiSession) setFleetSecretsKey(ctx context.Context, a apiAcct, fleet, pub string) (fleetKeyAnswer, error) {
+ in := struct {
+ Pubkey string `json:"pubkey"`
+ }{pub}
+ status, body, err := s.putJSON(ctx, fleetPath(a, "/"+url.PathEscape(fleet)+"/secrets-key"), in)
+ if err != nil {
+ return fleetKeyAnswer{}, err
+ }
+ if status != http.StatusOK {
+ err := apiErrorFromBody(status, body)
+ if errors.Is(err, errMembershipNotFound) {
+ return fleetKeyAnswer{}, errFleetKeyNoFleet
+ }
+ return fleetKeyAnswer{}, err
+ }
+ var res fleetKeyAnswer
+ if err := json.Unmarshal(body, &res); err != nil {
+ return fleetKeyAnswer{}, fmt.Errorf("fleets secrets-key: unreadable response: %w", err)
+ }
+ return res, nil
}
// createFleet mints one account-owned fleet record — `carlos fleets create`.
diff --git a/appconfig_cli.go b/appconfig_cli.go
index 6956ab259..786ea6cb6 100644
--- a/appconfig_cli.go
+++ b/appconfig_cli.go
@@ -784,6 +784,7 @@ commands:
unset --app <a> [--environment <name>] KEY [KEY2 ...] remove secrets
list --app <a> [--environment <name>] list a secret's key names only — never values
genkey mint a CARLOS_SECRETS_KEY/PUBKEY pair
+ fingerprint [--file <path>] print the fingerprint of the key in a host.env, never the key
--environment names a bundle at apps/<acct>/<app>/environments/<name>.json —
see "carlos env" for the full explanation; the same bundle backs both env
@@ -797,8 +798,10 @@ configured; the store env vars win outright when set (direct-bucket mode,
unchanged). In that mode "secrets set" seals with CARLOS_SECRETS_PUBKEY if
it's set in this terminal's own environment, otherwise the console's own
served public key (Config.SecretsPub) if it has one — CARLOS_SECRETS_KEY
-(the PRIVATE half) never leaves the box holding it either way. genkey is
-always local, in both modes.
+(the PRIVATE half) never leaves the box holding it either way.
+genkey and fingerprint are always local, in both modes.
+for an app placed on a fleet the console serves the fleet's own key, so leave
+CARLOS_SECRETS_PUBKEY unset. register that key with "carlos fleets secrets-key".
`
// RunSecrets is the `carlos secrets` verb.
@@ -816,6 +819,8 @@ func RunSecrets(args []string) {
runSecretsList(args[1:])
case "genkey":
runSecretsGenkey(args[1:])
+ case "fingerprint":
+ runSecretsFingerprint(args[1:])
default:
fmt.Fprint(os.Stderr, secretsUsage)
os.Exit(1)
@@ -1127,6 +1132,48 @@ func runSecretsGenkey(args []string) {
"the instance's own /data/<host>.env always wins conflicts)")
}
+// hostEnvPath is where a box keeps its environment file, and so the default
+// file `carlos secrets fingerprint` reads.
+const hostEnvPath = "/etc/carlos/host.env"
+
+// secretsKeyFingerprint is the fingerprint of the public half of the
+// CARLOS_SECRETS_KEY set in the host.env-style file at path. The errors are
+// the user-facing sentences: none of them carries any of the file's content.
+func secretsKeyFingerprint(path string) (string, error) {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return "", fmt.Errorf("cannot read %s. run this as a user who can read it, or name another file with --file <path>", path)
+ }
+ val, ok := envFileValue(raw, "CARLOS_SECRETS_KEY")
+ if !ok || val == "" {
+ return "", fmt.Errorf("%s has no CARLOS_SECRETS_KEY. add the fleet's private key there as CARLOS_SECRETS_KEY=<key> and run carlos secrets fingerprint again", path)
+ }
+ priv, err := appconfig.ParsePrivateKey(val, "CARLOS_SECRETS_KEY")
+ if err != nil {
+ return "", fmt.Errorf("the CARLOS_SECRETS_KEY in %s is not a valid secrets key. make a new pair with carlos secrets genkey", path)
+ }
+ return appconfig.KeyFingerprint(priv.PublicKey()), nil
+}
+
+// runSecretsFingerprint is `carlos secrets fingerprint`: local in both modes,
+// no console call. It prints the fingerprint of the key a box holds, never
+// the key, so an owner can check it against what the fleet has registered.
+func runSecretsFingerprint(args []string) {
+ fs := flag.NewFlagSet("secrets fingerprint", flag.ExitOnError)
+ file := fs.String("file", hostEnvPath, "the host.env-style file holding CARLOS_SECRETS_KEY")
+ fs.Usage = flagUsage(fs, "usage: carlos secrets fingerprint [--file <path>]")
+ fs.Parse(args)
+ if fs.NArg() != 0 {
+ log.Fatal("usage: carlos secrets fingerprint [--file <path>]")
+ }
+ fp, err := secretsKeyFingerprint(*file)
+ if err != nil {
+ log.Fatal(err)
+ }
+ fmt.Fprintf(stdout, "the secrets key in %s has fingerprint %s\n", *file, fp)
+ fmt.Fprintln(stdout, "carlos fleets ls shows the first 12 characters after sha256:")
+}
+
// runEnvAdopt is `carlos env adopt` (team-scoped credentials §5): an
// owner's act, through a console, marking an unbound environment as owned
// by a team scope.
diff --git a/approved_fleet_secrets_copy_test.go b/approved_fleet_secrets_copy_test.go
index fe9c212d9..5a507351d 100644
--- a/approved_fleet_secrets_copy_test.go
+++ b/approved_fleet_secrets_copy_test.go
@@ -54,11 +54,17 @@ 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.
+// row is approved. Task 3 built the door, BYO page and fleet page rows; Task 4 the CLI 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",
+ "FSK-C09", "FSK-C10", "FSK-C11", "FSK-C12",
+ "FSK-C13", "FSK-C14", "FSK-C15", "FSK-C16",
+ "FSK-C17", "FSK-C18", "FSK-C19", "FSK-C20",
+ "FSK-C21", "FSK-C22", "FSK-C23", "FSK-C24",
+ "FSK-C25", "FSK-C26", "FSK-C27", "FSK-C28",
+ "FSK-C29", "FSK-C30", "FSK-C31", "FSK-C32",
+ "FSK-C33", "FSK-C34", "FSK-C35", "FSK-C36",
}
func mustParseFleetSecretsRecord(t *testing.T) []copyRow {
diff --git a/fleets.go b/fleets.go
index aaa7c2423..d5e62d552 100644
--- a/fleets.go
+++ b/fleets.go
@@ -17,17 +17,21 @@ package main
import (
"context"
+ "encoding/base64"
+ "errors"
"flag"
"fmt"
"log"
"os"
+ "strconv"
"strings"
"text/tabwriter"
+ "github.com/carlosframework/platform/internal/appconfig"
"github.com/carlosframework/platform/internal/registry"
)
-const fleetsUsage = `usage: carlos fleets <create|add-box|rotate-token|tag-box|detach-box|ls> [flags]
+const fleetsUsage = `usage: carlos fleets <create|add-box|rotate-token|tag-box|detach-box|secrets-key|ls> [flags]
create --bucket <bucket> [--account <sqid|name>] <name>
mint an account-owned fleet: a named group of remote boxes
@@ -72,9 +76,18 @@ const fleetsUsage = `usage: carlos fleets <create|add-box|rotate-token|tag-box|d
channel it already holds. This is what a compromised box
needs.
+ secrets-key [--account <sqid|name>] [--file <path>] <fleet> [<pubkey>]
+ register the public half of the fleet's secrets key. every secret
+ and credential for an app placed on the fleet is sealed to it.
+ keep the private half in each box's host.env as CARLOS_SECRETS_KEY
+ and nowhere else. make a pair with "carlos secrets genkey". only an
+ account owner can run this. --file reads a CARLOS_SECRETS_PUBKEY=
+ line or a bare key.
+
ls [--account <sqid|name>]
- list every fleet the account owns, with each box's label,
- status and tags.
+ list every fleet the account owns, with its secrets key fingerprint and each box's label,
+ status and tags. STALE counts the sealed values its boxes cannot
+ open yet.
--account <sqid|name> account the fleet belongs to (default: your only
account, or the configured/chosen one) —
@@ -106,6 +119,8 @@ func RunFleets(args []string) {
runFleetsTagBox(args[1:])
case "detach-box":
runFleetsDetachBox(args[1:])
+ case "secrets-key":
+ runFleetsSecretsKey(args[1:])
case "ls":
runFleetsList(args[1:])
default:
@@ -370,10 +385,17 @@ func runFleetsList(args []string) {
return
}
w := tabwriter.NewWriter(stdout, 0, 4, 2, ' ', 0)
- fmt.Fprintln(w, "FLEET\tBUCKET\tBOX\tSTATUS\tTAGS")
+ fmt.Fprintln(w, "FLEET\tBUCKET\tSECRETS KEY\tSTALE\tBOX\tSTATUS\tTAGS")
for _, f := range fleets {
+ key, stale := "-", "-"
+ if hex := strings.TrimPrefix(f.SecretsKeyFP, "sha256:"); hex != "" {
+ key = hex[:min(len(hex), 12)]
+ }
+ if f.StaleSecrets > 0 {
+ stale = strconv.Itoa(f.StaleSecrets)
+ }
if len(f.Boxes) == 0 {
- fmt.Fprintf(w, "%s\t%s\t-\t-\t-\n", f.Name, f.Bucket)
+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\t-\t-\t-\n", f.Name, f.Bucket, key, stale)
continue
}
for _, b := range f.Boxes {
@@ -381,8 +403,135 @@ func runFleetsList(args []string) {
if tags == "" {
tags = "-"
}
- fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", f.Name, f.Bucket, b.Label, b.Status, tags)
+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", f.Name, f.Bucket, key, stale, b.Label, b.Status, tags)
}
}
w.Flush()
}
+
+// fleetPubKeyEnvName is the line `carlos secrets genkey` prints for the public
+// half, and the one `fleets secrets-key --file` looks for.
+const fleetPubKeyEnvName = "CARLOS_SECRETS_PUBKEY"
+
+// envFileValue is the value of the first NAME=value line of a host.env-style
+// file: blank lines and # comments skipped, an `export ` prefix and one pair
+// of surrounding quotes dropped. ok is false when no line sets NAME.
+func envFileValue(raw []byte, name string) (value string, ok bool) {
+ for _, line := range strings.Split(string(raw), "\n") {
+ line = strings.TrimSpace(line)
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ line = strings.TrimSpace(strings.TrimPrefix(line, "export "))
+ v, found := strings.CutPrefix(line, name+"=")
+ if !found {
+ continue
+ }
+ v = strings.TrimSpace(v)
+ if len(v) >= 2 && (v[0] == '"' || v[0] == '\'') && v[len(v)-1] == v[0] {
+ v = v[1 : len(v)-1]
+ }
+ return v, true
+ }
+ return "", false
+}
+
+// readFleetPubKeyFile is the base64 public key in path: its
+// CARLOS_SECRETS_PUBKEY= line, or, when the file has no such line and holds
+// exactly one non-blank, non-comment line, that line as a bare key. The
+// caller parses what comes back; an empty string is a file with no key in it.
+func readFleetPubKeyFile(path string) (string, error) {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return "", fmt.Errorf("cannot read %s. check the path, or pass the key as <pubkey>", path)
+ }
+ if v, ok := envFileValue(raw, fleetPubKeyEnvName); ok {
+ return v, nil
+ }
+ var lines []string
+ for _, line := range strings.Split(string(raw), "\n") {
+ if line = strings.TrimSpace(line); line != "" && !strings.HasPrefix(line, "#") {
+ lines = append(lines, line)
+ }
+ }
+ if len(lines) != 1 {
+ return "", nil
+ }
+ return lines[0], nil
+}
+
+// runFleetsSecretsKey is `carlos fleets secrets-key`: register the public
+// half of a fleet's secrets key. The key is parsed here first, so a key the
+// console is certain to refuse costs no request; the fingerprint printed is
+// the console's own, computed from the key it parsed.
+func runFleetsSecretsKey(args []string) {
+ fs := flag.NewFlagSet("fleets secrets-key", flag.ExitOnError)
+ acctRaw := fs.String("account", "", "account (sqid or name) the fleet belongs to (default: your only account, or the configured/chosen one)")
+ acctIDRaw := fs.String("account-id", "", "account sqid, matched as a sqid ONLY — supersedes --account")
+ consoleFlag := consoleOption(fs, "console to register through (default: the only logged-in one)")
+ file := fs.String("file", "", "read the public key from this file")
+ const keyUsage = "usage: carlos fleets secrets-key [--account <sqid|name>] [--file <path>] <fleet> [<pubkey>]"
+ fs.Usage = flagUsage(fs, keyUsage)
+ fs.Parse(args)
+ if fs.NArg() < 1 || fs.NArg() > 2 || (*file != "" && fs.NArg() != 1) {
+ log.Fatal(keyUsage)
+ }
+ fleet := strings.TrimSpace(fs.Arg(0))
+ if err := validFleetName(fleet); err != nil {
+ log.Fatalf("fleets secrets-key: %v", err)
+ }
+ raw := ""
+ switch {
+ case *file != "":
+ var err error
+ if raw, err = readFleetPubKeyFile(*file); err != nil {
+ log.Fatal(err)
+ }
+ case fs.NArg() == 2:
+ raw = fs.Arg(1)
+ default:
+ log.Fatal("pass the public key as <pubkey> or with --file <path>")
+ }
+ key, err := appconfig.ParsePublicKey(raw, fleetPubKeyEnvName)
+ if err != nil {
+ log.Fatal("that is not a public secrets key. use the CARLOS_SECRETS_PUBKEY value that carlos secrets genkey prints")
+ }
+
+ sess := fleetsSignedInSession(*consoleFlag)
+ fmt.Fprintf(stdout, "using %s as %s\n", sess.console, sess.address)
+ acct := resolvedAccount(sess, acctRaw, acctIDRaw)
+ ans, err := sess.setFleetSecretsKey(context.Background(), acct, fleet, base64.StdEncoding.EncodeToString(key.Bytes()))
+ if errors.Is(err, errFleetKeyNoFleet) {
+ log.Fatalf("no fleet called %s in this account. run carlos fleets ls to see yours", fleet)
+ }
+ if err != nil {
+ log.Fatalf("fleets secrets-key: %v", err)
+ }
+ if ans.Changed {
+ fmt.Fprintf(stdout, "registered the secrets key for %s. fingerprint %s\n", fleet, ans.Fingerprint)
+ } else {
+ fmt.Fprintln(stdout, fmt.Sprintf("%s already has this secrets key. fingerprint %s. nothing changed", fleet, ans.Fingerprint))
+ }
+ printFleetKeyStale(fleet, ans.Stale)
+}
+
+// printFleetKeyStale prints the key door's stale list: each app's values the
+// fleet's boxes cannot open yet, the ones the console minted on their own
+// line, then how to fix both. Nothing is printed for an empty list, and
+// nothing for an absent one: the console says it could not list them, and the
+// deck has no sentence for that.
+func printFleetKeyStale(fleet string, stale []fleetKeyStale) {
+ if len(stale) == 0 {
+ return
+ }
+ fmt.Fprintln(stdout, fmt.Sprintf("these apps on %s hold values its boxes cannot open yet:", fleet))
+ for _, a := range stale {
+ if len(a.Vars) > 0 {
+ fmt.Fprintln(stdout, fmt.Sprintf("%s: %s", a.App, strings.Join(a.Vars, ", ")))
+ }
+ if len(a.Minted) > 0 {
+ fmt.Fprintln(stdout, fmt.Sprintf("%s: %s (minted by the console)", a.App, strings.Join(a.Minted, ", ")))
+ }
+ }
+ fmt.Fprintln(stdout, "set each secret again with carlos secrets set --app <app> <var>=<value>. for a credential the console minted, run carlos store rotate --app <app> or carlos email rotate --app <app>")
+}
diff --git a/fleets_secrets_key_cli_test.go b/fleets_secrets_key_cli_test.go
new file mode 100644
index 000000000..b34931fb0
--- /dev/null
+++ b/fleets_secrets_key_cli_test.go
@@ -0,0 +1,372 @@
+// Tests for `carlos fleets secrets-key`, the SECRETS KEY and STALE columns of
+// `carlos fleets ls`, and `carlos secrets fingerprint` (fleet secrets key
+// plan Task 4). The first two run the real verbs in-process against a REAL
+// console.Server (DirStore, registry, owner record), the shape
+// config_e2e_test.go uses, so the CLI's request, the console's answer and
+// the printed text are all the production ones.
+package main
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// fskCLI is a real console with the ops account (sqid bab), a logged-in
+// credential, a fleet home, and an app shop placed on it.
+type fskCLI struct {
+ rel release.Store
+ sess *apiSession
+ depPub string // the deployment's own public key
+ account string
+}
+
+func fskCLIFixture(t *testing.T) *fskCLI {
+ t.Helper()
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ t.Setenv("CARLOS_SECRETS_PUBKEY", "")
+
+ tmp := t.TempDir()
+ rel := release.NewDirStore(filepath.Join(tmp, "store"))
+ _, depPub, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ seed, pubB64, err := release.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ priv, err := release.ParseSigningKey(seed, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := release.ParsePublicKey(pubB64, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ cst, err := console.Open(filepath.Join(tmp, "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cst.Close() })
+ var srv *console.Server
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ srv.ServeHTTP(w, r)
+ }))
+ t.Cleanup(ts.Close)
+ srv, err = console.NewServer(console.Config{
+ Origin: ts.URL,
+ Keymail: "http://keymail.invalid",
+ Registry: filepath.Join(tmp, "registry.db"),
+ Releases: rel,
+ ReleasePub: pub,
+ Key: priv,
+ AppScheme: "http",
+ SecretsPub: depPub,
+ }, cst)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const addr = "paul@keymail.dev"
+ if err := cst.AddMember(console.OpsAccountID, addr, console.RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := cst.CreateAppIn(console.OpsAccountID, "shop", addr, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ token, expiresAt := e2eDeviceLogin(t, ts.URL, cst, addr, "fsk@laptop")
+ creds, err := loadCredentials()
+ if err != nil {
+ t.Fatal(err)
+ }
+ creds.put(credential{Console: ts.URL, Address: addr, Token: token, ExpiresAt: expiresAt})
+ if err := creds.save(); err != nil {
+ t.Fatal(err)
+ }
+ fx := &fskCLI{
+ rel: rel,
+ sess: &apiSession{c: newConsoleClient(ts.URL, token), console: ts.URL, address: addr},
+ depPub: depPub,
+ account: release.OpsAccount,
+ }
+ buf := captureStdout(t)
+ RunFleets([]string{"create", "-bucket", "home-data", "-account", "ops", "home"})
+ if err := fx.sess.place(context.Background(), apiAcct{Seg: "ops"}, "shop", "fleet/home"); err != nil {
+ t.Fatalf("place shop on home: %v", err)
+ }
+ buf.Reset()
+ return fx
+}
+
+// seal is a real envelope for shop sealed to sealedTo's public half ("" for
+// the deployment key with no sealed_to, a value from before keys existed).
+func (fx *fskCLI) setSecrets(t *testing.T, pubB64 string, names ...string) {
+ t.Helper()
+ pub, err := appconfig.ParsePublicKey(pubB64, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ b := appconfig.Binding{Account: fx.account, App: "shop"}
+ vars := map[string]appconfig.Var{}
+ for _, n := range names {
+ if pubB64 == fx.depPub {
+ env, err := appconfig.Seal(pub, b, []byte("value"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ vars[n] = appconfig.Var{Kind: "secret", Envelope: env}
+ continue
+ }
+ v, err := appconfig.NewSealer(pub, b, true).Seal(b, []byte("value"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ vars[n] = v
+ }
+ if err := appconfig.SetSecret(context.Background(), fx.rel, fx.account, "shop", vars); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestFleetsSecretsKeyCLI(t *testing.T) {
+ fx := fskCLIFixture(t)
+
+ // A bare key as the argument registers, and the fingerprint is printed.
+ priv1, pub1, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ fp1, err := appconfig.PublicFingerprint(pub1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ buf := captureStdout(t)
+ RunFleets([]string{"secrets-key", "-account", "ops", "home", pub1})
+ if want := "registered the secrets key for home. fingerprint " + fp1 + "\n"; !strings.Contains(buf.String(), want) {
+ t.Fatalf("output = %q, want it to contain %q", buf.String(), want)
+ }
+
+ // The same key again is the no-op row.
+ buf.Reset()
+ RunFleets([]string{"secrets-key", "-account", "ops", "home", pub1})
+ if want := "home already has this secrets key. fingerprint " + fp1 + ". nothing changed\n"; !strings.Contains(buf.String(), want) {
+ t.Fatalf("output = %q, want it to contain %q", buf.String(), want)
+ }
+
+ // --file with `carlos secrets genkey`'s own output (both lines) registers
+ // the PUBKEY line on a second fleet, and never reads the KEY line out.
+ fskMakeFleet(t, "away")
+ _ = priv1
+ priv2, pub2, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ fp2, _ := appconfig.PublicFingerprint(pub2)
+ keyFile := filepath.Join(t.TempDir(), "genkey.out")
+ if err := os.WriteFile(keyFile, []byte("CARLOS_SECRETS_KEY="+priv2+"\nCARLOS_SECRETS_PUBKEY="+pub2+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ buf.Reset()
+ RunFleets([]string{"secrets-key", "-account", "ops", "-file", keyFile, "away"})
+ if want := "registered the secrets key for away. fingerprint " + fp2 + "\n"; !strings.Contains(buf.String(), want) {
+ t.Fatalf("output = %q, want it to contain %q", buf.String(), want)
+ }
+ if strings.Contains(buf.String(), priv2) {
+ t.Fatalf("output carries the private key: %q", buf.String())
+ }
+
+ // The registry holds what was registered.
+ fleets, err := fx.sess.listFleets(context.Background(), apiAcct{Seg: "ops"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := map[string]string{}
+ for _, f := range fleets {
+ got[f.Name] = f.SecretsKeyFP
+ }
+ if got["home"] != fp1 || got["away"] != fp2 {
+ t.Fatalf("listed fingerprints = %v, want home %s away %s", got, fp1, fp2)
+ }
+}
+
+// fskMakeFleet creates one more fleet through the verb.
+func fskMakeFleet(t *testing.T, name string) {
+ t.Helper()
+ RunFleets([]string{"create", "-bucket", name + "-data", "-account", "ops", name})
+}
+
+func TestFleetsSecretsKeyCLIPrintsStaleValues(t *testing.T) {
+ fx := fskCLIFixture(t)
+ fx.setSecrets(t, fx.depPub, "API_KEY", "CARLOS_STORE_SECRET_KEY")
+ _, pub, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ buf := captureStdout(t)
+ RunFleets([]string{"secrets-key", "-account", "ops", "home", pub})
+ out := buf.String()
+ for _, want := range []string{
+ "these apps on home hold values its boxes cannot open yet:\n",
+ "shop: API_KEY\n",
+ "shop: CARLOS_STORE_SECRET_KEY (minted by the console)\n",
+ "set each secret again with carlos secrets set --app <app> <var>=<value>. for a credential the console minted, run carlos store rotate --app <app> or carlos email rotate --app <app>\n",
+ } {
+ if !strings.Contains(out, want) {
+ t.Fatalf("output missing %q:\n%s", want, out)
+ }
+ }
+}
+
+func TestFleetsLsShowsSecretsKey(t *testing.T) {
+ fx := fskCLIFixture(t)
+ fx.setSecrets(t, fx.depPub, "API_KEY", "DB_PASSWORD")
+ ls := func() string {
+ buf := captureStdout(t)
+ RunFleets([]string{"ls", "-account", "ops"})
+ return buf.String()
+ }
+ row := func(out, fleet string) []string {
+ t.Helper()
+ for _, line := range strings.Split(out, "\n") {
+ if f := strings.Fields(line); len(f) > 0 && f[0] == fleet {
+ return f
+ }
+ }
+ t.Fatalf("no row for %s in:\n%s", fleet, out)
+ return nil
+ }
+
+ out := ls()
+ if h := strings.Fields(out[strings.Index(out, "FLEET"):strings.Index(out, "\n"+row(out, "home")[0])]); strings.Join(h, " ") != "FLEET BUCKET SECRETS KEY STALE BOX STATUS TAGS" {
+ t.Fatalf("header = %q", h)
+ }
+ // No key: both columns read "-".
+ if f := row(out, "home"); f[2] != "-" || f[3] != "-" {
+ t.Fatalf("keyless row = %v, want - and - in the key and stale columns", f)
+ }
+
+ priv, pub, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ fp, _ := appconfig.PublicFingerprint(pub)
+ buf := captureStdout(t)
+ RunFleets([]string{"secrets-key", "-account", "ops", "home", pub})
+ buf.Reset()
+ out = ls()
+ short := strings.TrimPrefix(fp, "sha256:")[:12]
+ if f := row(out, "home"); f[2] != short || f[3] != "2" {
+ t.Fatalf("keyed row = %v, want %s and 2", f, short)
+ }
+ if strings.Contains(out, fp) || strings.Contains(out, priv) {
+ t.Fatalf("ls prints more than the short fingerprint:\n%s", out)
+ }
+
+ // The two secrets set again, sealed to the fleet's key, clear the count.
+ fx.setSecrets(t, pub, "API_KEY", "DB_PASSWORD")
+ if f := row(ls(), "home"); f[2] != short || f[3] != "-" {
+ t.Fatalf("after re-sealing, row = %v, want %s and -", f, short)
+ }
+}
+
+func TestFleetsSecretsKeyFromFileGrammar(t *testing.T) {
+ priv, pub, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ write := func(name, body string) string {
+ p := filepath.Join(dir, name)
+ if err := os.WriteFile(p, []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return p
+ }
+ for name, body := range map[string]string{
+ "bare": pub + "\n",
+ "line": "CARLOS_SECRETS_PUBKEY=" + pub + "\n",
+ "genkey": "CARLOS_SECRETS_KEY=" + priv + "\nCARLOS_SECRETS_PUBKEY=" + pub + "\n",
+ "quoted": "export CARLOS_SECRETS_PUBKEY=\"" + pub + "\"\n",
+ "commented": "# the fleet key\n\nCARLOS_SECRETS_PUBKEY=" + pub + "\n",
+ "no newline": pub,
+ "crlf": "CARLOS_SECRETS_PUBKEY=" + pub + "\r\n",
+ "blank first": "\n " + pub + " \n",
+ } {
+ got, err := readFleetPubKeyFile(write(strings.ReplaceAll(name, " ", "_"), body))
+ if err != nil || got != pub {
+ t.Errorf("%s: got %q, %v, want the key", name, got, err)
+ }
+ }
+ // A file holding only the private key is not a public key.
+ got, err := readFleetPubKeyFile(write("privonly", "CARLOS_SECRETS_KEY="+priv+"\n"))
+ if err == nil && got != "" {
+ if _, perr := appconfig.ParsePublicKey(got, "x"); perr == nil {
+ t.Errorf("a private-key-only file yielded a parseable public key")
+ }
+ }
+ if _, err := readFleetPubKeyFile(filepath.Join(dir, "missing")); err == nil {
+ t.Error("a missing file read without error")
+ }
+}
+
+func TestSecretsFingerprintReadsHostEnv(t *testing.T) {
+ priv, pub, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ fp, err := appconfig.PublicFingerprint(pub)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ env := filepath.Join(dir, "host.env")
+ body := "CARLOS_EDGE=1\n# the fleet key\nexport CARLOS_SECRETS_KEY=\"" + priv + "\"\nOTHER=x\n"
+ if err := os.WriteFile(env, []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ // No network: the credential file points nowhere and no console exists.
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+
+ buf := captureStdout(t)
+ RunSecrets([]string{"fingerprint", "-file", env})
+ out := buf.String()
+ if want := "the secrets key in " + env + " has fingerprint " + fp + "\n"; !strings.Contains(out, want) {
+ t.Fatalf("output = %q, want it to contain %q", out, want)
+ }
+ if want := "carlos fleets ls shows the first 12 characters after sha256:\n"; !strings.Contains(out, want) {
+ t.Fatalf("output = %q, want it to contain %q", out, want)
+ }
+ if strings.Contains(out, priv) || strings.Contains(out, pub) {
+ t.Fatalf("output carries key material: %q", out)
+ }
+
+ // The errors name the file and never the key.
+ if _, err := secretsKeyFingerprint(filepath.Join(dir, "missing.env")); err == nil || !strings.Contains(err.Error(), "cannot read "+filepath.Join(dir, "missing.env")+". run this as a user who can read it") {
+ t.Errorf("missing file error = %v", err)
+ }
+ empty := filepath.Join(dir, "empty.env")
+ os.WriteFile(empty, []byte("OTHER=x\n"), 0o600)
+ if _, err := secretsKeyFingerprint(empty); err == nil || !strings.Contains(err.Error(), empty+" has no CARLOS_SECRETS_KEY. add the fleet's private key there") {
+ t.Errorf("no-key error = %v", err)
+ }
+ bad := filepath.Join(dir, "bad.env")
+ os.WriteFile(bad, []byte("CARLOS_SECRETS_KEY=not-a-key-SECRETVALUE\n"), 0o600)
+ err = nil
+ if _, err = secretsKeyFingerprint(bad); err == nil || !strings.Contains(err.Error(), "the CARLOS_SECRETS_KEY in "+bad+" is not a valid secrets key. make a new pair with carlos secrets genkey") {
+ t.Errorf("bad-key error = %v", err)
+ }
+ if err != nil && strings.Contains(err.Error(), "SECRETVALUE") {
+ t.Errorf("bad-key error echoes the key: %v", err)
+ }
+}