carlos / platform Public

store write credential: carlos store credential

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 344ce17b39e7c83a3b8fb7d4859d585e30ccb434 parent 4091a73
4 files changed, +328 −2
  • store.go +3 −1
  • store_credential.go +191 −0
  • store_credential_test.go +133 −0
  • store_test.go +1 −1
diff --git a/store.go b/store.go
index f1c2b05ae..2a0b94217 100644
--- a/store.go
+++ b/store.go
@@ -46,7 +46,7 @@ import (
"github.com/carlosframework/platform/internal/objstore"
)
-var storeUsage = `usage: carlos store <create|status|apply|approvals|approve|decline|grant|rotate|scan|uploads|versioning|versions|restore> [flags]
+var storeUsage = `usage: carlos store <create|status|apply|approvals|approve|decline|grant|rotate|credential|scan|uploads|versioning|versions|restore> [flags]
create --app <a> [--env-prefix <PREFIX>] [--environment <e>] [--versioning [--keep-days <n>]]
@@ -80,6 +80,7 @@ var storeUsage = `usage: carlos store <create|status|apply|approvals|approve|dec
mint a fresh credential, leaving the old one live
until --finish deletes it. A member verb: spends
nothing new, so there is no operator gate here.
+` + storeCredentialText("store_usage") + `
scan <sub-verb> --app <a>
virus scanning over the store's objects — off by
default. Run carlos store scan on its own to list
@@ -121,6 +122,7 @@ func storeCommand() *clireg.Node {
raw("status", cust, runStoreStatus),
raw("grant", op, runStoreGrant),
raw("rotate", cust, runStoreRotate),
+ rawErr("credential", cust, runStoreCredential),
raw("apply", cust, runStoreApply),
raw("approvals", op, runStoreApprovals),
raw("approve", op, runStoreApprove),
diff --git a/store_credential.go b/store_credential.go
new file mode 100644
index 000000000..e8e143859
--- /dev/null
+++ b/store_credential.go
@@ -0,0 +1,191 @@
+// store_credential.go is `carlos store credential`: mint a write credential
+// for an app's store, or revoke every one it issued (store write credential
+// spec, 2026-11-25). API mode only, like the rest of `store`. A write
+// credential can only upload under one prefix of the store, for a lifetime
+// from 15 minutes to 24 hours, and is meant for a third party such as a
+// LiveKit recorder. The console mints it; this file sends the request and
+// prints the answer.
+//
+// The secret and session token go to stdout and nowhere else.
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/objstore"
+)
+
+// storeCredentialCopy is this verb's text by key. New copy, pending the Luna
+// pass (docs/superpowers/notes/copy-luna-brief-store-write-credential.md).
+var storeCredentialCopy = map[string]string{
+ "usage": "usage: carlos store credential --write --prefix <folder/> --ttl <duration> --app <a> [--environment <e>] [--json]\n" +
+ " carlos store credential --revoke --app <a> [--environment <e>] [--json]",
+ "store_usage": " credential --write --prefix <folder/> --ttl <duration> --app <a> [--json]\n" +
+ " Prints a credential that can only upload files\n" +
+ " under one folder of the app's store, for 15 minutes\n" +
+ " to 24 hours. Give it to a service that uploads for\n" +
+ " you, such as a LiveKit recorder. --revoke stops\n" +
+ " every one issued so far.",
+ "flag_write": "mint a credential that can only upload under --prefix",
+ "flag_revoke": "revoke every write credential this store has issued",
+ "flag_prefix": "the folder the credential may upload into, ending in /, such as recordings/",
+ "flag_ttl": "how long the credential works, from 15m to 24h, such as 4h",
+ "flag_json": "print the answer as JSON, with the field names LiveKit's S3Upload takes",
+ "flag_app": "app whose store the credential is for",
+ "need_one": "say --write or --revoke",
+ "need_prefix": "--write needs --prefix, such as --prefix recordings/",
+ "need_ttl": "--write needs --ttl, such as --ttl 4h",
+ "revoke_flags": "--revoke takes no --prefix or --ttl",
+ "line_expires": "write credential expires %s (in %s)",
+ "line_scope": "can do upload under %s, nothing else",
+ "line_bucket": "bucket %s",
+ "line_region": "region %s",
+ "line_access_key": "access_key %s",
+ "line_secret": "secret %s",
+ "line_token": "session_token %s",
+ "line_revoked": "write credentials revoked",
+ "line_revoked_at": "issued before %s",
+ "line_revoke_note": "note this can take a few minutes to reach every upload",
+ "unreadable": "store credential: unreadable response: %w",
+}
+
+func storeCredentialText(key string) string { return storeCredentialCopy[key] }
+
+// apiWriteCredential mirrors the console's mint answer.
+type apiWriteCredential struct {
+ AccessKey string `json:"access_key"`
+ Secret string `json:"secret"`
+ SessionToken string `json:"session_token"`
+ Region string `json:"region"`
+ Bucket string `json:"bucket"`
+ Prefix string `json:"prefix"`
+ ExpiresAt time.Time `json:"expires_at"`
+}
+
+// apiWriteRevoke mirrors the console's revoke answer.
+type apiWriteRevoke struct {
+ RevokedBefore time.Time `json:"revoked_before"`
+}
+
+func (s *apiSession) storeCredentialCall(ctx context.Context, a apiAcct, app, env, tail string, in any, out any) error {
+ status, body, err := s.postJSON(ctx, apiPath(a, app, storeEnvTail(tail, env)), in)
+ if err != nil {
+ return err
+ }
+ if status != http.StatusOK {
+ return apiErrorFromBody(status, body)
+ }
+ if err := json.Unmarshal(body, out); err != nil {
+ return fmt.Errorf(storeCredentialText("unreadable"), err)
+ }
+ return nil
+}
+
+func runStoreCredential(args []string) error {
+ fs := flag.NewFlagSet("store credential", flag.ExitOnError)
+ app := appFlag(fs, storeCredentialText("flag_app"))
+ write := fs.Bool("write", false, storeCredentialText("flag_write"))
+ revoke := fs.Bool("revoke", false, storeCredentialText("flag_revoke"))
+ prefix := fs.String("prefix", "", storeCredentialText("flag_prefix"))
+ ttl := fs.Duration("ttl", 0, storeCredentialText("flag_ttl"))
+ asJSON := fs.Bool("json", false, storeCredentialText("flag_json"))
+ environment := storeEnvironmentFlag(fs, "a credential for this config environment's store instead of the app's own")
+ acctRaw, acctIDRaw, _ := accountFlags(fs)
+ consoleFlag := consoleOption(fs, "console origin to act through (API mode only; default: the only logged-in one)")
+ fs.Usage = flagUsage(fs, "")
+ fs.Parse(args)
+
+ if err := storeCredentialFlags(*write, *revoke, *prefix, *ttl); err != nil {
+ return fmt.Errorf("store credential: %w\n%s", err, storeCredentialText("usage"))
+ }
+ name := strings.TrimSpace(*app)
+ if name != "" {
+ if err := validAppName(name); err != nil {
+ return fmt.Errorf("store credential: %w", err)
+ }
+ }
+ sess := requireStoreAPISession(*consoleFlag)
+ if !*asJSON {
+ printUsing(stdout, sess)
+ }
+ acct := resolvedAccount(sess, acctRaw, acctIDRaw)
+ name = resolvedApp(sess, acct, name, storeCredentialText("usage"))
+ env := strings.TrimSpace(*environment)
+ ctx := context.Background()
+ if *revoke {
+ var res apiWriteRevoke
+ if err := sess.storeCredentialCall(ctx, acct, name, env, "/store/credentials/revoke", struct{}{}, &res); err != nil {
+ return fmt.Errorf("store credential --revoke: %w", err)
+ }
+ return printStoreRevoke(stdout, res, *asJSON)
+ }
+ in := struct {
+ Access string `json:"access"`
+ Prefix string `json:"prefix"`
+ TTLSeconds int64 `json:"ttl_seconds"`
+ }{"write", *prefix, int64(*ttl / time.Second)}
+ var res apiWriteCredential
+ if err := sess.storeCredentialCall(ctx, acct, name, env, "/store/credentials", in, &res); err != nil {
+ return fmt.Errorf("store credential --write: %w", err)
+ }
+ return printStoreCredential(stdout, res, *asJSON, time.Now())
+}
+
+// storeCredentialFlags checks the flags before any request: exactly one of
+// --write and --revoke, and for --write a prefix and lifetime the console
+// would take. The console checks them again.
+func storeCredentialFlags(write, revoke bool, prefix string, ttl time.Duration) error {
+ switch {
+ case write == revoke:
+ return errors.New(storeCredentialText("need_one"))
+ case revoke && (prefix != "" || ttl != 0):
+ return errors.New(storeCredentialText("revoke_flags"))
+ case revoke:
+ return nil
+ case prefix == "":
+ return errors.New(storeCredentialText("need_prefix"))
+ case ttl == 0:
+ return errors.New(storeCredentialText("need_ttl"))
+ }
+ if err := objstore.ValidWritePrefix(prefix); err != nil {
+ return err
+ }
+ return objstore.ValidWriteTTL(ttl)
+}
+
+// printStoreCredential leads with when the credential stops working and
+// what it may do, then the values a third party needs.
+func printStoreCredential(w io.Writer, c apiWriteCredential, asJSON bool, now time.Time) error {
+ if asJSON {
+ enc := json.NewEncoder(w)
+ enc.SetIndent("", " ")
+ return enc.Encode(c)
+ }
+ left := c.ExpiresAt.Sub(now).Round(time.Minute)
+ fmt.Fprintf(w, storeCredentialText("line_expires")+"\n", c.ExpiresAt.UTC().Format("2006-01-02 15:04 UTC"), left)
+ fmt.Fprintf(w, storeCredentialText("line_scope")+"\n", c.Prefix)
+ fmt.Fprintf(w, storeCredentialText("line_bucket")+"\n", c.Bucket)
+ fmt.Fprintf(w, storeCredentialText("line_region")+"\n", c.Region)
+ fmt.Fprintf(w, storeCredentialText("line_access_key")+"\n", c.AccessKey)
+ fmt.Fprintf(w, storeCredentialText("line_secret")+"\n", c.Secret)
+ fmt.Fprintf(w, storeCredentialText("line_token")+"\n", c.SessionToken)
+ return nil
+}
+
+func printStoreRevoke(w io.Writer, r apiWriteRevoke, asJSON bool) error {
+ if asJSON {
+ return json.NewEncoder(w).Encode(r)
+ }
+ fmt.Fprintln(w, storeCredentialText("line_revoked"))
+ fmt.Fprintf(w, storeCredentialText("line_revoked_at")+"\n", r.RevokedBefore.UTC().Format("2006-01-02 15:04:05 UTC"))
+ fmt.Fprintln(w, storeCredentialText("line_revoke_note"))
+ return nil
+}
diff --git a/store_credential_test.go b/store_credential_test.go
new file mode 100644
index 000000000..0bb417d24
--- /dev/null
+++ b/store_credential_test.go
@@ -0,0 +1,133 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestStoreCredentialFlags(t *testing.T) {
+ for _, tc := range []struct {
+ write, revoke bool
+ prefix string
+ ttl time.Duration
+ want string // "" ok, else a fragment of the refusal
+ }{
+ {true, false, "recordings/", 4 * time.Hour, ""},
+ {false, true, "", 0, ""},
+ {false, false, "", 0, "--write or --revoke"},
+ {true, true, "recordings/", time.Hour, "--write or --revoke"},
+ {false, true, "recordings/", 0, "takes no --prefix"},
+ {true, false, "", time.Hour, "needs --prefix"},
+ {true, false, "recordings/", 0, "needs --ttl"},
+ {true, false, "recordings", time.Hour, "end it with /"},
+ {true, false, "recordings/", 25 * time.Hour, "lifetime"},
+ } {
+ err := storeCredentialFlags(tc.write, tc.revoke, tc.prefix, tc.ttl)
+ if tc.want == "" && err != nil || tc.want != "" && (err == nil || !strings.Contains(err.Error(), tc.want)) {
+ t.Errorf("flags %+v: %v, want %q", tc, err, tc.want)
+ }
+ }
+}
+
+// The wire shape and both outputs. The human form leads with the expiry
+// and the scope; --json is the console's answer, with S3Upload's names.
+func TestStoreCredentialVerb(t *testing.T) {
+ var calls []string
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ calls = append(calls, r.Method+" "+r.URL.RequestURI()+" "+string(b))
+ if strings.HasSuffix(r.URL.Path, "/revoke") {
+ io.WriteString(w, `{"revoked_before":"2026-11-25T10:01:01Z"}`)
+ return
+ }
+ io.WriteString(w, `{"access_key":"ASIAX","secret":"s3cr3t","session_token":"tok","region":"eu-west-1",`+
+ `"bucket":"carlos-store-bab-shop","prefix":"recordings/","expires_at":"2026-11-25T14:00:00Z"}`)
+ }))
+ defer ts.Close()
+ s := newTestSession(ts.URL)
+ a := apiAcct{Seg: "bab"}
+ ctx := context.Background()
+
+ var c apiWriteCredential
+ in := map[string]any{"access": "write", "prefix": "recordings/", "ttl_seconds": 14400}
+ if err := s.storeCredentialCall(ctx, a, "shop", "", "/store/credentials", in, &c); err != nil {
+ t.Fatal(err)
+ }
+ var out bytes.Buffer
+ if err := printStoreCredential(&out, c, false, time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)); err != nil {
+ t.Fatal(err)
+ }
+ want := "write credential expires 2026-11-25 14:00 UTC (in 4h0m0s)\n" +
+ "can do upload under recordings/, nothing else\n" +
+ "bucket carlos-store-bab-shop\n" +
+ "region eu-west-1\n" +
+ "access_key ASIAX\n" +
+ "secret s3cr3t\n" +
+ "session_token tok\n"
+ if out.String() != want {
+ t.Fatalf("human output:\n%s\nwant:\n%s", out.String(), want)
+ }
+ out.Reset()
+ if err := printStoreCredential(&out, c, true, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ var j map[string]any
+ if err := json.Unmarshal(out.Bytes(), &j); err != nil {
+ t.Fatal(err)
+ }
+ for _, k := range []string{"access_key", "secret", "session_token", "region", "bucket", "prefix", "expires_at"} {
+ if _, ok := j[k]; !ok {
+ t.Fatalf("--json has no %s: %s", k, out.String())
+ }
+ }
+
+ var r apiWriteRevoke
+ if err := s.storeCredentialCall(ctx, a, "shop", "live", "/store/credentials/revoke", struct{}{}, &r); err != nil {
+ t.Fatal(err)
+ }
+ out.Reset()
+ if err := printStoreRevoke(&out, r, false); err != nil {
+ t.Fatal(err)
+ }
+ if want := "write credentials revoked\nissued before 2026-11-25 10:01:01 UTC\nnote this can take a few minutes to reach every upload\n"; out.String() != want {
+ t.Fatalf("revoke output:\n%s\nwant:\n%s", out.String(), want)
+ }
+ wantCalls := []string{
+ `POST /api/cli/apps/bab/shop/store/credentials {"access":"write","prefix":"recordings/","ttl_seconds":14400}`,
+ `POST /api/cli/apps/bab/shop/store/credentials/revoke?environment=live {}`,
+ }
+ if strings.Join(calls, "\n") != strings.Join(wantCalls, "\n") {
+ t.Fatalf("calls:\n%s\nwant:\n%s", strings.Join(calls, "\n"), strings.Join(wantCalls, "\n"))
+ }
+}
+
+// A refusal is the console's sentence.
+func TestStoreCredentialRefusalIsTheConsolesSentence(t *testing.T) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ io.WriteString(w, `{"error":"this console release cannot issue write credentials yet","code":"write_credentials_not_released"}`)
+ }))
+ defer ts.Close()
+ var c apiWriteCredential
+ err := newTestSession(ts.URL).storeCredentialCall(context.Background(), apiAcct{Seg: "bab"}, "shop", "", "/store/credentials", struct{}{}, &c)
+ if err == nil || !strings.Contains(err.Error(), "cannot issue write credentials yet") {
+ t.Fatalf("err = %v", err)
+ }
+}
+
+func TestStoreCredentialCopyRowsExist(t *testing.T) {
+ for _, k := range []string{"usage", "store_usage", "flag_write", "flag_revoke", "flag_prefix", "flag_ttl", "flag_json", "flag_app",
+ "need_one", "need_prefix", "need_ttl", "revoke_flags", "line_expires", "line_scope", "line_bucket", "line_region",
+ "line_access_key", "line_secret", "line_token", "line_revoked", "line_revoked_at", "line_revoke_note", "unreadable"} {
+ if storeCredentialText(k) == "" {
+ t.Errorf("no copy for %s", k)
+ }
+ }
+}
diff --git a/store_test.go b/store_test.go
index 7f0dd52c7..f8cce098b 100644
--- a/store_test.go
+++ b/store_test.go
@@ -830,7 +830,7 @@ func TestStoreVerbDispatchAndRefusals(t *testing.T) {
if err == nil {
t.Fatalf("carlos %v exited 0:\n%s", args, out)
}
- if !strings.Contains(out, "usage: carlos store <create|status|apply|approvals|approve|decline|grant|rotate|scan|uploads|versioning|versions|restore>") {
+ if !strings.Contains(out, "usage: carlos store <create|status|apply|approvals|approve|decline|grant|rotate|credential|scan|uploads|versioning|versions|restore>") {
t.Fatalf("carlos %v = %q, want the store usage block", args, out)
}
}