carlos / platform Public

store write credential: console doors, phase gate, boot switch

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 4091a734cbc584a17fdd64631fb18ee3ed01bb47 parent 2279b9e
13 files changed, +588 −12
  • cmd/console/main.go +11 −1
  • cmd/console/writecredentials.go +44 −0
  • cmd/console/writecredentials_test.go +32 −0
  • internal/console/apistorecredentials.go +209 −0
  • internal/console/apistorecredentials_test.go +200 −0
  • internal/console/claim_invariant_fixtures_test.go +12 −0
  • internal/console/linkedpolicy.go +2 −0
  • internal/console/routedecls.go +4 −0
  • internal/console/server.go +15 −10
  • internal/console/testdata/claim-routes.txt +2 −0
  • internal/objstore/walk.go +5 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/store_write_credential_census_test.go +51 −0
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 3cb47d247..90e8a771c 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -56,6 +56,11 @@
// versioning spec §8.1); it needs CARLOS_STORE_BACKEND, refuses
// CARLOS_STORE_ENDPOINT, and is the console's half of the region-host
// module's store_versioning grant.
+// CARLOS_STORE_WRITE_CREDENTIALS=1 lets apps mint write credentials (store
+// write credential spec, 2026-11-25); it needs CARLOS_STORE_BACKEND, refuses
+// CARLOS_STORE_ENDPOINT, and is the console's half of the region-host
+// module's store_write_credentials grant. This release is phase 1: its doors
+// refuse whatever the variable says.
// CARLOS_STORE_CONVERSION=1 alone turns on browser uploads. CARLOS_MEDIA_LIMITS
// overrides the engine's limits. See media.go.
//
@@ -416,6 +421,7 @@ func serve() {
// page's S3 requests are charged to the page that made them (and a
// background job's to the job).
rec := new(perf.Recorder)
+ logConsoleCapabilities()
storeProvisioner, storeDeployment := storeBackend(rec)
storeScanner, seedAntivirus := storeScannerFor(storeDeployment)
pdfLimits, pdfAddr, err := pdfSettings(os.Getenv)
@@ -1148,6 +1154,10 @@ func storeBackend(rec *perf.Recorder) (objstore.Provisioner, objstore.Deployment
if err != nil {
log.Fatalf("console: %v", err)
}
+ writeCredentials, err := storeWriteCredentialsOn(os.Getenv)
+ if err != nil {
+ log.Fatalf("console: %v", err)
+ }
backend := strings.TrimSpace(os.Getenv("CARLOS_STORE_BACKEND"))
if backend == "" {
return nil, objstore.Deployment{}
@@ -1190,7 +1200,7 @@ func storeBackend(rec *perf.Recorder) (objstore.Provisioner, objstore.Deployment
if err != nil {
log.Fatal(err)
}
- return p, objstore.Deployment{Backend: backend, Region: region, Endpoint: endpoint, BucketPrefix: prefix, Versioning: versioning}
+ return p, objstore.Deployment{Backend: backend, Region: region, Endpoint: endpoint, BucketPrefix: prefix, Versioning: versioning, WriteCredentials: writeCredentials}
}
// storeOperators parses CARLOS_STORE_OPERATORS (comma-separated addresses) —
diff --git a/cmd/console/writecredentials.go b/cmd/console/writecredentials.go
new file mode 100644
index 000000000..3ea87761d
--- /dev/null
+++ b/cmd/console/writecredentials.go
@@ -0,0 +1,44 @@
+package main
+
+import (
+ "errors"
+ "fmt"
+ "log"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// storeWriteCredentialsOn reads CARLOS_STORE_WRITE_CREDENTIALS (store write
+// credential spec, 2026-11-25, §8). It is the console's half of the
+// region-host module's store_write_credentials grant: set it only where that
+// grant is applied, or every mint fails at STS.
+//
+// Refused, as CARLOS_STORE_VERSIONING is, for a value that is neither on nor
+// off, without a store backend, and with CARLOS_STORE_ENDPOINT: the store
+// users are AWS IAM users even then, and an AWS STS session would mean
+// nothing to another S3 server.
+func storeWriteCredentialsOn(getenv func(string) string) (bool, error) {
+ switch v := strings.TrimSpace(getenv("CARLOS_STORE_WRITE_CREDENTIALS")); v {
+ case "", "0":
+ return false, nil
+ case "1":
+ default:
+ return false, fmt.Errorf("CARLOS_STORE_WRITE_CREDENTIALS %q is not a value this build knows: set 1 to turn it on, or leave it unset", v)
+ }
+ if strings.TrimSpace(getenv("CARLOS_STORE_BACKEND")) == "" {
+ return false, errors.New("CARLOS_STORE_WRITE_CREDENTIALS=1 is set: also set CARLOS_STORE_BACKEND (there are no object stores on this deployment to write to)")
+ }
+ if strings.TrimSpace(getenv("CARLOS_STORE_ENDPOINT")) != "" {
+ return false, errors.New("CARLOS_STORE_WRITE_CREDENTIALS=1 is set with CARLOS_STORE_ENDPOINT: write credentials need AWS S3 and STS. Unset one of them")
+ }
+ return true, nil
+}
+
+// logConsoleCapabilities names what this console build knows, at boot. It
+// is also what keeps release.ConsoleStoreWritersCapability in the binary's
+// bytes, which is how an adopting box tells this build from one that
+// predates store writers (release/consolefloor.go).
+func logConsoleCapabilities() {
+ log.Printf("console: capabilities: %s", release.ConsoleStoreWritersCapability)
+}
diff --git a/cmd/console/writecredentials_test.go b/cmd/console/writecredentials_test.go
new file mode 100644
index 000000000..4c75b336e
--- /dev/null
+++ b/cmd/console/writecredentials_test.go
@@ -0,0 +1,32 @@
+package main
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestStoreWriteCredentialsOn(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ env map[string]string
+ on bool
+ err string
+ }{
+ {"unset", map[string]string{}, false, ""},
+ {"zero", map[string]string{"CARLOS_STORE_WRITE_CREDENTIALS": "0"}, false, ""},
+ {"on", map[string]string{"CARLOS_STORE_WRITE_CREDENTIALS": "1", "CARLOS_STORE_BACKEND": "aws"}, true, ""},
+ {"typo", map[string]string{"CARLOS_STORE_WRITE_CREDENTIALS": "yes", "CARLOS_STORE_BACKEND": "aws"}, false, "not a value this build knows"},
+ {"no backend", map[string]string{"CARLOS_STORE_WRITE_CREDENTIALS": "1"}, false, "CARLOS_STORE_BACKEND"},
+ {"endpoint", map[string]string{"CARLOS_STORE_WRITE_CREDENTIALS": "1", "CARLOS_STORE_BACKEND": "aws", "CARLOS_STORE_ENDPOINT": "https://s3.example.com"}, false, "need AWS S3"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ on, err := storeWriteCredentialsOn(func(k string) string { return tc.env[k] })
+ if on != tc.on {
+ t.Fatalf("on = %v, want %v", on, tc.on)
+ }
+ if tc.err == "" && err != nil || tc.err != "" && (err == nil || !strings.Contains(err.Error(), tc.err)) {
+ t.Fatalf("err = %v, want one naming %q", err, tc.err)
+ }
+ })
+ }
+}
diff --git a/internal/console/apistorecredentials.go b/internal/console/apistorecredentials.go
new file mode 100644
index 000000000..73c25029e
--- /dev/null
+++ b/internal/console/apistorecredentials.go
@@ -0,0 +1,209 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "log"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/carlosframework/platform/internal/objstore"
+)
+
+// Write credentials (spec 2026-11-25-store-write-credential-design.md):
+// `carlos store credential --write` and `--revoke`. A temporary credential
+// that can only upload under one prefix of the app's own store, for the app
+// to hand to a third party such as a LiveKit recorder. The walk is
+// objstore.MintWriteCredentialIn; this file is the two doors.
+//
+// Service credentials reach both (Paul, 2026-11-25: the app's backend
+// starts each recording), so do members and Admin. Both take the account
+// lock and then the store walk lock, as the uploads door does: the walks
+// write the store's writer policy, and that lock discipline is what spec
+// §2.3 rests on.
+
+// writeCredentialsReleasedPhase is the rollout phase this build is (spec
+// §10). Phase 1 knows store writers everywhere they live (grant, teardown,
+// purge, storage-limit convergence) but cannot make one: both doors refuse.
+// Phase 2, a later release, is this constant set to 2, once every console a
+// rollback could reach is phase 1 or later.
+const writeCredentialsReleasedPhase = 1
+
+// writeCredentialsBodyLimit caps the mint body: a 200-byte prefix and two
+// small fields fit many times over.
+const writeCredentialsBodyLimit = 4 << 10
+
+// The codes the doors answer.
+const (
+ wcCodeNotConfigured = "write_credentials_not_configured"
+ wcCodeNotReleased = "write_credentials_not_released"
+ wcCodeUnsupported = "write_credentials_unsupported"
+ wcCodeNoStore = "no_store"
+ wcCodeBadAccess = "bad_access"
+ wcCodeBadPrefix = "bad_prefix"
+ wcCodeBadTTL = "bad_ttl"
+ wcCodeSettling = "revocation_settling"
+ wcCodeNoneIssued = "no_write_credentials"
+)
+
+// writeCredentialsCopy is the doors' refusals by code. New copy, pending
+// the Luna pass (docs/superpowers/notes/copy-luna-brief-store-write-credential.md).
+var writeCredentialsCopy = map[string]string{
+ wcCodeNotConfigured: "write credentials are not turned on for this deployment (CARLOS_STORE_WRITE_CREDENTIALS)",
+ wcCodeNotReleased: "this console release cannot issue write credentials yet; a later release turns them on",
+ wcCodeUnsupported: "this store is on an S3-compatible server, and write credentials need AWS S3",
+ wcCodeNoStore: "this app has no store yet; create one with carlos store create",
+ wcCodeBadAccess: "the only kind of credential is write",
+ wcCodeBadTTL: "the lifetime must be from 15 minutes to 24 hours",
+ wcCodeSettling: "write credentials were just revoked; try again in a minute",
+ wcCodeNoneIssued: "this store has not issued any write credentials, so there is nothing to revoke",
+}
+
+// writeCredentialBody is the mint door's body, decoded strictly.
+type writeCredentialBody struct {
+ Access string `json:"access"`
+ Prefix string `json:"prefix"`
+ TTLSeconds int64 `json:"ttl_seconds"`
+}
+
+// writeCredentialAnswer is the mint door's answer. The first five names are
+// the ones LiveKit's S3Upload takes.
+type writeCredentialAnswer 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"`
+}
+
+// writeCredentialsGates are both doors' gates after apiAccountApp, in
+// order: a host-claim console, the switch, the phase, then the store walk
+// gates every store door shares.
+func (s *Server) writeCredentialsGates(w http.ResponseWriter, r *http.Request) bool {
+ if s.cfg.HostClaim {
+ mediaRefuse(w, http.StatusServiceUnavailable, "claims_console", mediaText("media.claims_console"))
+ return false
+ }
+ if !s.cfg.StoreDeployment.WriteCredentials {
+ jsonErrorCode(w, http.StatusServiceUnavailable, wcCodeNotConfigured, writeCredentialsCopy[wcCodeNotConfigured])
+ return false
+ }
+ if s.writeCredentialsPhase < 2 {
+ jsonErrorCode(w, http.StatusServiceUnavailable, wcCodeNotReleased, writeCredentialsCopy[wcCodeNotReleased])
+ return false
+ }
+ p, _ := principalFrom(r.Context())
+ return s.storeWalkGates(w, p)
+}
+
+// writeCredentialsRefusal answers the walk's refusals, and false for an
+// error that is not one.
+func writeCredentialsRefusal(w http.ResponseWriter, err error) bool {
+ var settling *objstore.RevocationSettlingError
+ switch {
+ case errors.Is(err, objstore.ErrNotProvisioned):
+ jsonErrorCode(w, http.StatusConflict, wcCodeNoStore, writeCredentialsCopy[wcCodeNoStore])
+ case errors.Is(err, objstore.ErrWriteCredentialsUnsupported):
+ jsonErrorCode(w, http.StatusConflict, wcCodeUnsupported, writeCredentialsCopy[wcCodeUnsupported])
+ case errors.Is(err, objstore.ErrNoWriteCredentials):
+ jsonErrorCode(w, http.StatusConflict, wcCodeNoneIssued, writeCredentialsCopy[wcCodeNoneIssued])
+ case errors.As(err, &settling):
+ secs := int(time.Until(settling.Until).Seconds()) + 1
+ if secs < 1 {
+ secs = 1
+ }
+ w.Header().Set("Retry-After", strconv.Itoa(secs))
+ jsonErrorCode(w, http.StatusConflict, wcCodeSettling, writeCredentialsCopy[wcCodeSettling])
+ default:
+ return false
+ }
+ return true
+}
+
+// handleAPIStoreCredentials is POST /api/cli/apps/{account}/{app}/store/credentials:
+// mint a write credential. The secret and token go into the answer and
+// nowhere else: not the audit row, not a log line.
+func (s *Server) handleAPIStoreCredentials(w http.ResponseWriter, r *http.Request) {
+ addr, acct, app, ok := s.apiAccountApp(w, r)
+ if !ok || !s.writeCredentialsGates(w, r) {
+ return
+ }
+ env, ok := s.storeEnvParam(w, r)
+ if !ok {
+ return
+ }
+ var body writeCredentialBody
+ if !readJSONStrictLimit(w, r, &body, writeCredentialsBodyLimit) {
+ return
+ }
+ if body.Access != "write" {
+ jsonErrorCode(w, http.StatusBadRequest, wcCodeBadAccess, writeCredentialsCopy[wcCodeBadAccess])
+ return
+ }
+ if err := objstore.ValidWritePrefix(body.Prefix); err != nil {
+ jsonErrorCode(w, http.StatusBadRequest, wcCodeBadPrefix, err.Error())
+ return
+ }
+ ttl := time.Duration(body.TTLSeconds) * time.Second
+ if body.TTLSeconds <= 0 || body.TTLSeconds > int64(objstore.WriteCredentialMaxTTL/time.Second) || objstore.ValidWriteTTL(ttl) != nil {
+ jsonErrorCode(w, http.StatusBadRequest, wcCodeBadTTL, writeCredentialsCopy[wcCodeBadTTL])
+ return
+ }
+ // The grant timeout: a mint waits up to about 30 seconds for a new key
+ // to reach STS.
+ ctx, cancel := context.WithTimeout(r.Context(), storeGrantTimeout)
+ defer cancel()
+ defer s.lockAccount(acct.Sqid)()
+ defer s.storeWalks.lock(acct.Sqid, app, env)()
+ cred, err := claimAppCall(s, ctx, acct, app, "store-credential-mint", func(ctx context.Context) (*objstore.WriteCredential, error) {
+ return objstore.MintWriteCredentialIn(ctx, s.cfg.Releases, s.cfg.StoreProvisioner, acct.Sqid, app, env, addr, body.Prefix, ttl, time.Now())
+ })
+ if err != nil {
+ if !writeCredentialsRefusal(w, err) {
+ log.Printf("console: api store credential mint %s/%s: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusBadGateway, "could not issue the write credential; nothing was handed out. Try again")
+ }
+ return
+ }
+ s.audit(acct, app, addr, "store-credential-mint",
+ "issued a write credential for "+body.Prefix+" until "+cred.Expires.UTC().Format(time.RFC3339)+storeEnvSuffix(env)+" (cli)")
+ writeJSON(w, http.StatusOK, writeCredentialAnswer{
+ AccessKey: cred.AccessKeyID, Secret: cred.SecretAccessKey, SessionToken: cred.SessionToken,
+ Region: cred.Region, Bucket: cred.Bucket, Prefix: cred.Prefix, ExpiresAt: cred.Expires.UTC(),
+ })
+}
+
+// handleAPIStoreCredentialsRevoke is POST
+// /api/cli/apps/{account}/{app}/store/credentials/revoke: every write
+// credential the store issued until now stops working once IAM's change
+// has propagated. No body.
+func (s *Server) handleAPIStoreCredentialsRevoke(w http.ResponseWriter, r *http.Request) {
+ addr, acct, app, ok := s.apiAccountApp(w, r)
+ if !ok || !s.writeCredentialsGates(w, r) {
+ return
+ }
+ env, ok := s.storeEnvParam(w, r)
+ if !ok {
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), storeRotateTimeout)
+ defer cancel()
+ defer s.lockAccount(acct.Sqid)()
+ defer s.storeWalks.lock(acct.Sqid, app, env)()
+ rb, err := claimAppCall(s, ctx, acct, app, "store-credential-revoke", func(ctx context.Context) (time.Time, error) {
+ return objstore.RevokeWriteCredentialsIn(ctx, s.cfg.Releases, s.cfg.StoreProvisioner, acct.Sqid, app, env, time.Now())
+ })
+ if err != nil {
+ if !writeCredentialsRefusal(w, err) {
+ log.Printf("console: api store credential revoke %s/%s: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusBadGateway, "could not revoke the write credentials. Try again")
+ }
+ return
+ }
+ s.audit(acct, app, addr, "store-credential-revoke",
+ "revoked every write credential issued before "+rb.UTC().Format(time.RFC3339)+storeEnvSuffix(env)+" (cli)")
+ writeJSON(w, http.StatusOK, map[string]time.Time{"revoked_before": rb.UTC()})
+}
diff --git a/internal/console/apistorecredentials_test.go b/internal/console/apistorecredentials_test.go
new file mode 100644
index 000000000..35b528e03
--- /dev/null
+++ b/internal/console/apistorecredentials_test.go
@@ -0,0 +1,200 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// credentialsFixture is a console whose app titogo has a granted store, with
+// write credentials switched on and the doors in phase 2 unless a test says
+// otherwise.
+type credentialsFixture struct {
+ *consoleFixture
+ t *testing.T
+ prov *objstore.MemProvisioner
+ token string
+}
+
+func newCredentials(t *testing.T, code string) *credentialsFixture {
+ t.Helper()
+ fx, prov, _, token := grantedMediaStore(t, code)
+ fx.srv.cfg.StoreDeployment.WriteCredentials = true
+ fx.srv.writeCredentialsPhase = 2
+ return &credentialsFixture{consoleFixture: fx, t: t, prov: prov, token: token}
+}
+
+type credentialsReply struct {
+ status int
+ raw string
+ header http.Header
+ ans writeCredentialAnswer
+ err struct{ Error, Code string }
+}
+
+func (c *credentialsFixture) post(path, body string) credentialsReply {
+ c.t.Helper()
+ status, hdr, raw := rawReq(c.t, http.MethodPost, storeURL(c.consoleFixture, "titogo")+path, c.token, body)
+ r := credentialsReply{status: status, raw: raw, header: hdr}
+ if status == http.StatusOK && path == "/credentials" {
+ if err := json.Unmarshal([]byte(raw), &r.ans); err != nil {
+ c.t.Fatalf("answer %q: %v", raw, err)
+ }
+ } else {
+ _ = json.Unmarshal([]byte(raw), &r.err)
+ }
+ return r
+}
+
+func (c *credentialsFixture) mint(prefix string, ttl int) credentialsReply {
+ c.t.Helper()
+ b, _ := json.Marshal(map[string]any{"access": "write", "prefix": prefix, "ttl_seconds": ttl})
+ return c.post("/credentials", string(b))
+}
+
+func TestStoreCredentialsMint(t *testing.T) {
+ c := newCredentials(t, "code-wc-mint")
+ r := c.mint("recordings/", 4*3600)
+ if r.status != http.StatusOK {
+ t.Fatalf("mint: %d %s", r.status, r.raw)
+ }
+ bucket := mediaMintedName(c.consoleFixture)
+ a := r.ans
+ if a.AccessKey == "" || a.Secret == "" || a.SessionToken == "" || a.Bucket != bucket || a.Region != "eu-west-1" ||
+ a.Prefix != "recordings/" || a.ExpiresAt.IsZero() {
+ t.Fatalf("answer = %+v", a)
+ }
+ if got := r.header.Get("Cache-Control"); got != "no-store" {
+ t.Fatalf("Cache-Control = %q", got)
+ }
+ // The field names LiveKit's S3Upload takes.
+ for _, k := range []string{`"access_key"`, `"secret"`, `"session_token"`, `"region"`, `"bucket"`, `"prefix"`, `"expires_at"`} {
+ if !strings.Contains(r.raw, k) {
+ t.Fatalf("answer has no %s: %s", k, r.raw)
+ }
+ }
+ if len(c.prov.Sessions) != 1 || c.prov.Sessions[0].User != objstore.WriterName(objstore.UserNameIn(c.sqid, "titogo", "")) {
+ t.Fatalf("sessions = %+v", c.prov.Sessions)
+ }
+ // The audit row names the scope and never the secret.
+ auditedBy(t, c.consoleFixture, "titogo", "store-credential-mint", "alice@keymail.dev", "recordings/")
+ events, err := c.st.Events(OpsAccountID, "titogo", 20)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, e := range events {
+ if strings.Contains(e.Detail, a.Secret) || strings.Contains(e.Detail, a.SessionToken) {
+ t.Fatalf("audit row carries a credential: %+v", e)
+ }
+ }
+}
+
+func TestStoreCredentialsRevoke(t *testing.T) {
+ c := newCredentials(t, "code-wc-revoke")
+ if r := c.post("/credentials/revoke", ""); r.status != http.StatusConflict || r.err.Code != "no_write_credentials" {
+ t.Fatalf("revoke before a mint: %d %s", r.status, r.raw)
+ }
+ if r := c.mint("recordings/", 3600); r.status != http.StatusOK {
+ t.Fatalf("mint: %d %s", r.status, r.raw)
+ }
+ r := c.post("/credentials/revoke", "")
+ if r.status != http.StatusOK || !strings.Contains(r.raw, `"revoked_before"`) {
+ t.Fatalf("revoke: %d %s", r.status, r.raw)
+ }
+ // A mint straight after is refused while the revocation settles.
+ if r := c.mint("recordings/", 3600); r.status != http.StatusConflict || r.err.Code != "revocation_settling" || r.header.Get("Retry-After") == "" {
+ t.Fatalf("mint after revoke: %d %s %v", r.status, r.raw, r.header)
+ }
+}
+
+func TestStoreCredentialsRefusals(t *testing.T) {
+ t.Run("phase 1", func(t *testing.T) {
+ c := newCredentials(t, "code-wc-phase")
+ c.srv.writeCredentialsPhase = writeCredentialsReleasedPhase
+ for _, path := range []string{"/credentials", "/credentials/revoke"} {
+ if r := c.post(path, `{"access":"write","prefix":"recordings/","ttl_seconds":3600}`); r.status != http.StatusServiceUnavailable || r.err.Code != "write_credentials_not_released" {
+ t.Fatalf("%s in phase 1: %d %s", path, r.status, r.raw)
+ }
+ }
+ if len(c.prov.Sessions) != 0 || c.prov.WriterWrites != 0 {
+ t.Fatal("a phase 1 console minted")
+ }
+ if _, _, err := c.srv.cfg.Releases.Get(context.Background(), release.ConsoleStoreWritersFloorKey); err == nil {
+ t.Fatal("a phase 1 console wrote the console floor")
+ }
+ })
+ t.Run("not configured", func(t *testing.T) {
+ c := newCredentials(t, "code-wc-off")
+ c.srv.cfg.StoreDeployment.WriteCredentials = false
+ if r := c.mint("recordings/", 3600); r.status != http.StatusServiceUnavailable || r.err.Code != "write_credentials_not_configured" {
+ t.Fatalf("mint switched off: %d %s", r.status, r.raw)
+ }
+ })
+ t.Run("body", func(t *testing.T) {
+ c := newCredentials(t, "code-wc-body")
+ for _, tc := range []struct{ body, code string }{
+ {`{"access":"read","prefix":"recordings/","ttl_seconds":3600}`, "bad_access"},
+ {`{"access":"write","prefix":"derived/","ttl_seconds":3600}`, "bad_prefix"},
+ {`{"access":"write","prefix":"rec*/","ttl_seconds":3600}`, "bad_prefix"},
+ {`{"access":"write","prefix":"recordings/","ttl_seconds":60}`, "bad_ttl"},
+ {`{"access":"write","prefix":"recordings/","ttl_seconds":172800}`, "bad_ttl"},
+ } {
+ if r := c.post("/credentials", tc.body); r.status != http.StatusBadRequest || r.err.Code != tc.code {
+ t.Fatalf("%s: %d %s, want %s", tc.body, r.status, r.raw, tc.code)
+ }
+ }
+ if r := c.post("/credentials", `{"access":"write","prefix":"recordings/","ttl_seconds":3600,"extra":1}`); r.status != http.StatusBadRequest {
+ t.Fatalf("unknown field: %d %s", r.status, r.raw)
+ }
+ if len(c.prov.Sessions) != 0 {
+ t.Fatal("a refused body minted")
+ }
+ })
+ t.Run("no store", func(t *testing.T) {
+ fx, prov, _, token := mediaStoreFixture(t, "code-wc-nostore")
+ fx.srv.cfg.StoreDeployment.WriteCredentials = true
+ fx.srv.writeCredentialsPhase = 2
+ c := &credentialsFixture{consoleFixture: fx, t: t, prov: prov, token: token}
+ if r := c.mint("recordings/", 3600); r.status != http.StatusConflict || r.err.Code != "no_store" {
+ t.Fatalf("mint with no store: %d %s", r.status, r.raw)
+ }
+ })
+ t.Run("endpoint store", func(t *testing.T) {
+ c := newCredentials(t, "code-wc-endpoint")
+ ctx := context.Background()
+ rec, etag, _ := objstore.GetIn(ctx, c.srv.cfg.Releases, c.sqid, "titogo", "")
+ rec.Provisioned.Endpoint = "https://s3.example.com"
+ if _, err := objstore.PutIn(ctx, c.srv.cfg.Releases, c.sqid, "titogo", "", rec, etag); err != nil {
+ t.Fatal(err)
+ }
+ if r := c.mint("recordings/", 3600); r.status != http.StatusConflict || r.err.Code != "write_credentials_unsupported" {
+ t.Fatalf("mint on an S3-compatible store: %d %s", r.status, r.raw)
+ }
+ })
+ t.Run("host claim", func(t *testing.T) {
+ c := newCredentials(t, "code-wc-claim")
+ c.srv.cfg.HostClaim = true
+ if r := c.mint("recordings/", 3600); r.status != http.StatusServiceUnavailable || r.err.Code != "claims_console" {
+ t.Fatalf("mint on a host-claim console: %d %s", r.status, r.raw)
+ }
+ })
+}
+
+// The secret and token never reach the console's log, whatever happens.
+func TestStoreCredentialsNeverLogTheSecret(t *testing.T) {
+ c := newCredentials(t, "code-wc-log")
+ logs := captureLog(t)
+ r := c.mint("recordings/", 3600)
+ if r.status != http.StatusOK {
+ t.Fatalf("mint: %d %s", r.status, r.raw)
+ }
+ _ = c.post("/credentials/revoke", "")
+ if out := logs.String(); strings.Contains(out, r.ans.Secret) || strings.Contains(out, r.ans.SessionToken) {
+ t.Fatalf("console log carries a credential: %s", out)
+ }
+}
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 3d84d36a5..3d20ac4b9 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -2342,6 +2342,18 @@ var claimFixtures = map[string]claimFixture{
do: claimRefusedAPI(http.MethodGet, "/api/cli/apps/bab/shop/store/uploads", ""),
status: http.StatusServiceUnavailable, msg: mediaText("media.claims_console"),
}},
+ // Write credentials: both doors refuse on a host-claim console after
+ // apiAccountApp, before the store record, the writer or STS.
+ "route POST /api/cli/apps/{account}/{app}/store/credentials": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/shop"), setup: claimEnrollShop,
+ do: claimRefusedAPI(http.MethodPost, "/api/cli/apps/bab/shop/store/credentials", `{"access":"write","prefix":"recordings/","ttl_seconds":3600}`),
+ status: http.StatusServiceUnavailable, msg: mediaText("media.claims_console"),
+ }},
+ "route POST /api/cli/apps/{account}/{app}/store/credentials/revoke": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/shop"), setup: claimEnrollShop,
+ do: claimRefusedAPI(http.MethodPost, "/api/cli/apps/bab/shop/store/credentials/revoke", ""),
+ status: http.StatusServiceUnavailable, msg: mediaText("media.claims_console"),
+ }},
// Store versioning's four doors refuse on a host-claim console
// after apiAccountApp, before the store record or the bucket.
"route POST /api/cli/apps/{account}/{app}/store/versioning": {refused: &claimRefusalFixture{
diff --git a/internal/console/linkedpolicy.go b/internal/console/linkedpolicy.go
index 55c51f620..dc80548c4 100644
--- a/internal/console/linkedpolicy.go
+++ b/internal/console/linkedpolicy.go
@@ -273,6 +273,8 @@ var linkedPolicies = map[string]linkedPolicy{
"GET /api/cli/apps/{account}/{app}/store/scan/object": linkedRefuse,
"POST /api/cli/apps/{account}/{app}/store/uploads": linkedRefuse,
"GET /api/cli/apps/{account}/{app}/store/uploads": linkedRefuse,
+ "POST /api/cli/apps/{account}/{app}/store/credentials": linkedRefuse,
+ "POST /api/cli/apps/{account}/{app}/store/credentials/revoke": linkedRefuse,
"POST /api/cli/apps/{account}/{app}/store/versioning": linkedRefuse,
"GET /api/cli/apps/{account}/{app}/store/versioning": linkedRefuse,
"GET /api/cli/apps/{account}/{app}/store/versions": linkedRefuse,
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index ddc6da8cc..b9484eb96 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -1098,6 +1098,10 @@ var routeDecls = []routeDecl{
// Admin, as every member store verb; refused on a host-claim console.
{Pattern: "POST /api/cli/apps/{account}/{app}/store/uploads", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIStoreUploadsSet},
{Pattern: "GET /api/cli/apps/{account}/{app}/store/uploads", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIStoreUploadsGet},
+ // Write credentials (apistorecredentials.go): Service as well, because
+ // an app's backend mints one per recording (Paul, 2026-11-25).
+ {Pattern: "POST /api/cli/apps/{account}/{app}/store/credentials", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Service), Handler: (*Server).handleAPIStoreCredentials},
+ {Pattern: "POST /api/cli/apps/{account}/{app}/store/credentials/revoke", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Service), Handler: (*Server).handleAPIStoreCredentialsRevoke},
// Store versioning (apistoreversioning.go, store versioning spec §10.2).
// Turning it on is a person's act: the zero Set, so an app's own Admin
// service credential cannot choose its store's history policy. There is
diff --git a/internal/console/server.go b/internal/console/server.go
index b011e6e50..b608503e0 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1290,6 +1290,10 @@ type Server struct {
// door serialises these verbs per app" (objstore/walk.go:560) — and until
// #381 nothing did.
storeWalks *storeWalkLocks
+ // writeCredentialsPhase is the write-credential rollout phase this build
+ // is (apistorecredentials.go): writeCredentialsReleasedPhase in
+ // production, which a test may raise to open the doors.
+ writeCredentialsPhase int
// doorPublish is the door-key publication lock per app, keyed
// "<sqid>/<app>" (apidoorkeys.go): one publisher per app at a time, so a
// renewal can never land an older key set after a revoke. Built lazily
@@ -2046,16 +2050,17 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// slow-loris uploads against a stolen or shared token can't pile up
// goroutines and buffers without bound.
shipSem: make(chan struct{}, 2), releaseReads: make(chan struct{}, releaseReadsMax),
- delegationZone: normalizeDelegationZone(cfg.DelegationZone),
- steeringHost: normalizeSteeringHost(cfg.SteeringHost),
- lookupCNAME: net.DefaultResolver.LookupCNAME,
- lookupTXT: cfg.LookupTXT,
- storeWalks: newStoreWalkLocks(),
- consoleMail: cfg.ConsoleMail,
- consoleNameCfg: cfg.ConsoleName,
- challengeSem: make(chan struct{}, challengeSendSlots),
- inviteTimeout: 20 * time.Second,
- inviteKeymailShare: 12 * time.Second,
+ delegationZone: normalizeDelegationZone(cfg.DelegationZone),
+ steeringHost: normalizeSteeringHost(cfg.SteeringHost),
+ lookupCNAME: net.DefaultResolver.LookupCNAME,
+ lookupTXT: cfg.LookupTXT,
+ storeWalks: newStoreWalkLocks(),
+ writeCredentialsPhase: writeCredentialsReleasedPhase,
+ consoleMail: cfg.ConsoleMail,
+ consoleNameCfg: cfg.ConsoleName,
+ challengeSem: make(chan struct{}, challengeSendSlots),
+ inviteTimeout: 20 * time.Second,
+ inviteKeymailShare: 12 * time.Second,
// This process's identity in the relay writer lease. Random rather
// than derived from the host: two consoles on one box during a
// deploy overlap are two writers, and they must be able to tell
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 27e1bfa9d..00f57b74f 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -358,6 +358,8 @@ route POST /api/cli/apps/{account}/{app}/store/scan/object
route POST /api/cli/apps/{account}/{app}/store/scan/revoke
route POST /api/cli/apps/{account}/{app}/store/scan/sweep
route POST /api/cli/apps/{account}/{app}/store/uploads
+route POST /api/cli/apps/{account}/{app}/store/credentials
+route POST /api/cli/apps/{account}/{app}/store/credentials/revoke
route POST /api/cli/apps/{account}/{app}/store/restore
route POST /api/cli/apps/{account}/{app}/store/versioning
route POST /api/cli/apps/{account}/{app}/ttl
diff --git a/internal/objstore/walk.go b/internal/objstore/walk.go
index 03ae43593..5a644a16d 100644
--- a/internal/objstore/walk.go
+++ b/internal/objstore/walk.go
@@ -61,6 +61,11 @@ type Deployment struct {
// re-walk of a versioned store must work whatever this says now. It
// gates only the console's doors that turn versioning on.
Versioning bool
+ // WriteCredentials is CARLOS_STORE_WRITE_CREDENTIALS=1: the deployment
+ // applied the region-host module's store_write_credentials grant, so its
+ // console may mint write credentials (writecred.go). Like Versioning,
+ // the walks do not read it; it gates only the console's doors.
+ WriteCredentials bool
}
// MintedBucket is the name a store gets when the deployment mints one — the
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index f62e55e66..f9d5a22dc 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := releaseCopyWriteCensusInventory()
+ inventory := storeWriteCredentialWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/store_write_credential_census_test.go b/internal/provision/store_write_credential_census_test.go
new file mode 100644
index 000000000..414fa63c0
--- /dev/null
+++ b/internal/provision/store_write_credential_census_test.go
@@ -0,0 +1,51 @@
+package provision
+
+// storeWriteCredentialWriteCensusInventory is the record-write census for
+// branch store-write-credential (spec
+// 2026-11-25-store-write-credential-design), layered on
+// releaseCopyWriteCensusInventory. Reviewed by the branch author against
+// the source. No record write is added, moved or reclassified; two key-site
+// tables are re-pinned:
+//
+// - var routeDecls (console): two new declarations, POST
+// .../store/credentials (handleAPIStoreCredentials) and POST
+// .../store/credentials/revoke (handleAPIStoreCredentialsRevoke), in
+// apistorecredentials.go, kindCLI with Service (and so Admin). They
+// write the store's write-credentials state object and the console
+// floor in the deployment bucket, and IAM; neither writes an instance
+// or sidecar record. The instances and sidecars literals are
+// unchanged: still key-site.
+// - var linkedPolicies (console): the same two routes classified
+// linkedRefuse, as the other store doors are. Literals unchanged.
+//
+// Two new nonrecord write sites, neither a provision record:
+//
+// - objstore claimRawPutWriteCredentialsIn: the store's write-credentials
+// state object, apps/<acct>/<app>/write-credentials[/<env>].json.
+// - release PutConsoleStoreWritersFloor: the console floor,
+// control/console-floors/store-writers.json, create-only.
+func storeWriteCredentialWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), releaseCopyWriteCensusInventory()...)
+ repins := []censusEntry{
+ {"internal/console/routedecls.go", "var routeDecls", "key-site", "lit:instances,lit:sidecars", "3c9a2756566792737ebb3bbd1bf79f208d554dc5ededb0d17edf886b73fbad07"},
+ {"internal/console/linkedpolicy.go", "var linkedPolicies", "key-site", "lit:instances,lit:sidecars", "47cfdf2c276fefbcd1286fb107f2597d21154a58acc41b64cf48d79850d8e03a"},
+ }
+ for _, r := range repins {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ if e.Class != r.Class || e.Kinds != r.Kinds {
+ panic("store-write-credential re-pin changes the class or kinds of " + r.File + ":" + r.Unit)
+ }
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("store-write-credential re-pin of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return append(entries,
+ censusEntry{"internal/objstore/writecred.go", "claimRawPutWriteCredentialsIn", "nonrecord", "sel:Put", "e307f507e240180f59f25449017f1a5e18ea3a2ede486ea4dc0da44ffa738f57"},
+ censusEntry{"internal/release/consolefloor.go", "PutConsoleStoreWritersFloor", "nonrecord", "sel:Put", "0d012135862cfa72e00834958bc3372b0077726486a6249849b44f27a905150a"},
+ )
+}