carlos / platform Public

console: usage review R1: linked reads, rotation switch, CLI help

The usage door is linkedAllow: it reads this console's own count objects.
Both rotate doors refuse a stored usage credential while
CONSOLE_INSTANCE_USAGE is off (G2; the browser before the passkey), and
the original secret keeps working. The services help, the create usage
line and the --role flag help name usage; a test holds each list to the
catalogue less today's deliberate omissions.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 928e5f8cab0d06e6ef2085e6ba1ce71534f5b48d parent 3acdc08
8 files changed, +197 −6
  • internal/console/apilinks_test.go +3 −0
  • internal/console/apiservices.go +12 −0
  • internal/console/linkedpolicy.go +3 −1
  • internal/console/svcpage.go +11 −0
  • internal/console/svcprincipal.go +27 −0
  • internal/console/usagerole_test.go +82 −0
  • services.go +12 −5
  • services_roles_help_test.go +47 −0
diff --git a/internal/console/apilinks_test.go b/internal/console/apilinks_test.go
index 49320454b..731cedbd5 100644
--- a/internal/console/apilinks_test.go
+++ b/internal/console/apilinks_test.go
@@ -666,6 +666,9 @@ var linkedAllowAnswers = map[string]int{
"GET /api/cli/apps/{account}/{app}/analytics": http.StatusOK,
// The fixture deployment has no GeoIP database: the door's own answer.
"GET /api/cli/apps/{account}/{app}/geo": http.StatusServiceUnavailable,
+ // The usage read's placeholder answers 501 past its gates until the
+ // read lands (instance usage Task 6).
+ "GET /api/cli/apps/{account}/{app}/usage": http.StatusNotImplemented,
// Paul's ruling (2026-11-10): the hub applies these to a link's forward
// row, so they stay editable; each redirects back with its flash.
"POST /a/{sqid}/apps/{app}/analytics/setting": http.StatusSeeOther,
diff --git a/internal/console/apiservices.go b/internal/console/apiservices.go
index 8d002a756..fd056e1b9 100644
--- a/internal/console/apiservices.go
+++ b/internal/console/apiservices.go
@@ -777,6 +777,18 @@ func (s *Server) handleAPIServiceRotate(w http.ResponseWriter, r *http.Request)
return
}
name := h.name
+ // The usage switch holds for a fresh secret as it does for a mint:
+ // off, a stored usage credential is not rotated (instance usage
+ // design §12).
+ if err := s.usageRotateRefusal(r.Context(), acct.ID, name); err != nil {
+ if errors.Is(err, ErrUsageOff) {
+ jsonError(w, http.StatusBadRequest, usageCopyOff)
+ return
+ }
+ log.Printf("console: service rotate %s/%s: %v", acct.Sqid, name, err)
+ jsonError(w, http.StatusInternalServerError, "could not rotate the credential — try again")
+ return
+ }
var secret string
err := s.serviceCredentialWrite(r.Context(), acct, h, "sql.RotateServicePrincipal", func(st *Store) error {
var err error
diff --git a/internal/console/linkedpolicy.go b/internal/console/linkedpolicy.go
index 9309cec86..930bf871b 100644
--- a/internal/console/linkedpolicy.go
+++ b/internal/console/linkedpolicy.go
@@ -69,6 +69,9 @@ var linkedPolicies = map[string]linkedPolicy{
"GET /apps/{app}": linkedAllow,
"GET /api/cli/apps/{account}/{app}/analytics": linkedAllow,
"GET /api/cli/apps/{account}/{app}/geo": linkedAllow,
+ // The usage read (instance usage design §8) reads this console's own
+ // count objects, never the instances at home.
+ "GET /api/cli/apps/{account}/{app}/usage": linkedAllow,
// Plan 1's app-scoped buy routes only redirect to the account's
// (appdomainbuy.go): they depend on membership and a purchase's
@@ -193,7 +196,6 @@ var linkedPolicies = map[string]linkedPolicy{
"GET /api/cli/apps/{account}/{app}/edge-refs/{code}": linkedRefuse,
"GET /api/cli/apps/{account}/{app}/errors": linkedRefuse,
"GET /api/cli/apps/{account}/{app}/availability": linkedRefuse,
- "GET /api/cli/apps/{account}/{app}/usage": linkedRefuse, // per instance; a linked app's instances live at home
"PUT /api/cli/apps/{account}/{app}/telemetry": linkedRefuse,
"GET /api/cli/apps/{account}/{app}/telemetry": linkedRefuse,
"POST /api/cli/apps/{account}/{app}/instances": linkedRefuse,
diff --git a/internal/console/svcpage.go b/internal/console/svcpage.go
index 7b9573b18..640508878 100644
--- a/internal/console/svcpage.go
+++ b/internal/console/svcpage.go
@@ -498,6 +498,17 @@ func (s *Server) handleServiceRotatePage(w http.ResponseWriter, r *http.Request)
back("err", "That is not a credential this account can rotate. Nothing was rotated.")
return
}
+ // The usage switch, before the passkey as every refusal here is: off,
+ // a stored usage credential is not rotated.
+ if err := s.usageRotateRefusal(r.Context(), acct.ID, name); err != nil {
+ if errors.Is(err, ErrUsageOff) {
+ back("err", usageCopyOff)
+ return
+ }
+ log.Printf("console: service rotate %s/%s: %v", acct.Sqid, name, err)
+ back("err", "Could not rotate the credential — try again.")
+ return
+ }
if !s.requireFreshAuth(w, r, addr, raw) {
return
}
diff --git a/internal/console/svcprincipal.go b/internal/console/svcprincipal.go
index ba4ebf686..b02770f96 100644
--- a/internal/console/svcprincipal.go
+++ b/internal/console/svcprincipal.go
@@ -320,6 +320,33 @@ func (s *Server) usageMintRefusal(role svcrole.Role) error {
return nil
}
+// usageRotateRefusal is usageMintRefusal for a rotation: a fresh secret
+// for a stored usage credential is issued only while the switch is on.
+// It reads the stored row's role, not anything in the request. ErrUsageOff
+// for a live usage credential named name while the switch is off; a store
+// error otherwise, so a failed read refuses rather than rotates; nil when
+// the switch is on or no live credential has that name (the rotate then
+// answers its own not-found).
+func (s *Server) usageRotateRefusal(ctx context.Context, accountID int64, name string) error {
+ if s.cfg.InstanceUsage {
+ return nil
+ }
+ var role string
+ err := s.store.db.QueryRowContext(ctx, `SELECT role FROM cli_tokens
+WHERE kind = ? AND account_id = ? AND name = ? AND name != '' AND revoked_at = 0`,
+ cliKindService, accountID, name).Scan(&role)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("console: read the role of %q: %w", name, err)
+ }
+ if role == string(svcrole.Usage) {
+ return ErrUsageOff
+ }
+ return nil
+}
+
// ErrAccountScopedDeploy is a deploy credential minted without an app.
var ErrAccountScopedDeploy = errors.New("console: a deploy credential must be bound to one app")
diff --git a/internal/console/usagerole_test.go b/internal/console/usagerole_test.go
index 2795f4fb1..75c449d77 100644
--- a/internal/console/usagerole_test.go
+++ b/internal/console/usagerole_test.go
@@ -200,3 +200,85 @@ func TestServicesFormNeverListsUsage(t *testing.T) {
}
}
}
+
+// TestRotateUsageRefusedWhileSwitchOff: a usage credential minted while
+// the switch was on gets no fresh secret once it is off, at either rotate
+// door, and its secret still works. The refusal reads the stored role: an
+// operate credential rotates as before, and with the switch on a usage
+// credential rotates too.
+func TestRotateUsageRefusedWhileSwitchOff(t *testing.T) {
+ fx := usageFixture(t, false)
+ meter := serviceToken(t, fx.st, OpsAccountID, "meter", "kass", svcrole.Usage)
+ owner := cliToken(t, fx, "paul@keymail.dev", "code-usage-rotate")
+ stillWorks := func(why string) {
+ t.Helper()
+ if p, ok := fx.st.CLIPrincipal(meter, time.Now()); !ok || p.Role != svcrole.Usage {
+ t.Fatalf("%s: the original secret = %+v %v, want it to authenticate unchanged", why, p, ok)
+ }
+ }
+
+ status, body := postRaw(t, fx.ts.URL+"/api/cli/services/"+fx.sqid+"/meter/rotate", map[string]string{}, owner)
+ if status != http.StatusBadRequest || jsonField(t, body, "error") != usageCopyOff {
+ t.Errorf("API rotate = %d %s, want 400 %q", status, body, usageCopyOff)
+ }
+ stillWorks("API rotate")
+
+ b := signInPaul(t, fx)
+ csrf := sessionToken(t, fx, b)
+ status, loc, page := postForm(t, b, fx.u("/services/rotate"), url.Values{"csrf": {csrf}, "name": {"meter"}})
+ if strings.HasPrefix(loc, fx.fk.srv.URL) {
+ t.Errorf("the browser refusal cost a passkey trip (-> %q)", loc)
+ }
+ if status != http.StatusSeeOther || loc != fx.path("/settings") {
+ t.Fatalf("browser rotate = %d -> %q, want 303 back to the page:\n%s", status, loc, page)
+ }
+ if _, _, page := get(t, b, fx.u("/settings")); !strings.Contains(page, usageCopyOff) {
+ t.Errorf("the settings page does not say %q", usageCopyOff)
+ }
+ stillWorks("browser rotate")
+
+ // Another role rotates with the switch off.
+ serviceToken(t, fx.st, OpsAccountID, "ops", "kass", svcrole.Operate)
+ if status, body := postRaw(t, fx.ts.URL+"/api/cli/services/"+fx.sqid+"/ops/rotate", map[string]string{}, owner); status != http.StatusOK {
+ t.Errorf("operate rotate with the switch off = %d %s, want 200", status, body)
+ }
+
+ // With the switch on, the usage credential rotates.
+ on := usageFixture(t, true)
+ old := serviceToken(t, on.st, OpsAccountID, "meter", "kass", svcrole.Usage)
+ onOwner := cliToken(t, on, "paul@keymail.dev", "code-usage-rotate-on")
+ if status, body := postRaw(t, on.ts.URL+"/api/cli/services/"+on.sqid+"/meter/rotate", map[string]string{}, onOwner); status != http.StatusOK {
+ t.Fatalf("usage rotate with the switch on = %d %s, want 200", status, body)
+ }
+ if _, ok := on.st.CLIPrincipal(old, time.Now()); ok {
+ t.Error("the rotated-away secret still authenticates")
+ }
+}
+
+// TestLinkedAppReachesTheUsageDoor: the usage read is this console's own
+// count objects, so a member reading a linked app's usage gets past the
+// linked-app guard, where the logs read beside it is refused.
+func TestLinkedAppReachesTheUsageDoor(t *testing.T) {
+ fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, Tweak: func(c *Config) {
+ c.TunnelHost = "tunnel.example.com"
+ c.AppsDomain = "apps.example.com"
+ c.InstanceUsage = true
+ }})
+ acct := linkOpsAccount(t, fx)
+ linkToken := mintWalkLinkIn(t, fx.st, acct.ID)
+ p, _ := fx.st.CLIPrincipal(linkToken, time.Now())
+ if _, err := fx.st.CreateLinkedApp(acct.ID, "shop", "link:"+fx.sqid+"/"+p.LinkID, p.LinkID, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ refusal := linkCopy(copyLD11, "app", "shop", "home", "walk-home")
+ member := mintWalkPerson(t, fx.st)
+ status, body := getRaw(t, usageURL(fx, "shop"), member)
+ if status == http.StatusConflict || linkJSONErr(body) == refusal ||
+ status == http.StatusNotFound || status == http.StatusUnauthorized || status == http.StatusForbidden {
+ t.Errorf("member at a linked app's usage door = %d %s, want past the gates and the linked guard", status, body)
+ }
+ status, body = getRaw(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/shop/logs", member)
+ if status != http.StatusConflict || linkJSONErr(body) != refusal {
+ t.Errorf("member at a linked app's logs door = %d %s, want the linked refusal", status, body)
+ }
+}
diff --git a/services.go b/services.go
index 56a85fa96..93ad40c8e 100644
--- a/services.go
+++ b/services.go
@@ -34,7 +34,7 @@ import (
const servicesUsage = `usage: carlos services <create|ls|rotate|revoke> [flags]
- create --role <publish|deploy|instance|operate|service|run|admin> [--app <app>] [--account <sqid|name>] [--json] <name>
+ create --role <publish|deploy|instance|operate|service|run|usage|admin> [--app <app>] [--account <sqid|name>] [--json] <name>
mint a credential a SERVER holds, bound to this account —
not to you. Unlike your own CLI token, its reach is fixed
at mint: adding you to another account later does not widen
@@ -168,9 +168,18 @@ func validServiceHandle(handle string) error {
"a name (1-32 characters of a-z, 0-9 and hyphen) or a 64-character hex id", handle)
}
+// servicesCreateRoleHelp and servicesCreateUsage are the --role flag's
+// help and create's usage line, at package level so a test can read the
+// role lists they name (TestServicesHelpNamesEveryRole).
+const (
+ servicesCreateRoleHelp = "role: publish, deploy, instance, operate, service, run, team, usage or admin (required)"
+ servicesCreateUsage = "usage: carlos services create --role <publish|deploy|instance|operate|service|run|team|usage|admin> [--app <app>] " +
+ "[--rungs <list>] [--commands <list>] [--scope <name>] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>] [--json] <name>"
+)
+
func runServicesCreate(args []string) {
fs := flag.NewFlagSet("services create", flag.ExitOnError)
- role := fs.String("role", "", "role: publish, deploy, instance, operate, service, run, team or admin (required)")
+ role := fs.String("role", "", servicesCreateRoleHelp)
app := appFlag(fs, "bind the credential to one app (default: account-wide)")
rungsRaw := fs.String("rungs", "", "rungs a deploy credential may move, comma-separated: canary, edge, beta (required with --role deploy)")
commandsRaw := fs.String("commands", "", `command prefixes a run credential may run, comma-separated, words space-separated: "import classic,import sync" (required with --role run)`)
@@ -181,10 +190,8 @@ func runServicesCreate(args []string) {
asJSON := fs.Bool("json", false, "print the credential and its bare secret as one JSON object, for a script")
fs.Usage = flagUsage(fs, "")
fs.Parse(args)
- const usageMsg = "usage: carlos services create --role <publish|deploy|instance|operate|service|run|team|admin> [--app <app>] " +
- "[--rungs <list>] [--commands <list>] [--scope <name>] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>] [--json] <name>"
if fs.NArg() != 1 || strings.TrimSpace(*role) == "" {
- log.Fatal(usageMsg)
+ log.Fatal(servicesCreateUsage)
}
name := strings.TrimSpace(fs.Arg(0))
if err := validServiceName(name); err != nil {
diff --git a/services_roles_help_test.go b/services_roles_help_test.go
new file mode 100644
index 000000000..6138e98ed
--- /dev/null
+++ b/services_roles_help_test.go
@@ -0,0 +1,47 @@
+package main
+
+import (
+ "regexp"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// TestServicesHelpNamesEveryRole: each role list the services help prints
+// names every role in the catalogue, but for the roles each list leaves
+// out on purpose today: platform everywhere (platform access is minted for
+// a platform account, not offered here), and team in the top-level summary.
+// A role added to svcrole and not to the help fails here.
+func TestServicesHelpNamesEveryRole(t *testing.T) {
+ bracket := regexp.MustCompile(`--role <([a-z|]+)>`)
+ fromBracket := func(text string) []string {
+ m := bracket.FindStringSubmatch(text)
+ if m == nil {
+ t.Fatalf("no --role <...> list in %q", text)
+ }
+ return strings.Split(m[1], "|")
+ }
+ flag := strings.TrimSuffix(strings.TrimPrefix(servicesCreateRoleHelp, "role: "), " (required)")
+ flagRoles := strings.Split(strings.ReplaceAll(flag, " or ", ", "), ", ")
+ for _, c := range []struct {
+ name string
+ listed []string
+ omitted []svcrole.Role
+ }{
+ {"services help", fromBracket(servicesUsage), []svcrole.Role{svcrole.Team, svcrole.Platform}},
+ {"create usage line", fromBracket(servicesCreateUsage), []svcrole.Role{svcrole.Platform}},
+ {"--role flag help", flagRoles, []svcrole.Role{svcrole.Platform}},
+ } {
+ var want []string
+ for _, r := range svcrole.All() {
+ if !slices.Contains(c.omitted, r) {
+ want = append(want, string(r))
+ }
+ }
+ if !slices.Equal(c.listed, want) {
+ t.Errorf("%s lists %v, want %v", c.name, c.listed, want)
+ }
+ }
+}