carlos / platform Public

services --json: only the object on stdout; fail on a lost secret

Review R1 (#1056), P1 and P2-2. In --json mode the package stdout
points at stderr for the whole verb, so default account resolution's
"account: ..." line (configured default, one membership, old-console
fallback) and the chooser no longer corrupt the JSON. Tested for
create and rotate on all three paths.

A failed write of the object is now a non-zero exit with a stderr
sentence saying the credential was created or rotated but its secret
could not be written, and to rotate it; the secret is never in it.
Tested with a failing writer and with stdout on /dev/full.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a6478cb99b8349cf27671d3f8e72e36fbfcd02f4 parent b7270ff
2 files changed, +197 −9
  • services.go +49 −9
  • services_json_test.go +148 −0
diff --git a/services.go b/services.go
index 04d48f987..56a85fa96 100644
--- a/services.go
+++ b/services.go
@@ -19,6 +19,7 @@ import (
"encoding/json"
"flag"
"fmt"
+ "io"
"log"
"os"
"regexp"
@@ -222,6 +223,12 @@ func runServicesCreate(args []string) {
log.Fatal("services create: --role team needs --app, the one app it is bound to, and --scope, the scope name whose environments it owns")
}
+ var jsonOut io.Writer
+ if *asJSON {
+ var restore func()
+ jsonOut, restore = servicesJSONStdout()
+ defer restore()
+ }
sess := servicesSignedInSession(*consoleFlag)
if !*asJSON {
fmt.Fprintf(stdout, "using %s as %s\n", sess.console, sess.address)
@@ -232,11 +239,14 @@ func runServicesCreate(args []string) {
log.Fatalf("services create: %v", err)
}
if *asJSON {
- writeServiceJSON(serviceCreatedJSON{
+ err := writeServiceJSON(jsonOut, serviceCreatedJSON{
Name: name, Account: acct.Seg, App: appV, Role: roleV,
Rungs: orEmpty(gotRungs), Commands: orEmpty(gotCommands), Scope: gotScope,
Doors: orEmpty(doors), Secret: token,
})
+ if err != nil {
+ log.Fatal(serviceSecretUnwritten("services create", "created", acct.Seg, name, err))
+ }
return
}
printServiceCreated(acct.Seg, name, roleV, appV, gotRungs, gotCommands, gotScope, token, doors)
@@ -308,16 +318,38 @@ type serviceRotatedJSON struct {
Secret string `json:"secret"`
}
-// writeServiceJSON prints v as the only thing on stdout, indented like
-// `carlos email events --json`. Nothing else is printed in this mode, not
-// even the "using" line: a script reads stdout whole. Marshalling strings
-// and string slices cannot fail.
-func writeServiceJSON(v any) {
- enc := json.NewEncoder(stdout)
+// servicesJSONStdout is --json's stdout discipline: a script reads stdout
+// whole, so the one JSON object must be the only thing on it. It returns
+// the real stdout for that object and points the package's stdout at
+// stderr until restore, so everything else this verb prints on the way
+// (the "account: …" line default account resolution writes, the chooser)
+// lands on stderr instead (#1056 review R1).
+func servicesJSONStdout() (out io.Writer, restore func()) {
+ out = stdout
+ stdout = os.Stderr
+ return out, func() { stdout = out }
+}
+
+// writeServiceJSON writes v to w, indented like `carlos email events
+// --json`, and returns the write's error: the credential has already
+// changed by now, and a secret that never reached its reader is not a
+// success (#1056 review R1).
+func writeServiceJSON(w io.Writer, v any) error {
+ enc := json.NewEncoder(w)
enc.SetIndent("", " ")
- enc.Encode(v)
+ return enc.Encode(v)
}
+// serviceSecretUnwritten is the refusal when --json could not write the
+// secret: the credential exists with a secret nobody holds, so the way out
+// is another rotate. The secret is never in it.
+func serviceSecretUnwritten(verb, done, acctSeg, name string, err error) error {
+ return fmt.Errorf(servicesCopySecretUnwritten, verb, name, done, err, acctSeg, name)
+}
+
+// #1056 review R1. Not yet through a copy pass.
+const servicesCopySecretUnwritten = "%s: %s was %s, but its secret could not be written (%v). Rotate it for a new one: carlos services rotate --account %s %s"
+
// orEmpty is s, or an empty slice for nil, so JSON says [] and not null.
func orEmpty[T any](s []T) []T {
if s == nil {
@@ -462,6 +494,12 @@ func runServicesRotate(args []string) {
log.Fatalf("services rotate: %v", err)
}
+ var jsonOut io.Writer
+ if *asJSON {
+ var restore func()
+ jsonOut, restore = servicesJSONStdout()
+ defer restore()
+ }
sess := servicesSignedInSession(*consoleFlag)
if !*asJSON {
fmt.Fprintf(stdout, "using %s as %s\n", sess.console, sess.address)
@@ -472,7 +510,9 @@ func runServicesRotate(args []string) {
log.Fatalf("services rotate: %v", err)
}
if *asJSON {
- writeServiceJSON(serviceRotatedJSON{Name: name, Account: acct.Seg, Secret: token})
+ if err := writeServiceJSON(jsonOut, serviceRotatedJSON{Name: name, Account: acct.Seg, Secret: token}); err != nil {
+ log.Fatal(serviceSecretUnwritten("services rotate", "rotated", acct.Seg, name, err))
+ }
return
}
printServiceRotated(acct.Seg, name, token)
diff --git a/services_json_test.go b/services_json_test.go
index 0e1163168..f9feb917e 100644
--- a/services_json_test.go
+++ b/services_json_test.go
@@ -9,6 +9,11 @@ import (
"encoding/json"
"errors"
"io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
"strings"
"testing"
)
@@ -106,3 +111,146 @@ func TestServicesRotateJSONIsOneObjectWithTheBareSecret(t *testing.T) {
}
}
}
+
+// servicesJSONAccountFixture is a fake console for --json with the account
+// left out: create, rotate, and the memberships listing default account
+// resolution reads (GET /api/cli/apps). accounts nil answers that listing
+// 404, the old-console fallback. It returns the console's URL.
+func servicesJSONAccountFixture(t *testing.T, accounts []map[string]any) string {
+ t.Helper()
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("CARLOS_CONSOLE", "")
+ t.Setenv("CARLOS_DEPLOYMENT_BUCKET", "")
+ t.Setenv("CARLOS_DEPLOYMENT_DIR", "")
+ t.Chdir(t.TempDir())
+ creds := filepath.Join(home, "carlos-credentials")
+ t.Setenv("CARLOS_CREDENTIALS", creds)
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /api/cli/apps", func(w http.ResponseWriter, r *http.Request) {
+ if accounts == nil {
+ http.NotFound(w, r)
+ return
+ }
+ json.NewEncoder(w).Encode(map[string]any{"accounts": accounts})
+ })
+ mux.HandleFunc("POST /api/cli/services/{account}", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusCreated)
+ json.NewEncoder(w).Encode(map[string]any{"token": tokenFor(1), "doors": []string{"GET /api/cli/apps"}})
+ })
+ mux.HandleFunc("POST /api/cli/services/{account}/{name}/rotate", func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{"token": tokenFor(1)})
+ })
+ ts := httptest.NewServer(mux)
+ t.Cleanup(ts.Close)
+ writeTestCredential(t, creds, ts.URL)
+ return ts.URL
+}
+
+// With no --account, default resolution prints "account: …" on its way;
+// in --json mode that must not reach stdout, on every path: a configured
+// default, the caller's one membership, and an old console's fallback
+// (#1056 review R1, P1).
+func TestServicesJSONWithoutAccountIsStillOneObject(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ accounts []map[string]any
+ config bool
+ want string
+ }{
+ {"configured default", []map[string]any{{"name": "shop", "sqid": "bab"}, {"name": "other", "sqid": "cad"}}, true, "bab"},
+ {"one membership", []map[string]any{{"name": "shop", "sqid": "bab"}}, false, "bab"},
+ {"old console", nil, false, "ops"},
+ } {
+ for _, verb := range [][]string{
+ {"create", "-role", "publish", "--json", "amadan-hub"},
+ {"rotate", "--json", "amadan-hub"},
+ } {
+ t.Run(tc.name+"/"+verb[0], func(t *testing.T) {
+ url := servicesJSONAccountFixture(t, tc.accounts)
+ if tc.config {
+ if err := saveConfigAccount(filepath.Join(".carlos", "config"), url, "bab", 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ buf := captureStdout(t)
+ RunServices(verb)
+ var got map[string]any
+ dec := json.NewDecoder(strings.NewReader(buf.String()))
+ if err := dec.Decode(&got); err != nil {
+ t.Fatalf("stdout is not JSON: %v\n%s", err, buf)
+ }
+ var extra json.RawMessage
+ if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
+ t.Fatalf("stdout carries more than one JSON value:\n%s", buf)
+ }
+ if got["account"] != tc.want || got["secret"] != tokenFor(1) {
+ t.Fatalf("object = %v, want account %s and the secret", got, tc.want)
+ }
+ if stdout != buf {
+ t.Fatal("the verb left the package stdout pointed elsewhere")
+ }
+ })
+ }
+ }
+}
+
+type fullWriter struct{}
+
+func (fullWriter) Write([]byte) (int, error) { return 0, errors.New("no space left on device") }
+
+// A secret that could not be written is a failure, and the refusal says
+// how to recover without the secret in it (#1056 review R1, P2).
+func TestServicesJSONWriteFailureIsReported(t *testing.T) {
+ err := writeServiceJSON(fullWriter{}, serviceRotatedJSON{Name: "amadan-hub", Account: "bab", Secret: tokenFor(1)})
+ if err == nil {
+ t.Fatal("a failed write returned nil")
+ }
+ msg := serviceSecretUnwritten("services rotate", "rotated", "bab", "amadan-hub", err).Error()
+ for _, want := range []string{"amadan-hub was rotated", "could not be written", "no space left on device", "carlos services rotate --account bab amadan-hub"} {
+ if !strings.Contains(msg, want) {
+ t.Fatalf("refusal %q lacks %q", msg, want)
+ }
+ }
+ if strings.Contains(msg, tokenFor(1)) {
+ t.Fatalf("refusal carries the secret: %q", msg)
+ }
+}
+
+// Through the binary with stdout on /dev/full: non-zero, the refusal on
+// stderr, and no secret anywhere.
+func TestServicesJSONToAFullDeviceExitsNonZero(t *testing.T) {
+ full, err := os.OpenFile("/dev/full", os.O_WRONLY, 0)
+ if err != nil {
+ t.Skip("no /dev/full here")
+ }
+ defer full.Close()
+ bin := buildCarlos(t)
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.HasSuffix(r.URL.Path, "/rotate") {
+ w.WriteHeader(http.StatusCreated)
+ }
+ json.NewEncoder(w).Encode(map[string]any{"token": tokenFor(1), "doors": []string{}})
+ }))
+ defer ts.Close()
+ scratch := t.TempDir()
+ creds := filepath.Join(scratch, "credentials")
+ writeTestCredential(t, creds, ts.URL)
+ for _, args := range [][]string{
+ {"services", "create", "--role", "publish", "--account", "bab", "--json", "amadan-hub"},
+ {"services", "rotate", "--account", "bab", "--json", "amadan-hub"},
+ } {
+ cmd := exec.Command(bin, args...)
+ cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+creds, "CARLOS_DEPLOYMENT_BUCKET=", "CARLOS_DEPLOYMENT_DIR=")
+ cmd.Dir = scratch
+ cmd.Stdout = full
+ var stderr strings.Builder
+ cmd.Stderr = &stderr
+ if err := cmd.Run(); err == nil {
+ t.Fatalf("%s exited 0 with the secret unwritten; stderr:\n%s", args[1], stderr.String())
+ }
+ if !strings.Contains(stderr.String(), "could not be written") || strings.Contains(stderr.String(), tokenFor(1)) {
+ t.Fatalf("%s: stderr = %q, want the refusal without the secret", args[1], stderr.String())
+ }
+ }
+}