carlos / platform Public

console: short-lived per-customer credentials minted by a platform

POST /api/cli/platform/{account}/customers/{customer}/credentials mints a
cli_tokens row of the new kind platform (cliKindPlatform) on one customer
account: role publish (no app), or deploy on one of its apps with rungs;
1 hour by default, 1 minute to 24 hours. Every refusal (body, role, app,
lifetime, customer) comes before pending mints are finished, and a held
promise does not stop the mint. Inside the insert transaction the mint
re-checks the customer's link under the admitted grant generation
(platformLinkLive) and the minter's own authority; either gone is 403
door.revoked with nothing written.

The resolver reads a kind platform row only while it is unexpired (0 is
refused), well formed, and platformLinkLive holds, so a revoked grant, a
re-grant, a deleted platform or a deleted or unlinked customer ends it on
the next request whatever its revoked_at says. Its audit actor is
platform:<sqid>/<name>; the platform credential keeps service:. The
personal token list leaves these rows out.

AGENTS.md now states "a credential never mints a credential" and this one
exception with its limits; the four code comments that state the rule
point there. The claim census covers the new door, and a gated-store test
mints a deploy credential through the store and sees the revoke sweep it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2011092a30328d7e421a8c598e51cb0715999bd0 parent 2d85f5a
16 files changed, +1,241 −23
  • AGENTS.md +13 −0
  • internal/console/apicli.go +11 −1
  • internal/console/apiplatformcredentials.go +166 −0
  • internal/console/apiplatformcustomers_test.go +2 −1
  • internal/console/authstore.go +17 −8
  • internal/console/claim_invariant_fixtures_test.go +10 −0
  • internal/console/claim_invariant_probes_nonapp_test.go +11 −0
  • internal/console/platform_copy.go +5 −0
  • internal/console/platform_credentials.go +281 −0
  • internal/console/platform_credentials_test.go +666 −0
  • internal/console/platform_seams.go +5 −0
  • internal/console/platform_store.go +2 −2
  • internal/console/routedecls.go +16 −2
  • internal/console/svcprincipal.go +25 −8
  • internal/console/svcroutes_test.go +10 −1
  • internal/console/testdata/claim-routes.txt +1 −0
