console: a usage role and its one switched door
svcrole.Usage sits after Platform, outside Admin's union; Allow panics on
it. Its one door, GET /api/cli/apps/{account}/{app}/usage, is registered
through Exactly(Usage, Instance, Operate, Admin) behind gateInstanceUsage
(CONSOLE_INSTANCE_USAGE == "true"), with a 501 placeholder behind the
instance gate until Task 6. The store refuses a usage mint with no app
(G1) and the resolver fails closed on such a row; both mint doors refuse
the role while the switch is off (G2). The browser form never lists it.
The linked-app guard refuses the door.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
16 files changed,
+633
−31
cmd/console/instanceusage_test.go+89 −0cmd/console/main.go+10 −0internal/console/apilinks_test.go+1 −0internal/console/apiservices.go+9 −0internal/console/apiusage.go+13 −0internal/console/linkedpolicy.go+1 −0internal/console/platform_credentials_test.go+20 −0internal/console/routedecls.go+12 −1internal/console/routedecls_test.go+2 −1internal/console/server.go+5 −0internal/console/svcpage.go+18 −2internal/console/svcprincipal.go+37 −0internal/console/svcroutes_test.go+133 −16internal/console/usagerole_test.go+202 −0internal/svcrole/svcrole.go+23 −8internal/svcrole/svcrole_test.go+58 −3
Intent
diff --git a/cmd/console/instanceusage_test.go b/cmd/console/instanceusage_test.go| new file mode 100644 |
| index 000000000..9c5b1468b |
| --- /dev/null |
| +++ b/cmd/console/instanceusage_test.go |
| @@ -0,0 +1,89 @@ |
| +package main |
| + |
| +import ( |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/console" |
| +) |
| + |
| +// CONSOLE_INSTANCE_USAGE reaches console.Config.InstanceUsage through |
| +// applyInstanceUsageSwitch: exactly "true" turns it on, anything else |
| +// leaves it off. |
| +func TestApplyInstanceUsageSwitchSetsTheConfigField(t *testing.T) { |
| + for _, tc := range []struct { |
| + val string |
| + want bool |
| + }{ |
| + {"true", true}, {"", false}, {"1", false}, {"on", false}, {"TRUE", false}, {" true", false}, {"false", false}, |
| + } { |
| + cfg := console.Config{InstanceUsage: !tc.want} |
| + applyInstanceUsageSwitch(&cfg, func(k string) string { |
| + if k != "CONSOLE_INSTANCE_USAGE" { |
| + t.Fatalf("read %q, want only CONSOLE_INSTANCE_USAGE", k) |
| + } |
| + return tc.val |
| + }) |
| + if cfg.InstanceUsage != tc.want { |
| + t.Errorf("CONSOLE_INSTANCE_USAGE=%q: InstanceUsage = %v, want %v", tc.val, cfg.InstanceUsage, tc.want) |
| + } |
| + } |
| +} |
| + |
| +// serve() calls applyInstanceUsageSwitch(&X, os.Getenv) once, before |
| +// console.NewServer(X, ...): the moves switch's wiring check. |
| +func TestServeAppliesTheInstanceUsageSwitchFromTheEnvironment(t *testing.T) { |
| + f, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var serve *ast.FuncDecl |
| + for _, d := range f.Decls { |
| + if fn, ok := d.(*ast.FuncDecl); ok && fn.Name.Name == "serve" { |
| + serve = fn |
| + } |
| + } |
| + if serve == nil { |
| + t.Fatal("no serve() in main.go") |
| + } |
| + var applies, news []*ast.CallExpr |
| + ast.Inspect(serve.Body, func(n ast.Node) bool { |
| + call, ok := n.(*ast.CallExpr) |
| + if !ok { |
| + return true |
| + } |
| + switch fun := call.Fun.(type) { |
| + case *ast.Ident: |
| + if fun.Name == "applyInstanceUsageSwitch" { |
| + applies = append(applies, call) |
| + } |
| + case *ast.SelectorExpr: |
| + if isIdent(fun.X, "console") && fun.Sel.Name == "NewServer" { |
| + news = append(news, call) |
| + } |
| + } |
| + return true |
| + }) |
| + if len(applies) != 1 || len(news) != 1 { |
| + t.Fatalf("serve() has %d applyInstanceUsageSwitch calls and %d console.NewServer calls, want one of each", len(applies), len(news)) |
| + } |
| + apply, ns := applies[0], news[0] |
| + if len(apply.Args) != 2 || len(ns.Args) < 1 { |
| + t.Fatal("applyInstanceUsageSwitch wants (&cfg, os.Getenv) and console.NewServer wants (cfg, store)") |
| + } |
| + if sel, ok := apply.Args[1].(*ast.SelectorExpr); !ok || !isIdent(sel.X, "os") || sel.Sel.Name != "Getenv" { |
| + t.Fatal("applyInstanceUsageSwitch is not given os.Getenv") |
| + } |
| + addr, ok := apply.Args[0].(*ast.UnaryExpr) |
| + if !ok || addr.Op != token.AND { |
| + t.Fatal("applyInstanceUsageSwitch's first argument is not &X") |
| + } |
| + if x, ok := addr.X.(*ast.Ident); !ok || !isIdent(ns.Args[0], x.Name) { |
| + t.Fatal("console.NewServer is not handed the config applyInstanceUsageSwitch changed") |
| + } |
| + if apply.Pos() >= ns.Pos() { |
| + t.Fatal("applyInstanceUsageSwitch runs after console.NewServer") |
| + } |
| +} |
diff --git a/cmd/console/main.go b/cmd/console/main.go| index b3cd4b954..ccfc10413 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -731,6 +731,9 @@ func serve() { |
| // D13): applied after the literal so a test can prove it reaches the |
| // config (applyMovesSwitch). |
| applyMovesSwitch(&cfg, os.Getenv) |
| + // The instance usage switch (CONSOLE_INSTANCE_USAGE, off by default): |
| + // the usage read and the usage role's mint (applyInstanceUsageSwitch). |
| + applyInstanceUsageSwitch(&cfg, os.Getenv) |
| // The single-tenant declaration (CARLOS_DEPLOYMENT_SINGLE_TENANT, rootfs |
| // spec §5.7). A value the boxes would read differently stops the console |
| // here rather than let it allow creates every box refuses. |
| @@ -2297,6 +2300,13 @@ func applyMovesSwitch(cfg *console.Config, getenv func(string) string) { |
| cfg.MovesEnabled = moves.Enabled(getenv) |
| } |
| +// applyInstanceUsageSwitch sets console.Config.InstanceUsage from |
| +// CONSOLE_INSTANCE_USAGE (instance usage design §12): exactly "true" is on, |
| +// anything else, unset included, is off. |
| +func applyInstanceUsageSwitch(cfg *console.Config, getenv func(string) string) { |
| + cfg.InstanceUsage = getenv("CONSOLE_INSTANCE_USAGE") == "true" |
| +} |
| + |
| // singleTenantEnv is the operator's one-customer declaration (rootfs apps |
| // spec §5.7). Every box reads the same variable from its host.env |
| // (internal/host singleTenant). |
diff --git a/internal/console/apilinks_test.go b/internal/console/apilinks_test.go| index 2e60c42a4..49320454b 100644 |
| --- a/internal/console/apilinks_test.go |
| +++ b/internal/console/apilinks_test.go |
| @@ -793,6 +793,7 @@ func TestLinkedAppRefusedOnAppRoutes(t *testing.T) { |
| c.TunnelHost = "tunnel.example.com" |
| c.AppsDomain = "apps.example.com" |
| c.MovesEnabled = true |
| + c.InstanceUsage = true |
| // The email pause door is an operator's; paul is one here so the |
| // walk reaches its resolver. |
| c.MailOperators = []string{"paul@keymail.dev"} |
diff --git a/internal/console/apiservices.go b/internal/console/apiservices.go| index 5f30d8190..8d002a756 100644 |
| --- a/internal/console/apiservices.go |
| +++ b/internal/console/apiservices.go |
| @@ -308,6 +308,12 @@ func (s *Server) handleAPIServiceCreate(w http.ResponseWriter, r *http.Request) |
| "unknown role — one of: "+strings.Join(names, ", ")) |
| return |
| } |
| + // The usage switch, before anything else is read: off, the role is not |
| + // mintable here at all (instance usage design §12). |
| + if err := s.usageMintRefusal(role); err != nil { |
| + jsonError(w, http.StatusBadRequest, err.Error()) |
| + return |
| + } |
| // An app-scoped credential must name an app that is actually in this |
| // account. Otherwise the mint succeeds against nothing, and the day |
| // somebody creates an app of that name the credential silently acquires |
| @@ -366,6 +372,9 @@ func (s *Server) handleAPIServiceCreate(w http.ResponseWriter, r *http.Request) |
| return |
| } |
| switch { |
| + case errors.Is(err, ErrAccountScopedUsage): |
| + jsonError(w, http.StatusBadRequest, usageCopyNoApp) |
| + return |
| case errors.Is(err, ErrAppScopedPlatform): |
| jsonError(w, http.StatusBadRequest, platformCopy["svc.platform_app"]) |
| return |
diff --git a/internal/console/apiusage.go b/internal/console/apiusage.go| new file mode 100644 |
| index 000000000..64c61f86b |
| --- /dev/null |
| +++ b/internal/console/apiusage.go |
| @@ -0,0 +1,13 @@ |
| +package console |
| + |
| +import "net/http" |
| + |
| +// handleAPIUsage answers `carlos usage` (instance usage design §8). A |
| +// placeholder until the read lands: the instance gate (a member, or a |
| +// credential the door admits, bound to this app), then 501. |
| +func (s *Server) handleAPIUsage(w http.ResponseWriter, r *http.Request) { |
| + if _, _, _, ok := s.instanceGate(w, r); !ok { |
| + return |
| + } |
| + jsonError(w, http.StatusNotImplemented, "not implemented") |
| +} |
diff --git a/internal/console/linkedpolicy.go b/internal/console/linkedpolicy.go| index a2c13de5e..9309cec86 100644 |
| --- a/internal/console/linkedpolicy.go |
| +++ b/internal/console/linkedpolicy.go |
| @@ -193,6 +193,7 @@ 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/platform_credentials_test.go b/internal/console/platform_credentials_test.go| index 3e04484ba..fa75f29de 100644 |
| --- a/internal/console/platform_credentials_test.go |
| +++ b/internal/console/platform_credentials_test.go |
| @@ -301,6 +301,26 @@ func TestRevokedPlatformCredentialIsGoneFromManagement(t *testing.T) { |
| } |
| } |
| +// TestPlatformCredentialShapeAdmitsOnlyPublishAndDeploy: the platform door |
| +// mints Publish or Deploy and nothing else, whatever the catalogue grows |
| +// to (AGENTS.md, "A credential never mints a credential"). Every role is |
| +// tried in every shape the two admitted roles take. |
| +func TestPlatformCredentialShapeAdmitsOnlyPublishAndDeploy(t *testing.T) { |
| + for _, r := range svcrole.All() { |
| + for _, shape := range []struct { |
| + app string |
| + rungs []string |
| + }{{"", nil}, {"site", []string{"edge"}}, {"site", nil}, {"", []string{"edge"}}} { |
| + _, _, err := platformCredentialShape(r, shape.app, shape.rungs, 0) |
| + admitted := (r == svcrole.Publish && shape.app == "" && shape.rungs == nil) || |
| + (r == svcrole.Deploy && shape.app != "" && shape.rungs != nil) |
| + if (err == nil) != admitted { |
| + t.Errorf("platformCredentialShape(%q, %q, %v) = %v, want admitted=%v", r, shape.app, shape.rungs, err, admitted) |
| + } |
| + } |
| + } |
| +} |
| + |
| func TestBrowserMintFormDoesNotOfferPlatform(t *testing.T) { |
| fx := newConsoleFixture(t) |
| acct := planAccount(t, fx, 501) |
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go| index ff64343b6..c94e1648a 100644 |
| --- a/internal/console/routedecls.go |
| +++ b/internal/console/routedecls.go |
| @@ -56,11 +56,14 @@ var ( |
| gateNoHostClaim = &routeGate{"no-host-claim", func(c Config) bool { return !c.HostClaim }} |
| gateRegionHA = &routeGate{"region-ha", func(c Config) bool { return c.HostClaim && c.RegionHA }} |
| gateMoves = &routeGate{"moves", func(c Config) bool { return c.MovesEnabled }} |
| + // gateInstanceUsage is CONSOLE_INSTANCE_USAGE (instance usage design |
| + // §12): the usage read is registered only while it is on. |
| + gateInstanceUsage = &routeGate{"instance-usage", func(c Config) bool { return c.InstanceUsage }} |
| ) |
| // routeGates is every gate a declaration may carry. The equality test |
| // (TestRouteDeclsMatchRegistrations) flips each one on and off. |
| -var routeGates = []*routeGate{gateDemo, gateHostClaim, gateNoHostClaim, gateRegionHA, gateMoves} |
| +var routeGates = []*routeGate{gateDemo, gateHostClaim, gateNoHostClaim, gateRegionHA, gateMoves, gateInstanceUsage} |
| // routeDecl is one console route: everything its registration needs. |
| type routeDecl struct { |
| @@ -734,6 +737,14 @@ var routeDecls = []routeDecl{ |
| // The platform's GeoIP answer for an arbitrary address (geoip spec |
| // §11.1): the same holders as the analytics read. |
| {Pattern: "GET /api/cli/apps/{account}/{app}/geo", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Instance, svcrole.Operate), Handler: (*Server).handleAPIGeo}, |
| + // The usage read (`carlos usage`, apiusage.go; instance usage design |
| + // §8, §9): registered only while CONSOLE_INSTANCE_USAGE is on. The |
| + // analytics read's holders plus Usage, through Exactly because Usage is |
| + // outside Admin's union: this is the usage role's one door |
| + // (TestUsageDoorIsTheOnlyUsageDoor). |
| + {Pattern: "GET /api/cli/apps/{account}/{app}/usage", Kind: kindCLI, Gate: gateInstanceUsage, |
| + Allow: svcrole.Exactly(svcrole.Usage, svcrole.Instance, svcrole.Operate, svcrole.Admin), |
| + Handler: (*Server).handleAPIUsage}, |
| // The telemetry SETTINGS write, Operate only and deliberately narrower |
| // than the read beside it: this decides what counts as an error for the |
| // app's owner, and a credential the app itself holds must not be able to |
diff --git a/internal/console/routedecls_test.go b/internal/console/routedecls_test.go| index d2e5e7e50..c2c1c7716 100644 |
| --- a/internal/console/routedecls_test.go |
| +++ b/internal/console/routedecls_test.go |
| @@ -107,6 +107,7 @@ func TestRouteDeclsMatchRegistrations(t *testing.T) { |
| {"host-claim", func(t *testing.T) Config { c := base(t); c.HostClaim = true; return c }}, |
| {"host-claim-region-ha", func(t *testing.T) Config { c := base(t); c.HostClaim, c.RegionHA = true, true; return c }}, |
| {"moves", func(t *testing.T) Config { c := base(t); c.MovesEnabled = true; return c }}, |
| + {"instance-usage", func(t *testing.T) Config { c := base(t); c.InstanceUsage = true; return c }}, |
| {"demo", demoCfg}, |
| // A host-claim console refuses demos at startup (validateDemoConfig), |
| // so demos and host claims together are a demo box: gateDemo |
| @@ -171,7 +172,7 @@ func TestRouteDeclsMatchRegistrations(t *testing.T) { |
| func TestCheckDeclRegistrationRefuses(t *testing.T) { |
| h := func(*Server, http.ResponseWriter, *http.Request) {} |
| // Off and on for every gate in routeGates. |
| - flip := []Config{{}, {HostClaim: true, RegionHA: true, MovesEnabled: true, Demo: demo.Config{Enabled: true}}} |
| + flip := []Config{{}, {HostClaim: true, RegionHA: true, MovesEnabled: true, InstanceUsage: true, Demo: demo.Config{Enabled: true}}} |
| decls := []routeDecl{ |
| {Pattern: "GET /a", Handler: h}, |
| {Pattern: "GET /b", Gate: gateHostClaim, Handler: h}, |
diff --git a/internal/console/server.go b/internal/console/server.go| index a01bc8515..081dc6b1d 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -768,6 +768,11 @@ type Config struct { |
| // before Phase 1: the legacy move door answers and nothing new is |
| // reachable. |
| MovesEnabled bool |
| + // InstanceUsage is the instance usage switch (CONSOLE_INSTANCE_USAGE == |
| + // "true"; instance usage design §12). Off, the usage route is not |
| + // registered (it 404s) and both mint doors refuse the usage role; the |
| + // boxes keep counting either way. |
| + InstanceUsage bool |
| // AWSAccount (CARLOS_AWS_ACCOUNT) is the deployment's AWS account id, |
| // the trust anchor the move door checks every box's signed identity |
| // record against (boxid.Verifier.Account). Unset, no box verifies and |
diff --git a/internal/console/svcpage.go b/internal/console/svcpage.go| index 481903607..7b9573b18 100644 |
| --- a/internal/console/svcpage.go |
| +++ b/internal/console/svcpage.go |
| @@ -184,9 +184,11 @@ func (s *Server) servicePane(p *page, acct *Account) { |
| p.Services = rows |
| } |
| // Not the platform role: platform access is API and CLI only (spec |
| - // §2), and a platform credential is minted with carlos services. |
| + // §2), and a platform credential is minted with carlos services. Not |
| + // the usage role either, switch on or off: usage credentials are |
| + // minted with carlos services too (instance usage design §9). |
| for _, role := range svcrole.All() { |
| - if role == svcrole.Platform { |
| + if role == svcrole.Platform || role == svcrole.Usage { |
| continue |
| } |
| p.ServiceRoles = append(p.ServiceRoles, string(role)) |
| @@ -298,6 +300,17 @@ func (s *Server) handleServiceCreatePage(w http.ResponseWriter, r *http.Request) |
| // creates an app of that name the credential silently acquires authority |
| // over an app its minter never chose. |
| app := strings.TrimSpace(r.FormValue("app")) |
| + // The form never offers usage, but a hand-made POST meets the same two |
| + // refusals as the API door: the switch (the server's), then the app |
| + // (the store's authority, said here before the passkey trip). |
| + if err := s.usageMintRefusal(role); err != nil { |
| + back("err", usageCopyOff) |
| + return |
| + } |
| + if role == svcrole.Usage && app == "" { |
| + back("err", usageCopyNoApp) |
| + return |
| + } |
| // Said HERE as well as in NewServicePrincipal, and the duplication is |
| // deliberate rather than the thing §3.4 warns about. The store keeps the |
| // AUTHORITY — one place, so neither mint door can forget it — and this is |
| @@ -399,6 +412,9 @@ func (s *Server) handleServiceCreatePage(w http.ResponseWriter, r *http.Request) |
| // pre-checks above if one of them ever drifts. |
| var ue *UnknownRungError |
| switch { |
| + case errors.Is(err, ErrAccountScopedUsage): |
| + back("err", usageCopyNoApp) |
| + return |
| case errors.Is(err, ErrAccountScopedDeploy): |
| back("err", "A deploy credential must name one app. Nothing was minted.") |
| return |
diff --git a/internal/console/svcprincipal.go b/internal/console/svcprincipal.go| index 47980319c..ba4ebf686 100644 |
| --- a/internal/console/svcprincipal.go |
| +++ b/internal/console/svcprincipal.go |
| @@ -236,6 +236,12 @@ FROM cli_tokens WHERE token_hash = ?`, hash). |
| } else if teamScope != "" { |
| return Principal{}, false |
| } |
| + // The Run rule's twin for a usage row: it is minted bound to one |
| + // app, so one with no app is a row this console did not write, |
| + // never a credential that reads every app's usage. |
| + if r == svcrole.Usage && app == "" { |
| + return Principal{}, false |
| + } |
| p = Principal{Kind: PrincipalService, Address: addr, AccountID: accountID, App: app, Role: r, Name: name, Rungs: scope, |
| CredentialID: credID, Commands: granted, Scope: teamScope} |
| // A platform credential is its own account's, bound to no app, |
| @@ -288,6 +294,32 @@ var ErrAccountScopedService = errors.New("console: a service-role credential mus |
| // speaks for the whole platform account and is never bound to one app. |
| var ErrAppScopedPlatform = errors.New("console: a platform credential is never bound to an app") |
| +// The usage mint refusals' sentences (instance usage copy, section G), |
| +// said verbatim by both mint doors. |
| +const ( |
| + usageCopyNoApp = "A usage credential must name one app. Nothing was minted." |
| + usageCopyOff = "Usage credentials are not available on this console. Nothing was minted." |
| +) |
| + |
| +// ErrAccountScopedUsage is a usage credential minted without an app. The |
| +// store refuses it, so neither mint door can forget it. |
| +var ErrAccountScopedUsage = errors.New(usageCopyNoApp) |
| + |
| +// ErrUsageOff is a usage credential minted while CONSOLE_INSTANCE_USAGE is |
| +// off. The store has no config, so this one is the server's |
| +// (usageMintRefusal), checked by both mint doors before the store. |
| +var ErrUsageOff = errors.New(usageCopyOff) |
| + |
| +// usageMintRefusal is the switch half of the usage mint rules: ErrUsageOff |
| +// for the usage role while the switch is off, nil otherwise. Both mint |
| +// doors call it before the store. |
| +func (s *Server) usageMintRefusal(role svcrole.Role) error { |
| + if role == svcrole.Usage && !s.cfg.InstanceUsage { |
| + 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") |
| @@ -455,6 +487,11 @@ func (s *Store) claimRawNewServicePrincipalScoped(accountID int64, name, app str |
| if role == svcrole.Platform && app != "" { |
| return "", ErrAppScopedPlatform |
| } |
| + // A usage credential reads one app's usage (instance usage design §9), |
| + // so it names that app, as Deploy and Run do. |
| + if role == svcrole.Usage && app == "" { |
| + return "", ErrAccountScopedUsage |
| + } |
| canon, err := canonicalRungs(rungs) |
| if err != nil { |
| return "", err |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index ab07e9093..23e19e7fd 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -467,6 +467,87 @@ func TestRunDoorsTakeOnlyTheRunRole(t *testing.T) { |
| } |
| } |
| +// usageDoors is the intent list for the usage role (instance usage design |
| +// §9): the one door it reaches. The role is outside Admin's union and |
| +// Allow refuses it, so no later Allow(...) registration can hand a usage |
| +// credential a second door; this list says which door it has. |
| +var usageDoors = []string{ |
| + "GET /api/cli/apps/{account}/{app}/usage", |
| +} |
| + |
| +// TestUsageDoorIsTheOnlyUsageDoor: with the switch on, the only registered |
| +// door whose Set permits Usage is the usage door, and it takes exactly the |
| +// analytics read's holders plus Usage. In the source, the only declaration |
| +// naming Usage is that door's, built with Exactly: no Allow-built Set |
| +// carries it (Allow panics on it besides). |
| +func TestUsageDoorIsTheOnlyUsageDoor(t *testing.T) { |
| + s := usageFixture(t, true).srv |
| + var reach []string |
| + for pattern, set := range s.cliRoles { |
| + if set.Permits(svcrole.Usage) { |
| + reach = append(reach, pattern) |
| + } |
| + } |
| + sort.Strings(reach) |
| + if !slices.Equal(reach, usageDoors) { |
| + t.Errorf("the usage role reaches %q, want exactly %q", reach, usageDoors) |
| + } |
| + for _, pattern := range usageDoors { |
| + set, ok := s.cliRoles[pattern] |
| + if !ok { |
| + t.Errorf("%s is not registered with the switch on", pattern) |
| + continue |
| + } |
| + if got := set.Roles(); !slices.Equal(got, []svcrole.Role{svcrole.Admin, svcrole.Instance, svcrole.Operate, svcrole.Usage}) { |
| + t.Errorf("%s takes %v, want [admin instance operate usage]", pattern, got) |
| + } |
| + } |
| + fset, files := parseConsoleSource(t) |
| + lit := findRouteDecls(t, fset, files) |
| + var named []string |
| + for _, el := range lit.Elts { |
| + cl, ok := el.(*ast.CompositeLit) |
| + if !ok { |
| + continue |
| + } |
| + var pattern string |
| + var allow ast.Expr |
| + for _, e := range cl.Elts { |
| + kv, ok := e.(*ast.KeyValueExpr) |
| + if !ok { |
| + continue |
| + } |
| + switch id, _ := kv.Key.(*ast.Ident); { |
| + case id == nil: |
| + case id.Name == "Pattern": |
| + pattern, _ = stringLit(kv.Value) |
| + case id.Name == "Allow": |
| + allow = kv.Value |
| + } |
| + } |
| + if allow == nil || !mentionsIdent(allow, "Usage") { |
| + continue |
| + } |
| + named = append(named, pattern) |
| + var fun ast.Expr |
| + if call, ok := allow.(*ast.CallExpr); ok { |
| + fun = call.Fun |
| + } |
| + exactly := false |
| + if sel, ok := fun.(*ast.SelectorExpr); ok { |
| + pkg, isID := sel.X.(*ast.Ident) |
| + exactly = isID && pkg.Name == "svcrole" && sel.Sel.Name == "Exactly" |
| + } |
| + if !exactly { |
| + t.Errorf("%s at %s names Usage outside svcrole.Exactly", pattern, fset.Position(allow.Pos())) |
| + } |
| + } |
| + sort.Strings(named) |
| + if !slices.Equal(named, usageDoors) { |
| + t.Errorf("declarations naming Usage: %q, want exactly %q", named, usageDoors) |
| + } |
| +} |
| + |
| // Demo operators are recorded even without demo configuration. Host-claim |
| // consoles cannot run demos and must not register these doors. |
| var demoOperatorDoors = []string{ |
| @@ -531,11 +612,12 @@ func TestEveryCLIDoorNamesItsRoles(t *testing.T) { |
| // gateNamed maps each gate's identifier to the gate, so a declaration's |
| // Gate as the source spells it can be evaluated against a Config. |
| gateNamed := map[string]*routeGate{ |
| - "gateDemo": gateDemo, |
| - "gateHostClaim": gateHostClaim, |
| - "gateNoHostClaim": gateNoHostClaim, |
| - "gateRegionHA": gateRegionHA, |
| - "gateMoves": gateMoves, |
| + "gateDemo": gateDemo, |
| + "gateHostClaim": gateHostClaim, |
| + "gateNoHostClaim": gateNoHostClaim, |
| + "gateRegionHA": gateRegionHA, |
| + "gateMoves": gateMoves, |
| + "gateInstanceUsage": gateInstanceUsage, |
| } |
| named := map[*routeGate]bool{} |
| for _, g := range gateNamed { |
| @@ -569,6 +651,7 @@ func TestEveryCLIDoorNamesItsRoles(t *testing.T) { |
| {hostClaimDoors, "gateHostClaim"}, |
| {regionHADoors, "gateRegionHA"}, |
| {movesDoors, "gateMoves"}, |
| + {usageDoors, "gateInstanceUsage"}, |
| {demoOperatorDoors, "gateNoHostClaim"}, |
| {domainBuyDoors, "gateNoHostClaim"}, |
| {domainCertDoors, "gateNoHostClaim"}, |
| @@ -587,13 +670,16 @@ func TestEveryCLIDoorNamesItsRoles(t *testing.T) { |
| hostClaim bool |
| moves bool |
| regionHA bool |
| + usage bool |
| }{ |
| - {"flag-off", false, false, false}, |
| - {"flag-on", true, false, false}, |
| - {"moves-on", false, true, false}, |
| - {"flag-on-moves-on", true, true, false}, |
| - {"region-ha-on", false, false, true}, |
| - {"flag-on-region-ha-on", true, false, true}, |
| + {"flag-off", false, false, false, false}, |
| + {"flag-on", true, false, false, false}, |
| + {"moves-on", false, true, false, false}, |
| + {"flag-on-moves-on", true, true, false, false}, |
| + {"region-ha-on", false, false, true, false}, |
| + {"flag-on-region-ha-on", true, false, true, false}, |
| + {"usage-on", false, false, false, true}, |
| + {"flag-on-usage-on", true, false, false, true}, |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
| st := openTestStore(t) |
| @@ -605,7 +691,7 @@ func TestEveryCLIDoorNamesItsRoles(t *testing.T) { |
| } |
| t.Cleanup(func() { st.Close() }) |
| } |
| - s, err := NewServer(Config{Origin: "https://console.example", Keymail: "https://keymail.example", HostClaim: tc.hostClaim, MovesEnabled: tc.moves, RegionHA: tc.regionHA}, st) |
| + s, err := NewServer(Config{Origin: "https://console.example", Keymail: "https://keymail.example", HostClaim: tc.hostClaim, MovesEnabled: tc.moves, RegionHA: tc.regionHA, InstanceUsage: tc.usage}, st) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -673,6 +759,12 @@ func TestEveryCLIDoorNamesItsRoles(t *testing.T) { |
| t.Errorf("%s: present=%v empty=%v, want present=%v and a role set", pattern, present, set.Empty(), tc.moves) |
| } |
| } |
| + for _, pattern := range usageDoors { |
| + set, present := s.cliRoles[pattern] |
| + if present != tc.usage || (present && !set.Permits(svcrole.Usage)) { |
| + t.Errorf("%s: present=%v, want present=%v and the usage role", pattern, present, tc.usage) |
| + } |
| + } |
| for _, pattern := range demoOperatorDoors { |
| set, present := s.cliRoles[pattern] |
| if present == tc.hostClaim || (present && !set.Empty()) { |
| @@ -689,7 +781,8 @@ func TestEveryCLIDoorNamesItsRoles(t *testing.T) { |
| // own app may be brought up as, and must never move the platform binary the |
| // whole deployment runs (systemDoors). |
| func TestNoRoleReachesAMintFleetOrPolicyDoor(t *testing.T) { |
| - s := newConsoleFixture(t).srv |
| + // The usage switch on, so the usage door is registered too. |
| + s := usageFixture(t, true).srv |
| var families []string |
| families = append(families, mintDoors...) |
| families = append(families, fleetDoors...) |
| @@ -878,6 +971,12 @@ var exemptFromLegacyPin = map[string]bool{ |
| // public addresses, which DNS for the route already shows. It did not |
| // exist before service principals. |
| "GET /api/cli/apps/{account}/{app}/domains/{host}/placements": true, |
| + // The usage read (instance usage design §9) stands on the analytics |
| + // read's footing: the app's own traffic, counted per instance, admitted |
| + // to the analytics read's holders plus Usage. It did not exist before |
| + // service principals. TestInstanceRoleMatchesTodaysAppTokenReach checks |
| + // Instance reaches it with the switch on. |
| + "GET /api/cli/apps/{account}/{app}/usage": true, |
| } |
| // TestInstanceRoleMatchesTodaysAppTokenReach is the compatibility pin of spec |
| @@ -910,7 +1009,12 @@ func TestInstanceRoleMatchesTodaysAppTokenReach(t *testing.T) { |
| "DELETE /api/cli/apps/{account}/{app}/domains/{host}": true, |
| "GET /api/cli/apps/{account}/{app}/logs": true, |
| } |
| - s := newConsoleFixture(t).srv |
| + // The usage switch on, so the usage door is registered: new access for |
| + // Instance, exempted above and checked here. |
| + s := usageFixture(t, true).srv |
| + if set, ok := s.cliRoles["GET /api/cli/apps/{account}/{app}/usage"]; !ok || !set.Permits(svcrole.Instance) { |
| + t.Errorf("GET /api/cli/apps/{account}/{app}/usage: registered=%v, want it registered and reached by role instance", ok) |
| + } |
| got := map[string]bool{} |
| for pattern, set := range s.cliRoles { |
| if set.Permits(svcrole.Instance) && !exemptFromLegacyPin[pattern] { |
| @@ -1781,8 +1885,21 @@ func TestServiceRoleReachesTheDoorItNames(t *testing.T) { |
| // and non-members; TestAppSourceDoors proves that no |
| // storage read precedes these refusals. The walk checks its exact 404 too. |
| func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) { |
| - fx := newConsoleFixture(t) |
| - tok := serviceToken(t, fx.st, OpsAccountID, "root", "", svcrole.Admin) |
| + // The usage switch on, and a usage credential walks the list too: the |
| + // one role outside Admin's union that an app-bound door admits. |
| + fx := usageFixture(t, true) |
| + for _, tok := range []string{ |
| + serviceToken(t, fx.st, OpsAccountID, "root", "", svcrole.Admin), |
| + serviceToken(t, fx.st, OpsAccountID, "meter", "kass", svcrole.Usage), |
| + } { |
| + walkClosedDoors(t, fx, tok) |
| + } |
| +} |
| + |
| +// walkClosedDoors dials every closedDoors pattern with tok and checks the |
| +// closed-door refusal. |
| +func walkClosedDoors(t *testing.T, fx *consoleFixture, tok string) { |
| + t.Helper() |
| seen := 0 |
| for _, pattern := range closedDoors { |
| method, path, found := strings.Cut(pattern, " ") |
diff --git a/internal/console/usagerole_test.go b/internal/console/usagerole_test.go| new file mode 100644 |
| index 000000000..2795f4fb1 |
| --- /dev/null |
| +++ b/internal/console/usagerole_test.go |
| @@ -0,0 +1,202 @@ |
| +package console |
| + |
| +// The usage role and its switch (instance usage design §9, §12): a |
| +// credential that reads one app's usage and nothing else, minted by an |
| +// owner through the services doors only while CONSOLE_INSTANCE_USAGE is on. |
| + |
| +import ( |
| + "net/http" |
| + "net/url" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/svcrole" |
| +) |
| + |
| +// usageDoor is the one door the usage role reaches. |
| +const usageDoor = "GET /api/cli/apps/{account}/{app}/usage" |
| + |
| +// usageFixture is the console fixture with the instance usage switch set |
| +// to on. |
| +func usageFixture(t *testing.T, on bool) *consoleFixture { |
| + t.Helper() |
| + return newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, Tweak: func(c *Config) { c.InstanceUsage = on }}) |
| +} |
| + |
| +func usageURL(fx *consoleFixture, app string) string { |
| + return fx.ts.URL + "/api/cli/apps/" + fx.sqid + "/" + app + "/usage" |
| +} |
| + |
| +// TestUsageRouteGatedBySwitch: off, the route is not registered and a |
| +// member meets the mux's 404; on, it is registered and the member gets |
| +// past it. |
| +func TestUsageRouteGatedBySwitch(t *testing.T) { |
| + off := usageFixture(t, false) |
| + if _, ok := off.srv.cliRoles[usageDoor]; ok { |
| + t.Fatalf("switch off: %s is registered", usageDoor) |
| + } |
| + member := cliToken(t, off, "paul@keymail.dev", "code-usage-off") |
| + if status, body := getRaw(t, usageURL(off, "kass"), member); status != http.StatusNotFound || body != "404 page not found\n" { |
| + t.Fatalf("switch off: member at the usage route = %d %q, want the mux's 404", status, body) |
| + } |
| + |
| + on := usageFixture(t, true) |
| + set, ok := on.srv.cliRoles[usageDoor] |
| + if !ok { |
| + t.Fatalf("switch on: %s is not registered", usageDoor) |
| + } |
| + if got := set.Roles(); !slices.Equal(got, []svcrole.Role{svcrole.Admin, svcrole.Instance, svcrole.Operate, svcrole.Usage}) { |
| + t.Errorf("switch on: %s takes %v, want [admin instance operate usage]", usageDoor, got) |
| + } |
| + member = cliToken(t, on, "paul@keymail.dev", "code-usage-on") |
| + if status, body := getRaw(t, usageURL(on, "kass"), member); status == http.StatusNotFound || status == http.StatusUnauthorized || status == http.StatusForbidden { |
| + t.Fatalf("switch on: member at the usage route = %d %s, want past the gates", status, body) |
| + } |
| +} |
| + |
| +// TestMintUsage: a usage credential names one app, is refused while the |
| +// switch is off at both mint doors, and once minted reaches the usage door |
| +// of its own app and nothing else. |
| +func TestMintUsage(t *testing.T) { |
| + const noApp = "A usage credential must name one app. Nothing was minted." |
| + const off = "Usage credentials are not available on this console. Nothing was minted." |
| + |
| + // The API door. |
| + for _, c := range []struct { |
| + name string |
| + on bool |
| + app string |
| + want string |
| + }{ |
| + {"on, no app", true, "", noApp}, |
| + {"off, an app", false, "kass", off}, |
| + {"off, no app", false, "", off}, |
| + } { |
| + t.Run("api "+c.name, func(t *testing.T) { |
| + fx := usageFixture(t, c.on) |
| + owner := cliToken(t, fx, "paul@keymail.dev", "code-usage-mint") |
| + status, body := postRaw(t, fx.ts.URL+"/api/cli/services/"+fx.sqid, mintBody("meter", "usage", c.app), owner) |
| + if status != http.StatusBadRequest || jsonField(t, body, "error") != c.want { |
| + t.Errorf("mint = %d %s, want 400 %q", status, body, c.want) |
| + } |
| + if rows, err := fx.st.ServicePrincipals(OpsAccountID); err != nil || len(rows) != 0 { |
| + t.Errorf("ServicePrincipals = %d rows %v, want the mint refused", len(rows), err) |
| + } |
| + }) |
| + } |
| + |
| + // The browser POST, hand-made: the form never offers usage. Both |
| + // refusals come before the passkey. |
| + for _, c := range []struct { |
| + name string |
| + on bool |
| + app string |
| + want string |
| + }{ |
| + {"on, no app", true, "", noApp}, |
| + {"off, an app", false, "kass", off}, |
| + {"off, no app", false, "", off}, |
| + } { |
| + t.Run("browser "+c.name, func(t *testing.T) { |
| + fx := usageFixture(t, c.on) |
| + b := signInPaul(t, fx) |
| + csrf := sessionToken(t, fx, b) |
| + status, loc, body := postForm(t, b, fx.u("/services/new"), |
| + url.Values{"csrf": {csrf}, "name": {"meter"}, "role": {"usage"}, "app": {c.app}}) |
| + if strings.HasPrefix(loc, fx.fk.srv.URL) { |
| + t.Errorf("the refusal cost a passkey trip (-> %q)", loc) |
| + } |
| + if status != http.StatusSeeOther || loc != fx.path("/settings") { |
| + t.Fatalf("mint = %d -> %q, want 303 back to the page:\n%s", status, loc, body) |
| + } |
| + if _, _, page := get(t, b, fx.u("/settings")); !strings.Contains(page, c.want) { |
| + t.Errorf("the settings page does not say %q:\n%s", c.want, page) |
| + } |
| + if rows, err := fx.st.ServicePrincipals(OpsAccountID); err != nil || len(rows) != 0 { |
| + t.Errorf("ServicePrincipals = %d rows %v, want the mint refused", len(rows), err) |
| + } |
| + }) |
| + } |
| + |
| + // On, with an app, the browser mints it as it mints any app-bound role. |
| + t.Run("browser on, an app", func(t *testing.T) { |
| + fx := usageFixture(t, true) |
| + b := signInPaul(t, fx) |
| + csrf := sessionToken(t, fx, b) |
| + status, _, body := postGated(t, fx, b, fx.u("/services/new"), |
| + url.Values{"csrf": {csrf}, "name": {"meter"}, "role": {"usage"}, "app": {"kass"}}) |
| + if status != http.StatusOK { |
| + t.Fatalf("mint = %d:\n%s", status, body) |
| + } |
| + p, ok := fx.st.CLIPrincipal(paneSecret(t, body), time.Now()) |
| + if !ok || p.Role != svcrole.Usage || p.App != "kass" { |
| + t.Fatalf("the minted secret resolves to %+v %v, want usage on kass", p, ok) |
| + } |
| + }) |
| + |
| + // On, with an app, through the API: minted, and it reaches the usage |
| + // door of its own app only. |
| + fx := usageFixture(t, true) |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "other", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + owner := cliToken(t, fx, "paul@keymail.dev", "code-usage-mint-on") |
| + status, body := postRaw(t, fx.ts.URL+"/api/cli/services/"+fx.sqid, mintBody("meter", "usage", "kass"), owner) |
| + if status != http.StatusCreated { |
| + t.Fatalf("mint = %d %s, want 201", status, body) |
| + } |
| + if got := jsonField(t, body, "role"); got != "usage" { |
| + t.Errorf("minted role = %q, want usage", got) |
| + } |
| + if doors := jsonStrings(t, body, "doors"); !slices.Equal(doors, []string{usageDoor}) { |
| + t.Errorf("doors = %v, want exactly [%s]", doors, usageDoor) |
| + } |
| + tok := jsonField(t, body, "token") |
| + if status, body := getRaw(t, usageURL(fx, "kass"), tok); status == http.StatusNotFound || status == http.StatusUnauthorized || status == http.StatusForbidden { |
| + t.Errorf("usage credential at its own app's usage door = %d %s, want past the gates", status, body) |
| + } |
| + otherStatus, otherBody := getRaw(t, usageURL(fx, "other"), tok) |
| + ghostStatus, ghostBody := getRaw(t, usageURL(fx, "ghost"), tok) |
| + if otherStatus != http.StatusNotFound || ghostStatus != http.StatusNotFound || otherBody != ghostBody { |
| + t.Errorf("another app = %d %q, an unknown app = %d %q; want the same 404 bytes", otherStatus, otherBody, ghostStatus, ghostBody) |
| + } |
| + // Its own app's other reads stay shut: the role gate's 403. |
| + if status, body := getRaw(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/kass/analytics", tok); status != http.StatusForbidden { |
| + t.Errorf("usage credential at the analytics read = %d %s, want 403", status, body) |
| + } |
| +} |
| + |
| +// TestResolveUsageWithoutAppFailsClosed: the Run rule's twin. A usage row |
| +// bound to no app is a row this console did not write, and it does not |
| +// resolve; the same row bound to an app does. |
| +func TestResolveUsageWithoutAppFailsClosed(t *testing.T) { |
| + s := openTestStore(t) |
| + insertTokenRow(t, s, "usage-kass", cliKindService, OpsAccountID, "kass", string(svcrole.Usage), 0, 0, 0) |
| + if p, ok := s.CLIPrincipal("usage-kass", time.Now()); !ok || p.Role != svcrole.Usage || p.App != "kass" { |
| + t.Fatalf("app-bound usage row = %+v %v, want it to resolve", p, ok) |
| + } |
| + insertTokenRow(t, s, "usage-wide", cliKindService, OpsAccountID, "", string(svcrole.Usage), 0, 0, 0) |
| + if p, ok := s.CLIPrincipal("usage-wide", time.Now()); ok { |
| + t.Fatalf("usage row bound to no app resolved to %+v", p) |
| + } |
| +} |
| + |
| +// TestServicesFormNeverListsUsage: usage credentials are minted with |
| +// carlos services, so the form's role list skips usage, switch on or off, |
| +// as it skips platform. |
| +func TestServicesFormNeverListsUsage(t *testing.T) { |
| + for _, on := range []bool{false, true} { |
| + fx := usageFixture(t, on) |
| + acct := planAccount(t, fx, 501) |
| + p := &page{} |
| + fx.srv.servicePane(p, acct) |
| + if !slices.Contains(p.ServiceRoles, string(svcrole.Publish)) { |
| + t.Fatalf("switch %v: the form offers %v, want publish among them", on, p.ServiceRoles) |
| + } |
| + if slices.Contains(p.ServiceRoles, string(svcrole.Usage)) { |
| + t.Errorf("switch %v: the form offers %v, want no %q", on, p.ServiceRoles, svcrole.Usage) |
| + } |
| + } |
| +} |
diff --git a/internal/svcrole/svcrole.go b/internal/svcrole/svcrole.go| index 0f8a27a45..52dca7d81 100644 |
| --- a/internal/svcrole/svcrole.go |
| +++ b/internal/svcrole/svcrole.go |
| @@ -79,17 +79,25 @@ const ( |
| // a door admits it only by being registered through Exactly(Platform) |
| // (spec 2026-11-19-platform-accounts-design.md). |
| Platform Role = "platform" |
| - // Admin is the union of every role except Run, Team and Platform, plus |
| - // ledgers, store and place. It is NOT "everything harmless": store grant |
| - // mints a path-scoped IAM user, which is a real handover. Run and |
| - // Platform are reachable only through Exactly, and Team only through |
| - // Scoped, so an Admin principal cannot start a run, act for a platform |
| - // account, or act inside a team's scope by being Admin. |
| + // Usage reads one app's usage counts and nothing else: a credential an |
| + // outside server holds to meter what an app's instances served. It is |
| + // always bound to one app, and it is deliberately outside the union |
| + // Admin stands for, so that no Allow(...) registration can give a usage |
| + // credential a second door. Allow refuses it (it panics); its one door |
| + // is registered through Exactly(Usage, Instance, Operate, Admin) |
| + // (spec 2026-11-29-instance-usage-design.md §9). |
| + Usage Role = "usage" |
| + // Admin is the union of every role except Run, Team, Platform and |
| + // Usage, plus ledgers, store and place. It is NOT "everything harmless": |
| + // store grant mints a path-scoped IAM user, which is a real handover. |
| + // Run, Platform and Usage are reachable only through Exactly, and Team |
| + // only through Scoped, so an Admin principal cannot start a run, act for |
| + // a platform account, or act inside a team's scope by being Admin. |
| Admin Role = "admin" |
| ) |
| // catalogue is the whole vocabulary, in the order All returns it. |
| -var catalogue = []Role{Publish, Deploy, Instance, Operate, Service, Run, Team, Platform, Admin} |
| +var catalogue = []Role{Publish, Deploy, Instance, Operate, Service, Run, Team, Platform, Usage, Admin} |
| // All returns the catalogue. The slice is copied so a caller cannot edit the |
| // vocabulary by writing through it. |
| @@ -160,6 +168,13 @@ func Allow(roles ...Role) Set { |
| // not reach those. |
| panic("svcrole: Allow called with the platform role, which Admin must not reach; use Exactly(Platform)") |
| } |
| + if r == Usage { |
| + // Same cut again, for a different reason: a usage credential |
| + // has one door, and an Allow set is the form any later |
| + // registration would reach for, so it must not be able to |
| + // carry Usage at all. |
| + panic("svcrole: Allow called with the usage role, which has one door; use Exactly(Usage, ...)") |
| + } |
| if r == Team { |
| // A team door is a scoped door: the console's cliScopedRoute |
| // is the only registration that may admit Team, because it is |
| @@ -176,7 +191,7 @@ func Allow(roles ...Role) Set { |
| // Exactly builds the Set for a door that admits ONLY the roles listed. Unlike |
| // Allow it does not add Admin: this is how a role outside Admin's union (Run, |
| -// Platform) is granted to a door, and how a door says "no administrator either". |
| +// Platform, Usage) is granted to a door, and how a door says "no administrator either". |
| // |
| // Like Allow, it panics on an unparseable role, for the same reason: a |
| // dropped role would be a door silently narrowed. Called with no arguments it |
diff --git a/internal/svcrole/svcrole_test.go b/internal/svcrole/svcrole_test.go| index 041d6fe82..207666fe6 100644 |
| --- a/internal/svcrole/svcrole_test.go |
| +++ b/internal/svcrole/svcrole_test.go |
| @@ -34,9 +34,9 @@ func TestAdminPermitsEveryNonEmptySet(t *testing.T) { |
| t.Errorf("Allow(%v).Permits(Admin) = false; want true", s.Roles()) |
| } |
| } |
| - // Admin is the union of every role EXCEPT Run, Team and Platform, so an |
| - // Allow set never carries them on Admin's account either. |
| - for _, r := range []Role{Run, Team, Platform} { |
| + // Admin is the union of every role EXCEPT Run, Team, Platform and |
| + // Usage, so an Allow set never carries them on Admin's account either. |
| + for _, r := range []Role{Run, Team, Platform, Usage} { |
| if Allow(Publish).Permits(r) || Allow(Admin).Permits(r) { |
| t.Errorf("an Allow set permits %q; want false", r) |
| } |
| @@ -362,3 +362,58 @@ func TestExactlyPlatformAdmitsOnlyPlatform(t *testing.T) { |
| t.Errorf("Exactly(Platform).Roles() = %v; want [platform]", got) |
| } |
| } |
| + |
| +// The usage role (instance usage design §9): in the catalogue after |
| +// Platform and before Admin, outside Admin's union, refused by Allow, and |
| +// admitted only by a door registered through Exactly. |
| +func TestUsageIsInTheCatalogueAndOutsideAdminsUnion(t *testing.T) { |
| + got, ok := Parse("usage") |
| + if !ok || got != Usage { |
| + t.Fatalf(`Parse("usage") = %q, %v; want %q, true`, got, ok, Usage) |
| + } |
| + all := All() |
| + i := slices.Index(all, Usage) |
| + if i < 0 { |
| + t.Fatalf("All() = %v; want it to contain usage", all) |
| + } |
| + if i == 0 || all[i-1] != Platform || i+1 >= len(all) || all[i+1] != Admin { |
| + t.Errorf("All() = %v; want usage after platform and before admin", all) |
| + } |
| + if !Exactly(Usage).Permits(Usage) { |
| + t.Error("Exactly(Usage).Permits(Usage) = false; want true") |
| + } |
| + if Exactly(Usage).Permits(Admin) { |
| + t.Error("Exactly(Usage).Permits(Admin) = true; want false") |
| + } |
| + for _, s := range []Set{Allow(Publish), Allow(Admin), Allow(Instance, Operate)} { |
| + if s.Permits(Usage) { |
| + t.Errorf("%v permits usage; only an Exactly set may", s.Roles()) |
| + } |
| + } |
| + s := Exactly(Usage, Instance, Operate, Admin) |
| + if got := s.Roles(); !reflect.DeepEqual(got, []Role{Admin, Instance, Operate, Usage}) { |
| + t.Errorf("Exactly(Usage, Instance, Operate, Admin).Roles() = %v; want [admin instance operate usage]", got) |
| + } |
| +} |
| + |
| +func TestAllowPanicsOnUsage(t *testing.T) { |
| + // Every Allow set carries Admin, and a usage credential must have one |
| + // door only: an Allow(Usage, ...) registration would be a second door |
| + // written in the form that hides it. Both the bare and the mixed form |
| + // panic, and name Exactly. |
| + for _, roles := range [][]Role{{Usage}, {Publish, Usage}, {Usage, Instance, Operate}} { |
| + func() { |
| + defer func() { |
| + got := recover() |
| + if got == nil { |
| + t.Errorf("Allow(%v) did not panic", roles) |
| + return |
| + } |
| + if msg, _ := got.(string); !strings.Contains(msg, "Exactly(Usage") { |
| + t.Errorf("Allow(%v) panic = %v; want it to say to use Exactly(Usage, ...)", roles, got) |
| + } |
| + }() |
| + Allow(roles...) |
| + }() |
| + } |
| +} |