diff --git a/AGENTS.md b/AGENTS.md
index 38fcc3754..e94903990 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -590,6 +590,19 @@ unchanged.
comparison spelled `"ETag"` matches nothing. Ordering is load-bearing too:
recorder ABOVE the compressor (cache stores identity), usage counter BELOW it
(tenants are billed for wire bytes), wrap site AFTER the upgrade branch.
+- **A credential never mints a credential, with one exception.** The
+ services, instance-token, door-key and email-credential doors are closed to
+ every role (`closedDoors`, `mintDoors` in
+ `internal/console/svcroutes_test.go`), so no credential can mint, rotate or
+ revoke one. The one exception is the platform door
+ `POST /api/cli/platform/{account}/customers/{customer}/credentials`
+ (platform accounts spec §6.2, accepted by Paul 2026-11-19). Its limits:
+ only the `platform` role reaches it; what it mints is bound to one customer
+ account linked to that platform; it lives at most 24 hours; the minted
+ credential (role Publish or Deploy, kind `platform`) can never reach any
+ mint door; and it is checked against the platform's grant generation on
+ every request, so revoking the grant ends it. Widening any of these needs
+ Paul.
- **Console security gates are ordered**: session → CSRF → owner (byte-identical
404) → `requireFreshAuth` LAST. A non-member must never get a redirect that
confirms an account exists.
diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index 1c5398f8a..034a81841 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -123,6 +123,14 @@ func auditActor(p Principal, acct *Account) string {
// A linked deployment, never the person who approved the link.
return "link:" + acct.Sqid + "/" + p.LinkID
}
+ if p.Platform != "" && p.Role != svcrole.Platform {
+ // A per-customer credential (kind platform): its platform and the
+ // handle of whoever minted it, so a customer's history names the
+ // platform that acted (platform accounts spec §6.2). The platform
+ // credential itself carries a platform too, and stays service:
+ // below, on its own account.
+ return "platform:" + p.Platform + "/" + p.Name
+ }
if p.Name == "" {
// A legacy kind='app' row has no name; keep the string the audit
// trail has always written for it, so old rows and new rows about
@@ -339,7 +347,9 @@ func (s *Server) apiAccount(w http.ResponseWriter, r *http.Request) (string, *Ac
// a service whether the path it named is its own.
//
// It is the INNER of two walls at the doors whose subject is a human act:
-// minting a credential (a credential may never mint a credential) and
+// minting a credential (a credential may never mint a credential; the one
+// exception and its limits are in AGENTS.md, "Rules this repo has paid
+// for") and
// enabling instances (the manifest is standing policy about what may be
// brought into existence). Both are registered with the zero Set, so no role
// reaches either — and THAT registration is the load-bearing wall. The role
diff --git a/internal/console/apiplatformcredentials.go b/internal/console/apiplatformcredentials.go
new file mode 100644
index 000000000..697321ff9
--- /dev/null
+++ b/internal/console/apiplatformcredentials.go
@@ -0,0 +1,166 @@
+package console
+
+// The per-customer credential door (platform accounts spec §6.2):
+// POST /api/cli/platform/{account}/customers/{customer}/credentials mints a
+// short-lived credential bound to one customer account of the platform.
+// The store side, and why this credential mint reached by a credential is
+// the one allowed, is platform_credentials.go.
+
+import (
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// auditPlatformCustomerCredential is the customer account's audit action for
+// a per-customer credential mint, with app accountAuditSubject.
+const auditPlatformCustomerCredential = "platform-customer-credential"
+
+type platformCredentialMintRequest struct {
+ Role string `json:"role"`
+ App string `json:"app"`
+ Rungs []string `json:"rungs"`
+ TTLSeconds int64 `json:"ttl_seconds"`
+}
+
+// platformCredentialReply is the mint's 201. Account and Name are the
+// customer account's (pre-flight C5: the CLI's Minted line names it).
+type platformCredentialReply struct {
+ Token string `json:"token"`
+ Account string `json:"account"`
+ Name string `json:"name"`
+ Role string `json:"role"`
+ App string `json:"app"`
+ Rungs []string `json:"rungs"`
+ ExpiresAt time.Time `json:"expires_at"`
+}
+
+// handlePlatformCredentialMint answers POST .../customers/{customer}/credentials.
+//
+// A refused mint writes nothing (Astra r1-4, ruling B): every refusal comes
+// before the platform's pending mints are finished. In order: authorization
+// (platformAuthorize), the customer (the stdlib 404), the write budget
+// (429 door.rate), the body's shape, the role, app and rungs (400 cred.role,
+// or the services door's rung refusals), the lifetime (400 cred.ttl), and a
+// Deploy credential's app, which the customer must hold (the stdlib 404).
+// Then the gate's second half finishes pending mints (a held one is passed
+// over, Task 8 ruling C), and the mint runs under the generation the caller
+// was admitted with. The mint re-checks the authority inside its insert
+// transaction: a revoke, a re-grant, or the minter's own credential revoked
+// meanwhile is 403 door.revoked with nothing written. A store failure is
+// 500 cred.failed (pre-flight C10). The customer's history records the mint
+// (audit.credential).
+func (s *Server) handlePlatformCredentialMint(w http.ResponseWriter, r *http.Request) {
+ c, ok := s.platformAuthorize(w, r, "cred.failed")
+ if !ok {
+ return
+ }
+ lc, cust, ok := s.platformCustomer(w, r, c)
+ if !ok {
+ return
+ }
+ if !s.allowWrite(c.P, time.Now()) {
+ jsonError(w, http.StatusTooManyRequests, platformCopy["door.rate"])
+ return
+ }
+ var req platformCredentialMintRequest
+ if !readJSONStrictLimit(w, r, &req, 8<<10) {
+ return
+ }
+ role, _ := svcrole.Parse(req.Role) // an unknown role is the zero Role, which the shape refuses
+ app := strings.TrimSpace(req.App)
+ ttl, ok := platformCredentialTTL(req.TTLSeconds)
+ if !ok {
+ jsonError(w, http.StatusBadRequest, platformCopy["cred.ttl"])
+ return
+ }
+ rungs, ttl, err := platformCredentialShape(role, app, req.Rungs, ttl)
+ if err != nil {
+ s.platformCredentialRefused(w, r, c, err)
+ return
+ }
+ ctx := r.Context()
+ if app != "" {
+ found, err := s.store.HasAppInContext(ctx, cust.ID, app)
+ if err != nil {
+ s.platformCredentialRefused(w, r, c, fmt.Errorf("customer %s: has-app %s: %w", cust.Sqid, app, err))
+ return
+ }
+ if !found {
+ http.NotFound(w, r)
+ return
+ }
+ }
+ // The gate's second half, now that nothing below refuses up front.
+ if !s.platformFinishPending(w, r, c) {
+ return
+ }
+ if s.platformCredentialBeforeInsert != nil {
+ s.platformCredentialBeforeInsert()
+ }
+
+ name := c.P.Name
+ if c.P.Kind == PrincipalUser {
+ name = c.P.Address
+ }
+ raw, expires, err := s.store.NewPlatformCustomerCredential(ctx, PlatformCredentialRequest{
+ CustomerID: cust.ID, PlatformAccountID: c.Platform.ID, Generation: c.Grant.Generation, Minter: c.P,
+ Name: name, MintedBy: c.Actor, Role: role, App: app, Rungs: req.Rungs, TTL: ttl,
+ }, time.Now())
+ if err != nil {
+ s.platformCredentialRefused(w, r, c, err)
+ return
+ }
+
+ target := fmt.Sprintf("%s (%s)", lc.Name, cust.Sqid)
+ if app != "" {
+ target = app
+ }
+ s.audit(cust, accountAuditSubject, c.Actor, auditPlatformCustomerCredential,
+ fmt.Sprintf(platformCopy["audit.credential"], role, target, expires.Format("2 January 2006 15:04 UTC")))
+ reply := platformCredentialReply{Token: raw, Account: cust.Sqid, Name: lc.Name, Role: string(role), App: app,
+ Rungs: []string{}, ExpiresAt: expires}
+ if rungs != "" {
+ reply.Rungs = strings.Split(rungs, ",")
+ }
+ writeJSON(w, http.StatusCreated, reply)
+}
+
+// platformCredentialTTL is the requested lifetime: 0 seconds is the
+// default, anything negative or past the maximum is refused before it is
+// multiplied (so a huge value cannot wrap into range).
+func platformCredentialTTL(seconds int64) (time.Duration, bool) {
+ if seconds < 0 || seconds > int64(PlatformCredentialMaxTTL/time.Second) {
+ return 0, false
+ }
+ return time.Duration(seconds) * time.Second, true
+}
+
+// platformCredentialRefused answers a refused or failed mint. The rung
+// refusals are the services door's words, byte for byte (apiservices.go),
+// so one rule reads the same at both mint doors.
+func (s *Server) platformCredentialRefused(w http.ResponseWriter, r *http.Request, c platformCaller, err error) {
+ var ue *UnknownRungError
+ switch {
+ case errors.Is(err, ErrPlatformCredentialRole):
+ jsonError(w, http.StatusBadRequest, platformCopy["cred.role"])
+ case errors.Is(err, ErrPlatformCredentialTTL):
+ jsonError(w, http.StatusBadRequest, platformCopy["cred.ttl"])
+ case errors.Is(err, ErrStableNotDelegable):
+ jsonError(w, http.StatusBadRequest, "stable cannot be delegated: moving it needs a passkey in the console")
+ case errors.As(err, &ue):
+ jsonError(w, http.StatusBadRequest, fmt.Sprintf("unknown rung %q: one of canary, edge, beta", ue.Rung))
+ case errors.Is(err, ErrPlatformAuthorityEnded):
+ jsonError(w, http.StatusForbidden, platformCopy["door.revoked"])
+ case errors.Is(err, errPlatformCredentialNoApp):
+ http.NotFound(w, r)
+ default:
+ log.Printf("console: platform %s: mint customer credential: %v", c.Platform.Sqid, err)
+ jsonError(w, http.StatusInternalServerError, platformCopy["cred.failed"])
+ }
+}
diff --git a/internal/console/apiplatformcustomers_test.go b/internal/console/apiplatformcustomers_test.go
index 389ac94fd..82c1d1468 100644
--- a/internal/console/apiplatformcustomers_test.go
+++ b/internal/console/apiplatformcustomers_test.go
@@ -23,12 +23,13 @@ import (
"github.com/carlosframework/platform/internal/svcrole"
)
-// platformDoorPatterns is every platform door Tasks 8 and 9 register.
+// platformDoorPatterns is every platform door Tasks 8, 9 and 10 register.
var platformDoorPatterns = []string{
"GET /api/cli/platform/{account}/customers",
"GET /api/cli/platform/{account}/customers/{customer}",
"PATCH /api/cli/platform/{account}/customers/{customer}",
"POST /api/cli/platform/{account}/customers",
+ "POST /api/cli/platform/{account}/customers/{customer}/credentials",
}
func platformCustomersURL(base, sqid string) string {
diff --git a/internal/console/authstore.go b/internal/console/authstore.go
index 893978003..e70fd45f4 100644
--- a/internal/console/authstore.go
+++ b/internal/console/authstore.go
@@ -386,12 +386,17 @@ func newCredentialID() (string, error) {
// that is not an address (see svcprincipal.go). cliKindLink is a linked
// deployment's credential (links_store.go): bound to one account and one
// link (its name column is the link ID), minted only by link approval,
-// never expiring, ended only by rotate and unlink.
+// never expiring, ended only by rotate and unlink. cliKindPlatform is a
+// per-customer credential (platform_credentials.go): bound to one customer
+// account, minted only by the platform door, always expiring, and live only
+// while its link to the platform and the grant generation it was minted in
+// are.
const (
- cliKindUser = ""
- cliKindApp = "app"
- cliKindService = "service"
- cliKindLink = "link"
+ cliKindUser = ""
+ cliKindApp = "app"
+ cliKindService = "service"
+ cliKindLink = "link"
+ cliKindPlatform = "platform"
)
// cliPurposeLink is a login request's purpose when a home deployment asks
@@ -850,8 +855,11 @@ func scanCLITokenRows(rows *sql.Rows) ([]CLIToken, error) {
//
// A link credential is not listed: its address is the person who approved
// the link, but it does not speak as them, and it is managed (rotated,
-// unlinked) on the account, never revoked from a person's settings. It is
-// CLITokensContext for callers with no request to follow.
+// unlinked) on the account, never revoked from a person's settings. A
+// per-customer platform credential is not listed either, for the same
+// reason: its address is whoever minted it, but it is the customer
+// account's credential, not a terminal of theirs. It is CLITokensContext
+// for callers with no request to follow.
func (s *Store) CLITokens(address string) ([]CLIToken, error) {
return s.CLITokensContext(context.Background(), address)
}
@@ -861,7 +869,8 @@ func (s *Store) CLITokens(address string) ([]CLIToken, error) {
func (s *Store) CLITokensContext(ctx context.Context, address string) ([]CLIToken, error) {
rows, err := s.db.QueryContext(ctx, `SELECT token_hash, address, label, remote_addr, kind, account_id, app,
role, name, created_at, expires_at, last_used, revoked_at, rotated_at, rungs, commands, scope
-FROM cli_tokens WHERE address = ? AND revoked_at = 0 AND kind != ? ORDER BY created_at DESC, token_hash`, address, cliKindLink)
+FROM cli_tokens WHERE address = ? AND revoked_at = 0 AND kind NOT IN (?, ?) ORDER BY created_at DESC, token_hash`,
+ address, cliKindLink, cliKindPlatform)
if err != nil {
return nil, err
}
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 5a43aabfb..e59a357eb 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1653,6 +1653,16 @@ var claimFixtures = map[string]claimFixture{
apps: claimRefs("bab/titogo"),
do: claimAPI(http.MethodPost, "/api/cli/services/bab", `{"name":"svc-cli","role":"publish","app":"titogo"}`),
}},
+ // A platform's per-customer credential (apiplatformcredentials.go): a
+ // Deploy credential names the customer's app, and its row is written
+ // under that app's permit. bab is linked to the granted second account
+ // as its customer; the owner of both mints it.
+ "route POST /api/cli/platform/{account}/customers/{customer}/credentials": {door: &claimDoor{
+ apps: claimRefs("bab/titogo"),
+ setup: claimPlatformCustomerBab,
+ do: claimAPI(http.MethodPost, "/api/cli/platform/"+claimSecondSqid+"/customers/bab/credentials",
+ `{"role":"deploy","app":"titogo","rungs":["edge"]}`),
+ }},
"route POST /api/cli/services/{account}/{name}/revoke": {door: &claimDoor{
apps: claimRefs("bab/titogo"),
setup: func(t *testing.T, cx *claimCase) { cx.service(t) },
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go
index 63df83384..c55f2899c 100644
--- a/internal/console/claim_invariant_probes_nonapp_test.go
+++ b/internal/console/claim_invariant_probes_nonapp_test.go
@@ -1654,6 +1654,17 @@ func claimPlatformCustomer(t *testing.T, cx *claimCase) {
}
}
+// claimPlatformCustomerBab links bab, which holds titogo, to the granted
+// second account as its customer, for the per-customer credential door.
+func claimPlatformCustomerBab(t *testing.T, cx *claimCase) {
+ t.Helper()
+ claimPlatformGranted(t, cx)
+ if _, err := cx.st.db.ExecContext(context.Background(), `UPDATE accounts SET platform = ?, platform_ref = 'census'
+ WHERE sqid = 'bab'`, claimSecondSqid); err != nil {
+ t.Fatal(err)
+ }
+}
+
// claimPlatformGranted stages the second account with an active platform
// grant, for the grant door's read and revoke probes.
func claimPlatformGranted(t *testing.T, cx *claimCase) {
diff --git a/internal/console/platform_copy.go b/internal/console/platform_copy.go
index e08abce7a..053119938 100644
--- a/internal/console/platform_copy.go
+++ b/internal/console/platform_copy.go
@@ -36,6 +36,10 @@ var platformCopy = map[string]string{
"update.operator_plan": "an operator set this account’s plan. ask them to change it",
"update.failed": "could not change the customer account. try again",
+ "cred.role": "a customer credential is publish for the whole account, or deploy for one app with its rungs",
+ "cred.ttl": "a customer credential lasts from 1 minute to 24 hours",
+ "cred.failed": "could not mint the credential. try again",
+
"svc.platform_app": "a platform credential works for the whole platform account, so it takes no --app",
"svc.not_platform": "only a platform account can hold a platform credential. an operator grants that with carlos accounts platform",
@@ -47,6 +51,7 @@ var platformCopy = map[string]string{
"audit.customer_created_by": "created by platform account %s",
"audit.customer_rename": "renamed customer account %s to %s",
"audit.customer_plan": "moved customer account %s to the %s plan",
+ "audit.credential": "minted a %s credential for %s, valid until %s",
// Browser flashes on the account's Delete account (ownership.go),
// sentence case as the rest of the browser copy is.
diff --git a/internal/console/platform_credentials.go b/internal/console/platform_credentials.go
new file mode 100644
index 000000000..ce2323ad0
--- /dev/null
+++ b/internal/console/platform_credentials.go
@@ -0,0 +1,281 @@
+package console
+
+// Per-customer credentials (platform accounts spec §6.2): a platform mints a
+// short-lived credential bound to one of its customer accounts, a cli_tokens
+// row of kind platform.
+//
+// This is the one exception to "a credential never mints a credential"
+// (AGENTS.md, "Rules this repo has paid for"). Its limits are what keep it
+// one: only the platform role reaches the door; what it mints is bound to
+// one customer account linked to that platform; it is Publish on that
+// account, or Deploy on one of its apps; it lives at most 24 hours; its role
+// reaches no mint door; and every request checks its link and its grant
+// generation.
+//
+// The invariant (Astra r1-2): a per-customer credential is valid only under
+// the grant generation it was minted in, and it is only ever written while
+// that generation is current and its minter still holds authority under it.
+// The mint (inside its insert transaction) and the resolver
+// (platformCustomerPrincipal) both ask platformLinkLive, which is
+// PlatformGenerationLive plus the customer's link, so they cannot disagree.
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "time"
+
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// A per-customer credential's lifetime: the default, and the bounds a
+// requested one must fall within.
+const (
+ PlatformCredentialDefaultTTL = time.Hour
+ PlatformCredentialMaxTTL = 24 * time.Hour
+ PlatformCredentialMinTTL = time.Minute
+)
+
+var (
+ ErrPlatformCredentialRole = errors.New("console: a customer credential is publish, or deploy on one app")
+ ErrPlatformCredentialTTL = errors.New("console: a customer credential lives 1 minute to 24 hours")
+ // ErrPlatformAuthorityEnded is a mint whose authority was gone by the
+ // time its insert transaction ran: the grant generation ended, the
+ // customer's link ended, or the minter lost its own authority (its
+ // platform credential revoked, or the person no longer an owner).
+ // Nothing is written.
+ ErrPlatformAuthorityEnded = errors.New("console: the platform's grant or the minter's authority ended during the request")
+ // errPlatformCredentialNoApp is a Deploy mint whose app the customer no
+ // longer holds when the insert transaction runs: the door had found it,
+ // and it was deleted since. A credential bound to an app name that is
+ // not there would reach the next app given that name.
+ errPlatformCredentialNoApp = errors.New("console: the customer account no longer has that app")
+)
+
+// PlatformCredentialRequest is one per-customer credential mint.
+type PlatformCredentialRequest struct {
+ CustomerID, PlatformAccountID int64
+ Generation int64 // the grant generation the platform gate admitted the caller under (Astra r1-2)
+ Minter Principal // re-checked inside the insert transaction
+ Name string // the minter's handle: the platform credential's name, or the person's address
+ MintedBy string // auditActor of the minter
+ Role svcrole.Role
+ App string
+ Rungs []string
+ TTL time.Duration // 0 means PlatformCredentialDefaultTTL
+}
+
+// platformCredentialShape checks a per-customer credential's role, app,
+// rungs and lifetime, writing nothing, and answers its stored rungs and its
+// lifetime. Role Publish takes no app and no rungs; role Deploy takes one
+// app and at least one rung, through canonicalRungs (stable is refused as
+// the services door refuses it); every other role is
+// ErrPlatformCredentialRole. A lifetime outside [1 minute, 24 hours] is
+// ErrPlatformCredentialTTL; 0 is the default hour. The door runs it before
+// anything is written, and the mint again.
+func platformCredentialShape(role svcrole.Role, app string, rungs []string, ttl time.Duration) (string, time.Duration, error) {
+ var canon string
+ switch role {
+ case svcrole.Publish:
+ if app != "" || len(rungs) != 0 {
+ return "", 0, ErrPlatformCredentialRole
+ }
+ case svcrole.Deploy:
+ var err error
+ if canon, err = canonicalRungs(rungs); err != nil {
+ return "", 0, err
+ }
+ if app == "" || canon == "" {
+ return "", 0, ErrPlatformCredentialRole
+ }
+ default:
+ return "", 0, ErrPlatformCredentialRole
+ }
+ if ttl == 0 {
+ ttl = PlatformCredentialDefaultTTL
+ }
+ if ttl < PlatformCredentialMinTTL || ttl > PlatformCredentialMaxTTL {
+ return "", 0, ErrPlatformCredentialTTL
+ }
+ return canon, ttl, nil
+}
+
+// NewPlatformCustomerCredential mints a per-customer credential: a
+// cli_tokens row of kind platform on the customer's account, recording its
+// platform and the grant generation it is minted under, expiring at now +
+// TTL. It answers the secret and that expiry.
+//
+// The shape is checked first (platformCredentialShape). The authority is
+// checked inside the insert transaction (Astra r1-2): the customer's link to
+// the platform under req.Generation (platformLinkLive), and the minter's own
+// authority under it, a service minter's platform credential still
+// unrevoked at that generation, or a person still an owner of the platform
+// account. Any of those gone is ErrPlatformAuthorityEnded, and nothing is
+// written.
+//
+// A Deploy credential names an app, so under the host-claim gate its row
+// is written under that app's permit (withAutoAppSQL), as an app-bound
+// service credential's is.
+func (s *Store) NewPlatformCustomerCredential(ctx context.Context, req PlatformCredentialRequest, now time.Time) (raw string, expiresAt time.Time, err error) {
+ rungs, ttl, err := platformCredentialShape(req.Role, req.App, req.Rungs, req.TTL)
+ if err != nil {
+ return "", time.Time{}, err
+ }
+ if req.CustomerID == 0 || req.PlatformAccountID == 0 || req.Generation == 0 || req.Name == "" || req.MintedBy == "" {
+ return "", time.Time{}, errors.New("console: a customer credential needs a customer, a platform, a generation, a name and a minter")
+ }
+ expires := now.Add(ttl).Unix()
+ err = s.withAutoAppSQL(ctx, req.CustomerID, req.App, "sql.NewPlatformCustomerCredential", func(v *Store) error {
+ var err error
+ raw, err = v.claimRawNewPlatformCustomerCredential(ctx, req, rungs, expires, now)
+ return err
+ })
+ if err != nil {
+ return "", time.Time{}, err
+ }
+ return raw, time.Unix(expires, 0).UTC(), nil
+}
+
+// claimRawNewPlatformCustomerCredential is the mint's transaction: the
+// authority checks and the insert, on one connection, so a revoke, a
+// re-grant or the minter's own revoke commits either before all of it or
+// after the row exists (and then ends it).
+func (s *Store) claimRawNewPlatformCustomerCredential(ctx context.Context, req PlatformCredentialRequest, rungs string, expires int64, now time.Time) (string, error) {
+ credID, err := newCredentialID()
+ if err != nil {
+ return "", err
+ }
+ raw, err := randomToken()
+ if err != nil {
+ return "", err
+ }
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return "", err
+ }
+ defer tx.Rollback()
+ if _, live := s.platformLinkLive(ctx, tx, req.CustomerID, req.PlatformAccountID, req.Generation); !live {
+ return "", ErrPlatformAuthorityEnded
+ }
+ if held, err := platformMinterHolds(ctx, tx, req, now); err != nil {
+ return "", err
+ } else if !held {
+ return "", ErrPlatformAuthorityEnded
+ }
+ if req.App != "" {
+ var one int
+ err := tx.QueryRowContext(ctx, `SELECT 1 FROM apps WHERE account_id = ? AND app = ? AND deleted_at = 0`,
+ req.CustomerID, req.App).Scan(&one)
+ if errors.Is(err, sql.ErrNoRows) {
+ return "", errPlatformCredentialNoApp
+ }
+ if err != nil {
+ return "", err
+ }
+ }
+ if _, err := tx.ExecContext(ctx, `INSERT INTO cli_tokens
+(token_hash, address, label, remote_addr, created_at, rotated_at, expires_at, kind, account_id, app, role, name, rungs,
+credential_id, commands, scope, platform_account_id, platform_generation)
+VALUES (?, ?, '', '', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', '', ?, ?)`,
+ hashToken(raw), req.MintedBy, now.Unix(), now.Unix(), expires, cliKindPlatform, req.CustomerID, req.App,
+ string(req.Role), req.Name, rungs, credID, req.PlatformAccountID, req.Generation); err != nil {
+ return "", err
+ }
+ if err := tx.Commit(); err != nil {
+ return "", err
+ }
+ return raw, nil
+}
+
+// platformMinterHolds reports whether the minter still holds the authority
+// it was admitted with, read in the mint's transaction: a service minter's
+// own row (by credential id) is a live platform credential of this platform
+// at req.Generation; a person is an owner of the platform account. Any
+// other principal holds nothing.
+func platformMinterHolds(ctx context.Context, tx *sql.Tx, req PlatformCredentialRequest, now time.Time) (bool, error) {
+ var one int
+ var err error
+ switch req.Minter.Kind {
+ case PrincipalService:
+ if req.Minter.CredentialID == "" {
+ return false, nil
+ }
+ err = tx.QueryRowContext(ctx, `SELECT 1 FROM cli_tokens WHERE credential_id = ? AND kind = ? AND role = ?
+ AND account_id = ? AND platform_account_id = ? AND platform_generation = ? AND revoked_at = 0
+ AND (expires_at = 0 OR expires_at >= ?)`,
+ req.Minter.CredentialID, cliKindService, string(svcrole.Platform), req.PlatformAccountID, req.PlatformAccountID,
+ req.Generation, now.Unix()).Scan(&one)
+ case PrincipalUser:
+ if req.Minter.Address == "" {
+ return false, nil
+ }
+ err = tx.QueryRowContext(ctx, `SELECT 1 FROM memberships WHERE account_id = ? AND address = ? AND role = ?`,
+ req.PlatformAccountID, req.Minter.Address, RoleOwner).Scan(&one)
+ default:
+ return false, nil
+ }
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ return err == nil, err
+}
+
+// platformLinkLive is the one check that a per-customer credential's
+// authority stands: PlatformGenerationLive (the grant active at exactly
+// generation, the platform account live) and the customer account live and
+// linked to that platform, in one query. It answers the platform's sqid. q
+// is the pool or the mint's transaction, so resolution and minting ask the
+// identical question. Any error is "not live".
+func (s *Store) platformLinkLive(ctx context.Context, q dbQuerier, customerID, platformAccountID, generation int64) (platformSqid string, ok bool) {
+ err := q.QueryRowContext(ctx, `SELECT p.sqid FROM platform_grants g
+ JOIN accounts p ON p.id = g.account_id
+ JOIN accounts c ON c.platform = p.sqid
+ WHERE g.account_id = ? AND g.state = ? AND g.generation = ? AND p.deleted_at = 0
+ AND c.id = ? AND c.id != p.id AND c.deleted_at = 0`,
+ platformAccountID, PlatformGrantActive, generation, customerID).Scan(&platformSqid)
+ if err != nil || platformSqid == "" {
+ return "", false
+ }
+ return platformSqid, true
+}
+
+// platformCustomerPrincipal is the resolver's reading of a kind platform
+// row (CLIPrincipalContext, which has already refused a revoked row and one
+// whose expiry is 0 or past). It is the row the mint writes or nothing:
+// bound to a customer and a platform under a generation, named, with a
+// credential id; role Publish with no app and no rungs, or Deploy with an
+// app and readable rungs; no commands and no scope. And its authority
+// stands on this request: platformLinkLive. Deleting or unlinking the
+// customer, revoking the grant or deleting the platform ends it here,
+// whatever its revoked_at says.
+func (s *Store) platformCustomerPrincipal(ctx context.Context, addr string, accountID int64, app, role, name, rungs, credID, commands, scope string,
+ platformAccountID, generation int64) (Principal, bool) {
+ if accountID == 0 || platformAccountID == 0 || accountID == platformAccountID || generation == 0 || name == "" ||
+ credID == "" || commands != "" || scope != "" {
+ return Principal{}, false
+ }
+ r, ok := svcrole.Parse(role)
+ if !ok {
+ return Principal{}, false
+ }
+ var stored []string
+ switch r {
+ case svcrole.Publish:
+ if app != "" || rungs != "" {
+ return Principal{}, false
+ }
+ case svcrole.Deploy:
+ if stored, ok = parseStoredRungs(rungs); !ok || app == "" {
+ return Principal{}, false
+ }
+ default:
+ return Principal{}, false
+ }
+ sqid, live := s.platformLinkLive(ctx, s.db, accountID, platformAccountID, generation)
+ if !live {
+ return Principal{}, false
+ }
+ return Principal{Kind: PrincipalService, Address: addr, AccountID: accountID, App: app, Role: r, Name: name,
+ Rungs: stored, CredentialID: credID, PlatformAccountID: platformAccountID, Platform: sqid,
+ PlatformGeneration: generation}, true
+}
diff --git a/internal/console/platform_credentials_test.go b/internal/console/platform_credentials_test.go
index 81045e9b6..199f46e98 100644
--- a/internal/console/platform_credentials_test.go
+++ b/internal/console/platform_credentials_test.go
@@ -6,6 +6,8 @@ import (
"fmt"
"net/http"
"slices"
+ "strings"
+ "sync"
"testing"
"time"
@@ -312,3 +314,667 @@ func TestBrowserMintFormDoesNotOfferPlatform(t *testing.T) {
t.Fatalf("the form offers %v, want no %q", p.ServiceRoles, svcrole.Platform)
}
}
+
+// ---- per-customer credentials (Task 10) -----------------------------------
+
+func credentialsURL(base, platform, customer string) string {
+ return platformCustomerURL(base, platform, customer) + "/credentials"
+}
+
+func mintCustomerCredential(t *testing.T, base, platform, customer, bearer string, body any) (int, map[string]any, string) {
+ t.Helper()
+ status, out, raw, err := callJSON(http.MethodPost, credentialsURL(base, platform, customer), bearer, body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return status, out, raw
+}
+
+// customerCredential mints one through the door, which must answer 201, and
+// returns the reply.
+func customerCredential(t *testing.T, fx *consoleFixture, platform, customer, bearer string, body any) map[string]any {
+ t.Helper()
+ status, out, raw := mintCustomerCredential(t, fx.ts.URL, platform, customer, bearer, body)
+ if status != http.StatusCreated {
+ t.Fatalf("mint for %s = %d %s, want 201", customer, status, raw)
+ }
+ return out
+}
+
+func tokenIn(t *testing.T, out map[string]any) string {
+ t.Helper()
+ tok, _ := out["token"].(string)
+ if tok == "" {
+ t.Fatalf("reply %v has no token", out)
+ }
+ return tok
+}
+
+// customerCredentialRows counts the kind platform rows on the account.
+func customerCredentialRows(t *testing.T, st *Store, accountID int64) int {
+ t.Helper()
+ var n int
+ if err := st.db.QueryRowContext(context.Background(), `SELECT COUNT(*) FROM cli_tokens WHERE kind = ? AND account_id = ?`,
+ cliKindPlatform, accountID).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+// appsStatus is the status a bearer gets at GET /api/cli/apps, which every
+// publish credential reaches: 200 while it resolves, 401 once it does not.
+func appsStatus(t *testing.T, fx *consoleFixture, bearer string) int {
+ t.Helper()
+ status, _, _ := rawReq(t, http.MethodGet, fx.ts.URL+"/api/cli/apps", bearer, "")
+ return status
+}
+
+// secondCustomer creates cafe (ref 4813) on the platform and returns it.
+func secondCustomer(t *testing.T, fx *consoleFixture, p *Account, tok string) *Account {
+ t.Helper()
+ status, out, raw := createCustomer(t, fx.ts.URL, p.Sqid, tok, map[string]any{"name": "cafe", "ref": "4813"})
+ if status != http.StatusCreated {
+ t.Fatalf("create cafe = %d %s", status, raw)
+ }
+ c, err := fx.st.AccountBySqid(customerIn(t, out)["account"].(string))
+ if err != nil || c == nil {
+ t.Fatalf("cafe row: %+v %v", c, err)
+ }
+ return c
+}
+
+func TestCustomerCredentialResolvesToTheCustomerOnly(t *testing.T) {
+ fx, p, tok, cust := customerWorld(t, "free")
+ before := time.Now()
+ out := customerCredential(t, fx, p.Sqid, cust.Sqid, tok, map[string]any{"role": "publish"})
+ if out["account"] != cust.Sqid || out["name"] != "shop" || out["role"] != "publish" || out["app"] != "" ||
+ fmt.Sprint(out["rungs"]) != "[]" {
+ t.Fatalf("mint reply %v, want shop's account and name, publish, no app, no rungs", out)
+ }
+ raw := tokenIn(t, out)
+ expires, err := time.Parse(time.RFC3339, out["expires_at"].(string))
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ pr, ok := fx.st.CLIPrincipal(raw, time.Now())
+ if !ok || pr.Kind != PrincipalService || pr.AccountID != cust.ID || pr.Role != svcrole.Publish || pr.App != "" ||
+ pr.Platform != p.Sqid || pr.PlatformAccountID != p.ID || pr.PlatformGeneration != 1 || pr.Name != "cms" ||
+ pr.Rungs != nil || pr.CredentialID == "" {
+ t.Fatalf("CLIPrincipal = %+v %v, want publish on %s from platform %s at generation 1", pr, ok, cust.Sqid, p.Sqid)
+ }
+ if key := principalKey(pr); key != fmt.Sprintf("service:%d/cms", cust.ID) {
+ t.Fatalf("principalKey = %q, want the customer's own budget", key)
+ }
+ var kind, address string
+ var exp, platformID, gen int64
+ if err := fx.st.db.QueryRowContext(context.Background(), `SELECT kind, address, expires_at, platform_account_id,
+ platform_generation FROM cli_tokens WHERE token_hash = ?`, hashToken(raw)).Scan(&kind, &address, &exp, &platformID, &gen); err != nil {
+ t.Fatal(err)
+ }
+ actor := "service:" + p.Sqid + "/cms"
+ if kind != cliKindPlatform || address != actor || exp != expires.Unix() || platformID != p.ID || gen != 1 {
+ t.Fatalf("row kind %q address %q expires %d platform %d generation %d", kind, address, exp, platformID, gen)
+ }
+ if d := expires.Sub(before); d < PlatformCredentialDefaultTTL-time.Second || d > PlatformCredentialDefaultTTL+5*time.Second {
+ t.Fatalf("expires_at %v is %v after the mint, want the default hour", expires, d)
+ }
+
+ // The customer's own account, and only its own.
+ if status := appsStatus(t, fx, raw); status != http.StatusOK {
+ t.Fatalf("GET /api/cli/apps = %d, want 200", status)
+ }
+ if status, _, body := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+p.Sqid+"/new", raw, `{"name":"site"}`); status != http.StatusNotFound || body != "404 page not found\n" {
+ t.Fatalf("app create on the platform account = %d %q, want the stdlib 404", status, body)
+ }
+
+ want := fmt.Sprintf(platformCopy["audit.credential"], "publish", "shop ("+cust.Sqid+")", expires.UTC().Format("2 January 2006 15:04 UTC"))
+ if rows := platformAudit(t, fx, cust.ID, auditPlatformCustomerCredential); len(rows) != 1 || rows[0].Detail != want || rows[0].Address != actor {
+ t.Fatalf("customer audit %+v, want one %q by %s", rows, want, actor)
+ }
+}
+
+// TestCustomerCredentialRefusedOnASecondCustomer (Astra r1-5): two customers
+// each hold an app named site, and each credential reaches its own only.
+func TestCustomerCredentialRefusedOnASecondCustomer(t *testing.T) {
+ fx, p, tok, c1 := customerWorld(t, "free")
+ c2 := secondCustomer(t, fx, p, tok)
+ t1 := tokenIn(t, customerCredential(t, fx, p.Sqid, c1.Sqid, tok, map[string]any{"role": "publish"}))
+ t2 := tokenIn(t, customerCredential(t, fx, p.Sqid, c2.Sqid, tok, map[string]any{"role": "publish"}))
+ for _, c := range []struct {
+ acct *Account
+ tok string
+ }{{c1, t1}, {c2, t2}} {
+ status, _, body := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+c.acct.Sqid+"/new", c.tok, `{"name":"site"}`)
+ if status/100 != 2 {
+ t.Fatalf("create site in %s = %d %s", c.acct.Sqid, status, body)
+ }
+ if status, _, body := rawReq(t, http.MethodGet, fx.ts.URL+"/api/cli/apps/"+c.acct.Sqid+"/site/channels", c.tok, ""); status != http.StatusOK {
+ t.Fatalf("own channels in %s = %d %s, want 200", c.acct.Sqid, status, body)
+ }
+ }
+ for _, c := range []struct {
+ what, method, path, tok, body string
+ }{
+ {"T1 reads c2's channels", http.MethodGet, "/api/cli/apps/" + c2.Sqid + "/site/channels", t1, ""},
+ {"T1 promotes in c2", http.MethodPost, "/api/cli/apps/" + c2.Sqid + "/site/promote", t1, `{"from":"edge","to":"beta"}`},
+ {"T2 reads c1's channels", http.MethodGet, "/api/cli/apps/" + c1.Sqid + "/site/channels", t2, ""},
+ {"T2 promotes in c1", http.MethodPost, "/api/cli/apps/" + c1.Sqid + "/site/promote", t2, `{"from":"edge","to":"beta"}`},
+ } {
+ if status, _, body := rawReq(t, c.method, fx.ts.URL+c.path, c.tok, c.body); status != http.StatusNotFound || body != "404 page not found\n" {
+ t.Errorf("%s = %d %q, want the stdlib 404", c.what, status, body)
+ }
+ }
+}
+
+func TestCustomerCredentialExpiryBoundary(t *testing.T) {
+ fx, p, tok, cust := customerWorld(t, "free")
+ out := customerCredential(t, fx, p.Sqid, cust.Sqid, tok, map[string]any{"role": "publish"})
+ raw := tokenIn(t, out)
+ expires, err := time.Parse(time.RFC3339, out["expires_at"].(string))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := fx.st.CLIPrincipal(raw, expires); !ok {
+ t.Fatalf("credential at its expiry %v does not resolve", expires)
+ }
+ if pr, ok := fx.st.CLIPrincipal(raw, expires.Add(time.Second)); ok {
+ t.Fatalf("credential a second past its expiry resolved to %+v", pr)
+ }
+
+ // The bounds, and a lifetime inside them.
+ for _, c := range []struct {
+ seconds int64
+ status int
+ }{
+ {int64((25 * time.Hour).Seconds()), http.StatusBadRequest},
+ {30, http.StatusBadRequest},
+ {-60, http.StatusBadRequest},
+ {1 << 62, http.StatusBadRequest},
+ {int64(PlatformCredentialMinTTL.Seconds()), http.StatusCreated},
+ {int64(PlatformCredentialMaxTTL.Seconds()), http.StatusCreated},
+ } {
+ before := customerCredentialRows(t, fx.st, cust.ID)
+ status, out, raw := mintCustomerCredential(t, fx.ts.URL, p.Sqid, cust.Sqid, tok, map[string]any{"role": "publish", "ttl_seconds": c.seconds})
+ if status != c.status {
+ t.Fatalf("ttl %ds = %d %s, want %d", c.seconds, status, raw, c.status)
+ }
+ after := customerCredentialRows(t, fx.st, cust.ID)
+ if status == http.StatusBadRequest {
+ wantPlatformError(t, fmt.Sprintf("ttl %ds", c.seconds), status, out, http.StatusBadRequest, "cred.ttl")
+ if after != before {
+ t.Fatalf("refused ttl %ds wrote a row", c.seconds)
+ }
+ continue
+ }
+ exp, err := time.Parse(time.RFC3339, out["expires_at"].(string))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if d := time.Until(exp); d > time.Duration(c.seconds)*time.Second || d < time.Duration(c.seconds)*time.Second-time.Minute {
+ t.Fatalf("ttl %ds expires in %v", c.seconds, d)
+ }
+ }
+
+ // A row with no expiry is not one this console wrote: refused, never
+ // read as "never".
+ var credID string
+ if err := fx.st.db.QueryRowContext(context.Background(), `SELECT credential_id FROM cli_tokens WHERE token_hash = ?`,
+ hashToken(raw)).Scan(&credID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.db.ExecContext(context.Background(), `UPDATE cli_tokens SET expires_at = 0 WHERE credential_id = ?`, credID); err != nil {
+ t.Fatal(err)
+ }
+ if pr, ok := fx.st.CLIPrincipal(raw, time.Now()); ok {
+ t.Fatalf("credential with expires_at 0 resolved to %+v", pr)
+ }
+}
+
+func TestCustomerCredentialRefusedAfterRevokeAndLinkGone(t *testing.T) {
+ fx, p, tok, cust := customerWorld(t, "free")
+ raw := tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, tok, map[string]any{"role": "publish"}))
+ pr, ok := fx.st.CLIPrincipal(raw, time.Now())
+ if !ok {
+ t.Fatal("fresh credential does not resolve")
+ }
+ if status := appsStatus(t, fx, raw); status != http.StatusOK {
+ t.Fatalf("live credential = %d, want 200", status)
+ }
+
+ ctx := context.Background()
+ if _, err := fx.st.RevokePlatformGrant(ctx, p.ID, "ops@keymail.dev", "ended", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if status := appsStatus(t, fx, raw); status != http.StatusUnauthorized {
+ t.Fatalf("after the revoke = %d, want 401", status)
+ }
+ grantPlatformAccount(t, fx, p.Sqid, 5, "free", "personal")
+ if status := appsStatus(t, fx, raw); status != http.StatusUnauthorized {
+ t.Fatalf("after the re-grant = %d, want 401", status)
+ }
+ // The revoke swept the row (Task 4). Un-revoke it, so only the
+ // generation check can refuse it (pre-flight C4).
+ if _, err := fx.st.db.ExecContext(ctx, `UPDATE cli_tokens SET revoked_at = 0 WHERE credential_id = ?`, pr.CredentialID); err != nil {
+ t.Fatal(err)
+ }
+ if status := appsStatus(t, fx, raw); status != http.StatusUnauthorized {
+ t.Fatalf("un-revoked credential of generation 1 = %d, want 401", status)
+ }
+
+ // A fresh credential under the new generation works, until the
+ // customer is deleted: deletion does not revoke it, the link check
+ // refuses it.
+ tok2 := platformToken(t, fx, p.ID, "cms-2")
+ fresh := tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, tok2, map[string]any{"role": "publish"}))
+ if q, ok := fx.st.CLIPrincipal(fresh, time.Now()); !ok || q.PlatformGeneration != 2 {
+ t.Fatalf("fresh credential = %+v %v, want generation 2", q, ok)
+ }
+ if status := appsStatus(t, fx, fresh); status != http.StatusOK {
+ t.Fatalf("fresh credential = %d, want 200", status)
+ }
+ if err := fx.st.DeleteAccount(cust.ID, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if at := tokenRevokedAt(t, fx.st, hashToken(fresh)); at != 0 {
+ t.Fatalf("deleting the customer revoked its credential (revoked_at %d); the link check is the witness", at)
+ }
+ if status := appsStatus(t, fx, fresh); status != http.StatusUnauthorized {
+ t.Fatalf("after the customer's deletion = %d, want 401", status)
+ }
+}
+
+// pausedMint runs a mint that blocks in platformCredentialBeforeInsert, runs
+// during while it waits, releases it and answers its reply.
+func pausedMint(t *testing.T, fx *consoleFixture, set func(*seamGate), platform, customer, bearer string, during func()) (int, map[string]any, string) {
+ t.Helper()
+ gate := newGate(t)
+ set(gate)
+ defer set(nil)
+ type reply struct {
+ status int
+ out map[string]any
+ raw string
+ err error
+ }
+ done := make(chan reply, 1)
+ go func() {
+ status, out, raw, err := callJSON(http.MethodPost, credentialsURL(fx.ts.URL, platform, customer), bearer, map[string]any{"role": "publish"})
+ done <- reply{status, out, raw, err}
+ }()
+ guard := time.After(30 * time.Second)
+ waitOrGuard(t, gate.entered, guard, "the mint never reached its insert")
+ during()
+ gate.open()
+ r := waitOrGuard(t, done, guard, "the mint never answered")
+ if r.err != nil {
+ t.Fatal(r.err)
+ }
+ return r.status, r.out, r.raw
+}
+
+// TestCustomerCredentialMintPausedAcrossRevokeAndRegrant (Astra r1-2): the
+// authority is re-checked inside the insert transaction, so a revoke and a
+// re-grant while the mint waits, or the minter's own revoke, leaves no row.
+func TestCustomerCredentialMintPausedAcrossRevokeAndRegrant(t *testing.T) {
+ fx, p, tok, cust := customerWorld(t, "free")
+ var mu sync.Mutex
+ var cur *seamGate
+ set := func(g *seamGate) { mu.Lock(); cur = g; mu.Unlock() }
+ fx.srv.platformCredentialBeforeInsert = func() {
+ mu.Lock()
+ g := cur
+ mu.Unlock()
+ if g != nil {
+ g.block()
+ }
+ }
+ ctx := context.Background()
+ revokeAndRegrant := func() {
+ if _, err := fx.st.RevokePlatformGrant(ctx, p.ID, "ops@keymail.dev", "ended", time.Now()); err != nil {
+ t.Error(err)
+ }
+ grantPlatformAccount(t, fx, p.Sqid, 5, "free", "personal")
+ }
+ wantNone := func(what string, status int, out map[string]any) {
+ t.Helper()
+ wantPlatformError(t, what, status, out, http.StatusForbidden, "door.revoked")
+ if n := customerCredentialRows(t, fx.st, cust.ID); n != 0 {
+ t.Fatalf("%s left %d kind platform rows, want none", what, n)
+ }
+ if rows := platformAudit(t, fx, cust.ID, auditPlatformCustomerCredential); len(rows) != 0 {
+ t.Fatalf("%s audited %+v", what, rows)
+ }
+ }
+
+ status, out, _ := pausedMint(t, fx, set, p.Sqid, cust.Sqid, tok, revokeAndRegrant)
+ wantNone("platform credential across a revoke and re-grant", status, out)
+
+ // A person owner, admitted under generation 2: the generation moves
+ // under it.
+ owner := cliToken(t, fx, "owner"+p.Sqid+"@example.com", "code-paused-mint-owner")
+ status, out, _ = pausedMint(t, fx, set, p.Sqid, cust.Sqid, owner, revokeAndRegrant)
+ wantNone("person owner across a revoke and re-grant", status, out)
+
+ // Only the minter's own credential revoked: the grant is untouched.
+ tok3 := platformToken(t, fx, p.ID, "cms-3")
+ status, out, _ = pausedMint(t, fx, set, p.Sqid, cust.Sqid, tok3, func() {
+ if err := fx.st.RevokeServicePrincipal(p.ID, "cms-3", time.Now()); err != nil {
+ t.Error(err)
+ }
+ })
+ wantNone("platform credential revoked during the mint", status, out)
+
+ // With nothing in the way, the same mint goes through.
+ tok4 := platformToken(t, fx, p.ID, "cms-4")
+ if status, _, raw := pausedMint(t, fx, set, p.Sqid, cust.Sqid, tok4, func() {}); status != http.StatusCreated {
+ t.Fatalf("undisturbed mint = %d %s, want 201", status, raw)
+ }
+}
+
+func TestCustomerCredentialAuditNamesThePlatform(t *testing.T) {
+ fx, p, tok, cust := customerWorld(t, "free")
+ raw := tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, tok, map[string]any{"role": "publish"}))
+ if status, _, body := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+cust.Sqid+"/new", raw, `{"name":"site"}`); status/100 != 2 {
+ t.Fatalf("create site = %d %s", status, body)
+ }
+ events, err := fx.st.Events(cust.ID, "site", 50)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := "platform:" + p.Sqid + "/cms"
+ found := false
+ for _, e := range events {
+ if e.Action == "create" {
+ found = true
+ if e.Address != want {
+ t.Fatalf("app create audited by %q, want %q", e.Address, want)
+ }
+ }
+ }
+ if !found {
+ t.Fatalf("no create event in %+v", events)
+ }
+ // The platform credential itself keeps its service: actor (pre-flight C9).
+ pr, ok := fx.st.CLIPrincipal(tok, time.Now())
+ if !ok {
+ t.Fatal("platform credential does not resolve")
+ }
+ if got := auditActor(pr, p); got != "service:"+p.Sqid+"/cms" {
+ t.Fatalf("platform credential's actor %q, want service:%s/cms", got, p.Sqid)
+ }
+}
+
+// TestCustomerCredentialNeverReachesPersonOrMintDoors pins the limits of
+// the one exception to "a credential never mints a credential" (AGENTS.md):
+// what the platform door mints reaches no mint door, this one included,
+// and no person-only or operator door.
+func TestCustomerCredentialNeverReachesPersonOrMintDoors(t *testing.T) {
+ fx, p, tok, cust := customerWorld(t, "free")
+ if _, err := fx.st.CreateAppIn(cust.ID, "site", "service:"+p.Sqid+"/cms", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ publish := tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, tok, map[string]any{"role": "publish"}))
+ deploy := tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, tok,
+ map[string]any{"role": "deploy", "app": "site", "rungs": []string{"edge"}}))
+ var before int
+ count := func() int {
+ t.Helper()
+ var n int
+ if err := fx.st.db.QueryRowContext(context.Background(), `SELECT COUNT(*) FROM cli_tokens`).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+ }
+ before = count()
+ doors := []struct{ method, path, body string }{
+ {http.MethodPost, "/api/cli/services/" + cust.Sqid, `{"name":"x","role":"publish"}`},
+ {http.MethodGet, "/api/cli/services/" + cust.Sqid, ""},
+ {http.MethodPost, "/api/cli/apps/" + cust.Sqid + "/site/instance-token", `{}`},
+ {http.MethodPost, "/api/cli/apps/" + cust.Sqid + "/site/door-keys", `{}`},
+ {http.MethodPost, "/api/cli/accounts/" + cust.Sqid + "/plan", `{"plan":"personal"}`},
+ {http.MethodPost, "/api/cli/accounts/" + cust.Sqid + "/domains/purchases", `{}`},
+ {http.MethodPost, "/api/cli/platform/" + cust.Sqid + "/customers", `{"name":"x"}`},
+ {http.MethodPost, "/api/cli/platform/" + p.Sqid + "/customers/" + cust.Sqid + "/credentials", `{"role":"publish"}`},
+ {http.MethodPost, "/api/cli/platform/" + cust.Sqid + "/customers/" + cust.Sqid + "/credentials", `{"role":"publish"}`},
+ }
+ for _, bearer := range []struct{ name, tok string }{{"publish", publish}, {"deploy", deploy}} {
+ for _, d := range doors {
+ if status, _, body := rawReq(t, d.method, fx.ts.URL+d.path, bearer.tok, d.body); status != http.StatusForbidden {
+ t.Errorf("%s credential at %s %s = %d %s, want the role gate's 403", bearer.name, d.method, d.path, status, body)
+ }
+ }
+ }
+ if after := count(); after != before {
+ t.Fatalf("cli_tokens rows %d, were %d: a refused mint wrote a credential", after, before)
+ }
+}
+
+func TestCustomerCredentialDeployNarrowedToOneApp(t *testing.T) {
+ fx, p, tok, cust := customerWorld(t, "free")
+ for _, app := range []string{"site", "blog"} {
+ if _, err := fx.st.CreateAppIn(cust.ID, app, "service:"+p.Sqid+"/cms", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ out := customerCredential(t, fx, p.Sqid, cust.Sqid, tok, map[string]any{"role": "deploy", "app": "site", "rungs": []string{"edge"}})
+ if out["role"] != "deploy" || out["app"] != "site" || fmt.Sprint(out["rungs"]) != "[edge]" {
+ t.Fatalf("deploy mint reply %v", out)
+ }
+ raw := tokenIn(t, out)
+ pr, ok := fx.st.CLIPrincipal(raw, time.Now())
+ if !ok || pr.Role != svcrole.Deploy || pr.App != "site" || !slices.Equal(pr.Rungs, []string{"edge"}) || pr.Platform != p.Sqid {
+ t.Fatalf("CLIPrincipal = %+v %v, want deploy on site, rungs edge", pr, ok)
+ }
+ if status, _, body := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+cust.Sqid+"/blog/promote", raw, `{"from":"edge","to":"beta"}`); status != http.StatusNotFound || body != "404 page not found\n" {
+ t.Fatalf("promote blog = %d %q, want the stdlib 404", status, body)
+ }
+ if status, _, body := rawReq(t, http.MethodGet, fx.ts.URL+"/api/cli/apps/"+cust.Sqid+"/site/channels", raw, ""); status != http.StatusOK {
+ t.Fatalf("site channels = %d %s, want 200", status, body)
+ }
+ want := fmt.Sprintf(platformCopy["audit.credential"], "deploy", "site", "")
+ if rows := platformAudit(t, fx, cust.ID, auditPlatformCustomerCredential); len(rows) != 1 || !strings.HasPrefix(rows[0].Detail, want) {
+ t.Fatalf("customer audit %+v, want one starting %q", rows, want)
+ }
+}
+
+// TestCustomerCredentialRefusalsWriteNothing (ruling B): every refusal comes
+// before the platform's pending mints are finished, so a refused mint
+// writes no row and finishes no promise. A valid mint finishes it on its
+// way.
+func TestCustomerCredentialRefusalsWriteNothing(t *testing.T) {
+ fx, p, tok, cust := customerWorld(t, "free")
+ if _, err := fx.st.CreateAppIn(cust.ID, "site", "service:"+p.Sqid+"/cms", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ if err := fx.st.ReservePlatformMint(ctx, PendingMint{MintID: strings.Repeat("ab", 16), Platform: p.Sqid, Ref: "4900",
+ Name: "cafe", Plan: "free", PlanReason: "platform " + p.Sqid, By: "service:" + p.Sqid + "/cms",
+ CreatedAt: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+ stable := fmt.Sprintf("%q", "stable cannot be delegated: moving it needs a passkey in the console")
+ for _, c := range []struct {
+ what string
+ customer string
+ body map[string]any
+ status int
+ error string // "" for the stdlib 404
+ }{
+ {"an unknown field", cust.Sqid, map[string]any{"role": "publish", "tll": 60}, http.StatusBadRequest, "-"},
+ {"no role", cust.Sqid, map[string]any{}, http.StatusBadRequest, platformCopy["cred.role"]},
+ {"the platform role", cust.Sqid, map[string]any{"role": "platform"}, http.StatusBadRequest, platformCopy["cred.role"]},
+ {"the admin role", cust.Sqid, map[string]any{"role": "admin"}, http.StatusBadRequest, platformCopy["cred.role"]},
+ {"publish on an app", cust.Sqid, map[string]any{"role": "publish", "app": "site"}, http.StatusBadRequest, platformCopy["cred.role"]},
+ {"publish with rungs", cust.Sqid, map[string]any{"role": "publish", "rungs": []string{"edge"}}, http.StatusBadRequest, platformCopy["cred.role"]},
+ {"deploy with no app", cust.Sqid, map[string]any{"role": "deploy", "rungs": []string{"edge"}}, http.StatusBadRequest, platformCopy["cred.role"]},
+ {"deploy with no rungs", cust.Sqid, map[string]any{"role": "deploy", "app": "site"}, http.StatusBadRequest, platformCopy["cred.role"]},
+ {"deploy on stable", cust.Sqid, map[string]any{"role": "deploy", "app": "site", "rungs": []string{"stable"}}, http.StatusBadRequest, stable},
+ {"a ttl too long", cust.Sqid, map[string]any{"role": "publish", "ttl_seconds": 90000}, http.StatusBadRequest, platformCopy["cred.ttl"]},
+ {"deploy on an app the customer lacks", cust.Sqid, map[string]any{"role": "deploy", "app": "nope", "rungs": []string{"edge"}}, http.StatusNotFound, ""},
+ {"an unknown customer", "zzzz", map[string]any{"role": "publish"}, http.StatusNotFound, ""},
+ {"the platform itself", p.Sqid, map[string]any{"role": "publish"}, http.StatusNotFound, ""},
+ } {
+ status, out, raw := mintCustomerCredential(t, fx.ts.URL, p.Sqid, c.customer, tok, c.body)
+ switch {
+ case status != c.status:
+ t.Errorf("%s = %d %s, want %d", c.what, status, raw, c.status)
+ case c.error == "" && raw != "404 page not found\n":
+ t.Errorf("%s = %q, want the stdlib 404", c.what, raw)
+ case c.error == stable && fmt.Sprintf("%q", out["error"]) != stable:
+ t.Errorf("%s = %s, want the services door's stable refusal", c.what, raw)
+ case c.error != "" && c.error != "-" && c.error != stable && out["error"] != c.error:
+ t.Errorf("%s = %s, want %q", c.what, raw, c.error)
+ }
+ if n := customerCredentialRows(t, fx.st, cust.ID); n != 0 {
+ t.Fatalf("%s wrote %d kind platform rows", c.what, n)
+ }
+ if pm := pendingMints(t, fx.st, p.Sqid); len(pm) != 1 {
+ t.Fatalf("%s: pending mints %+v, want the 4900 promise unfinished", c.what, pm)
+ }
+ }
+ if rows := platformAudit(t, fx, cust.ID, auditPlatformCustomerCredential); len(rows) != 0 {
+ t.Fatalf("refusals audited %+v", rows)
+ }
+
+ customerCredential(t, fx, p.Sqid, cust.Sqid, tok, map[string]any{"role": "publish"})
+ if pm := pendingMints(t, fx.st, p.Sqid); len(pm) != 0 {
+ t.Fatalf("pending mints %+v after a valid mint, want the promise finished", pm)
+ }
+}
+
+// TestCustomerCredentialMintGoesOnPastAHeldPromise is Task 8's carry-forward
+// (ruling C): a promise held because a live customer took its ref fails
+// only a create for that ref. Minting a credential for another customer
+// goes ahead, and the promise stays.
+func TestCustomerCredentialMintGoesOnPastAHeldPromise(t *testing.T) {
+ fx, p, tok, cust := customerWorld(t, "free")
+ ctx := context.Background()
+ if err := fx.st.ReservePlatformMint(ctx, PendingMint{MintID: strings.Repeat("ab", 16), Platform: p.Sqid,
+ Ref: "4900", Name: "held", By: "service:" + p.Sqid + "/cms", CreatedAt: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+ holder := testAccountID()
+ if _, err := fx.st.EnsureLinkedAccount(holder, domains.Sqid(holder), "holder", p.Sqid, "4900",
+ strings.Repeat("cd", 16), time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ raw := tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, tok, map[string]any{"role": "publish"}))
+ if status := appsStatus(t, fx, raw); status != http.StatusOK {
+ t.Fatalf("credential minted beside a held promise = %d, want 200", status)
+ }
+ if pm := pendingMints(t, fx.st, p.Sqid); len(pm) != 1 || pm[0].Ref != "4900" {
+ t.Fatalf("pending mints %+v, want the held 4900 promise kept", pm)
+ }
+}
+
+func TestUnknownTokenKindStillRefused(t *testing.T) {
+ s := openTestStore(t)
+ p := mustAccount(t, s, "bcd")
+ gen := grantPlatformGen(t, s, p.ID)
+ other := mustAccount(t, s, "bcf")
+ grantPlatformGen(t, s, other.ID)
+ reserveMint(t, s, "bcd", "aa11", "4812")
+ c := customerOf("bcd", "bdf", "4812", "aa11")
+ if err := s.CreateLinkedAccount(context.Background(), c, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ later := time.Now().Add(time.Hour).Unix()
+ // The well-formed row resolves, so each variant below is refused for
+ // its one difference.
+ insertTokenRow(t, s, "customer-ok", cliKindPlatform, c.ID, "", string(svcrole.Publish), later, p.ID, gen)
+ if pr, ok := s.CLIPrincipal("customer-ok", time.Now()); !ok || pr.Platform != "bcd" || pr.AccountID != c.ID {
+ t.Fatalf("well-formed customer row = %+v %v, want it to resolve", pr, ok)
+ }
+ for _, row := range []struct {
+ what, kind, app, role string
+ account, expires int64
+ platform, gen int64
+ }{
+ {"an unknown kind", "platform2", "", string(svcrole.Publish), c.ID, later, p.ID, gen},
+ {"no expiry", cliKindPlatform, "", string(svcrole.Publish), c.ID, 0, p.ID, gen},
+ {"the platform role", cliKindPlatform, "", string(svcrole.Platform), c.ID, later, p.ID, gen},
+ {"the admin role", cliKindPlatform, "", string(svcrole.Admin), c.ID, later, p.ID, gen},
+ {"deploy with no rungs", cliKindPlatform, "x", string(svcrole.Deploy), c.ID, later, p.ID, gen},
+ {"publish on an app", cliKindPlatform, "x", string(svcrole.Publish), c.ID, later, p.ID, gen},
+ {"another platform", cliKindPlatform, "", string(svcrole.Publish), c.ID, later, other.ID, 1},
+ {"bound to the platform itself", cliKindPlatform, "", string(svcrole.Publish), p.ID, later, p.ID, gen},
+ {"no generation", cliKindPlatform, "", string(svcrole.Publish), c.ID, later, p.ID, 0},
+ {"a later generation", cliKindPlatform, "", string(svcrole.Publish), c.ID, later, p.ID, gen + 1},
+ {"no platform", cliKindPlatform, "", string(svcrole.Publish), c.ID, later, 0, 0},
+ } {
+ raw := "customer-" + strings.ReplaceAll(row.what, " ", "-")
+ insertTokenRow(t, s, raw, row.kind, row.account, row.app, row.role, row.expires, row.platform, row.gen)
+ if pr, ok := s.CLIPrincipal(raw, time.Now()); ok {
+ t.Errorf("customer row with %s resolved to %+v", row.what, pr)
+ }
+ }
+}
+
+func TestPersonalTokenListOmitsCustomerCredentials(t *testing.T) {
+ fx, p, _, cust := customerWorld(t, "free")
+ addr := "owner" + p.Sqid + "@example.com"
+ owner := cliToken(t, fx, addr, "code-customer-cred-list")
+ raw := tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, owner, map[string]any{"role": "publish"}))
+ var address, name string
+ if err := fx.st.db.QueryRowContext(context.Background(), `SELECT address, name FROM cli_tokens WHERE token_hash = ?`,
+ hashToken(raw)).Scan(&address, &name); err != nil {
+ t.Fatal(err)
+ }
+ if address != addr || name != addr {
+ t.Fatalf("person-minted row address %q name %q, want %q", address, name, addr)
+ }
+ if pr, ok := fx.st.CLIPrincipal(raw, time.Now()); !ok || auditActor(pr, cust) != "platform:"+p.Sqid+"/"+addr {
+ t.Fatalf("person-minted credential = %+v %v", pr, ok)
+ }
+ tokens, err := fx.st.CLITokens(addr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(tokens) != 1 || tokens[0].ID != hashToken(owner) {
+ t.Fatalf("CLITokens(%s) = %+v, want the person's own terminal alone", addr, tokens)
+ }
+}
+
+// The Task 4 carry: under the armed claim gate, a Deploy per-customer
+// credential minted through the store (an app-bound row, written under the
+// app's permit) is swept by the grant's revoke, and the revoke succeeds.
+func TestCustomerCredentialUnderTheGateIsSweptByARevoke(t *testing.T) {
+ s, _, _ := sqlIngestFixture(t)
+ ctx := context.Background()
+ p := newPlatform(t, s, "bcd")
+ grantPlatform(t, s, p)
+ // Account 7 (bab, holding blog) becomes the platform's customer.
+ if _, err := s.db.ExecContext(ctx, `UPDATE accounts SET platform = 'bcd', platform_ref = 'census' WHERE id = ?`, gateAcct); err != nil {
+ t.Fatal(err)
+ }
+ platformTok, err := s.NewServicePrincipal(p, "cms", "", svcrole.Platform, "owner-bcd@example.com", platformNow)
+ if err != nil {
+ t.Fatal(err)
+ }
+ minter, ok := s.CLIPrincipal(platformTok, time.Now())
+ if !ok {
+ t.Fatal("platform credential does not resolve")
+ }
+ now := time.Now()
+ raw, _, err := s.NewPlatformCustomerCredential(ctx, PlatformCredentialRequest{CustomerID: gateAcct, PlatformAccountID: p,
+ Generation: minter.PlatformGeneration, Minter: minter, Name: "cms", MintedBy: "service:bcd/cms", Role: svcrole.Deploy,
+ App: "blog", Rungs: []string{"edge"}}, now)
+ if err != nil {
+ t.Fatalf("gated mint: %v", err)
+ }
+ if pr, ok := s.CLIPrincipal(raw, now); !ok || pr.App != "blog" || pr.Platform != "bcd" {
+ t.Fatalf("gated customer credential = %+v %v", pr, ok)
+ }
+ revokeAt := now.Add(time.Minute)
+ n, err := s.RevokePlatformGrant(ctx, p, "operator@example.com", "ended", revokeAt)
+ if err != nil || n != 2 {
+ t.Fatalf("RevokePlatformGrant under the gate = %d, %v; want 2 (cms and the customer credential), nil", n, err)
+ }
+ if at := tokenRevokedAt(t, s, hashToken(raw)); at != revokeAt.Unix() {
+ t.Fatalf("customer credential revoked_at = %d, want %d", at, revokeAt.Unix())
+ }
+ if pr, ok := s.CLIPrincipal(raw, revokeAt); ok {
+ t.Fatalf("swept customer credential resolved to %+v", pr)
+ }
+}
diff --git a/internal/console/platform_seams.go b/internal/console/platform_seams.go
index 9571d1755..e87276a65 100644
--- a/internal/console/platform_seams.go
+++ b/internal/console/platform_seams.go
@@ -32,6 +32,11 @@ type platformSeams struct {
// update door after its operator-row pre-check and before the plan
// change, with no lock held: a test may assign an operator's plan there.
updateBeforePlan func()
+ // platformCredentialBeforeInsert, when set (tests only), is called by
+ // the per-customer credential door after its checks (and after it has
+ // finished pending mints), before the mint's insert transaction
+ // begins, with no lock held: a test may revoke or re-grant there.
+ platformCredentialBeforeInsert func()
}
// platformStep runs the platformMintStep seam, if one is set.
diff --git a/internal/console/platform_store.go b/internal/console/platform_store.go
index 219dc9acf..61f327e0c 100644
--- a/internal/console/platform_store.go
+++ b/internal/console/platform_store.go
@@ -293,9 +293,9 @@ func (s *Store) RevokePlatformGrant(ctx context.Context, accountID int64, by, re
// kind 'platform' is a per-customer credential (bound to the customer's
// account_id, its platform in platform_account_id); a platform-role
// service credential is bound to the platform's own account_id.
- const platformCreds = `revoked_at = 0 AND ((kind = 'platform' AND platform_account_id = ?)
+ const platformCreds = `revoked_at = 0 AND ((kind = ? AND platform_account_id = ?)
OR (kind = ? AND role = ? AND account_id = ?))`
- args := []any{accountID, cliKindService, string(svcrole.Platform), accountID}
+ args := []any{cliKindPlatform, accountID, cliKindService, string(svcrole.Platform), accountID}
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM cli_tokens WHERE `+platformCreds+`
AND (expires_at = 0 OR expires_at > ?)`, append(args, now.Unix())...).Scan(&credentials); err != nil {
return 0, err
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index ea82cbf93..beaa8e46e 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -760,7 +760,8 @@ var routeDecls = []routeDecl{
// door's whole gate once, then the read inside the same request.
{Pattern: "POST /api/cli/apps/{account}/{app}/db/{host}/reads", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIDBRead},
// The zero Set, deliberately: a credential may never mint a credential,
- // including itself. This is the escalation cut (spec §3). It takes no
+ // including itself (the one exception and its limits: AGENTS.md, "Rules
+ // this repo has paid for"). This is the escalation cut (spec §3). It takes no
// authority away — handleAPIInstanceToken gates on apiAccountApp, which
// has never been able to see a non-person at all — it moves the refusal
// out to the wrapper, where it is structural, and changes the ANSWER a
@@ -932,7 +933,9 @@ var routeDecls = []routeDecl{
// The service-credential API (apiservices.go, issue #220) — the
// principal that is not an address. Every door here takes the ZERO role
// set: a credential may never mint, rotate or revoke a credential,
- // including itself, which is what keeps a publish credential from
+ // including itself (the one exception, the platform door's per-customer
+ // mint, and its limits: AGENTS.md, "Rules this repo has paid for"),
+ // which is what keeps a publish credential from
// quietly becoming an admin one. Owner-gated inside, because minting is
// an authority grant that outlives its minter.
//
@@ -956,6 +959,17 @@ var routeDecls = []routeDecl{
{Pattern: "GET /api/cli/platform/{account}/customers", Kind: kindCLI, Allow: svcrole.Exactly(svcrole.Platform), Handler: (*Server).handlePlatformCustomerList},
{Pattern: "GET /api/cli/platform/{account}/customers/{customer}", Kind: kindCLI, Allow: svcrole.Exactly(svcrole.Platform), Handler: (*Server).handlePlatformCustomerShow},
{Pattern: "PATCH /api/cli/platform/{account}/customers/{customer}", Kind: kindCLI, Allow: svcrole.Exactly(svcrole.Platform), Handler: (*Server).handlePlatformCustomerUpdate},
+ // A per-customer credential (apiplatformcredentials.go, platform
+ // accounts spec §6.2): a credential mint reached by a credential, the
+ // one exception to "a credential may never mint a credential" (AGENTS.md,
+ // "Rules this repo has paid for"). What it mints is bounded, though not
+ // narrower than its minter: it can create apps and deploy in that
+ // account, which the platform role cannot. Its bounds: one
+ // customer account linked to this platform; Publish on it, or Deploy on
+ // one of its apps; at most 24 hours; refused on every request once the
+ // link or the grant generation ends; and its roles reach no mint door,
+ // this one included (TestCustomerCredentialNeverReachesPersonOrMintDoors).
+ {Pattern: "POST /api/cli/platform/{account}/customers/{customer}/credentials", Kind: kindCLI, Allow: svcrole.Exactly(svcrole.Platform), Handler: (*Server).handlePlatformCredentialMint},
// Placement lives under the apps family, not fleets: its subject is an
// APP, and a target fleet name is only ever the request body's data.
{Pattern: "POST /api/cli/apps/{account}/{app}/place", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIPlace},
diff --git a/internal/console/svcprincipal.go b/internal/console/svcprincipal.go
index 407135680..ec8448108 100644
--- a/internal/console/svcprincipal.go
+++ b/internal/console/svcprincipal.go
@@ -154,18 +154,29 @@ FROM cli_tokens WHERE token_hash = ?`, hash).
// expiry rule. A kind that never expires is a decision each minter
// makes; inheriting it by accident would turn any user row that ever
// carried 0 into an immortal credential.
- if kind == cliKindUser {
+ //
+ // For a per-customer platform credential (kind platform), 0 is refused
+ // too: it is always minted with an expiry, and a row without one is not
+ // a row this console wrote, never one that lives forever.
+ switch kind {
+ case cliKindUser:
if now.Unix() > expires {
return Principal{}, false
}
- } else if !(expires == 0 || now.Unix() <= expires) {
- return Principal{}, false
+ case cliKindPlatform:
+ if expires == 0 || now.Unix() > expires {
+ return Principal{}, false
+ }
+ default:
+ if !(expires == 0 || now.Unix() <= expires) {
+ return Principal{}, false
+ }
}
- // Only a platform credential carries a platform: on any other row the
- // columns are a row this console did not write, and reading past them
- // would let a row claim a platform's authority by a column nothing
- // checks.
- isPlatformRow := kind == cliKindService && role == string(svcrole.Platform)
+ // Only a platform credential and a per-customer credential carry a
+ // platform: on any other row the columns are a row this console did not
+ // write, and reading past them would let a row claim a platform's
+ // authority by a column nothing checks.
+ isPlatformRow := (kind == cliKindService && role == string(svcrole.Platform)) || kind == cliKindPlatform
if !isPlatformRow && (platformAccountID != 0 || platformGeneration != 0) {
return Principal{}, false
}
@@ -242,6 +253,12 @@ FROM cli_tokens WHERE token_hash = ?`, hash).
}
p.PlatformAccountID, p.Platform, p.PlatformGeneration = platformAccountID, sqid, platformGeneration
}
+ case cliKindPlatform:
+ var ok bool
+ if p, ok = s.platformCustomerPrincipal(ctx, addr, accountID, app, role, name, rungs, credID, commands, teamScope,
+ platformAccountID, platformGeneration); !ok {
+ return Principal{}, false
+ }
case cliKindLink:
// A link credential is its link's current credential or nothing:
// the links row must be live, in the same account, and hold this
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 024122077..e90a3a933 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -83,6 +83,14 @@ import (
// at a binary of its choosing, which is not a wider version of any workload's
// authority — it is the end of the boundary the roles are drawn inside. One
// substring covers all eight doors, and no role may ever reach any of them.
+//
+// The one exception to "a credential never mints a credential" is not in
+// mintDoors on purpose: the platform door POST
+// /api/cli/platform/{account}/customers/{customer}/credentials, which only
+// the platform role reaches (AGENTS.md, "Rules this repo has paid for",
+// names it and its limits). Its pin is
+// TestCustomerCredentialNeverReachesPersonOrMintDoors: what it mints reaches
+// none of these doors, nor itself.
var (
mintDoors = []string{"/instance-token", "/door-keys", "/api/cli/services/", "/email/credentials"}
fleetDoors = []string{"/api/cli/fleets/"}
@@ -131,7 +139,8 @@ var closedDoors = []string{
// operator-only. It closes the console to legacy record work.
"POST /api/cli/system/lifetimes/cutover",
// A credential may never mint a credential, including itself. This is
- // the escalation cut of spec §3.
+ // the escalation cut of spec §3 (the one exception and its limits:
+ // AGENTS.md, "Rules this repo has paid for").
"POST /api/cli/apps/{account}/{app}/instance-token",
// Door keys (#175 P7) are credentials too: minting one is the same cut,
// and listing and revoking them are closed with it, as the services
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index c14199680..fd62c40f0 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -267,6 +267,7 @@ route POST /api/cli/accounts/{account}/domains/purchases
route POST /api/cli/accounts/{account}/plan
route POST /api/cli/accounts/{account}/platform/revoke
route POST /api/cli/platform/{account}/customers
+route POST /api/cli/platform/{account}/customers/{customer}/credentials
route POST /api/cli/accounts/{account}/store/apply
route POST /api/cli/accounts/{account}/store/approve
route POST /api/cli/accounts/{account}/store/decline