--- name: gram-rbac description: Use when a task touches authorization in Speakeasy — gating a handler or list endpoint, `authz.Require` / `Decide` / `Either` / `WithoutChallenges`, typed refs like `authz.MCPServer(id, project).Write()` or `authz.Environments(p).Read()`, `authz.Check{...}` literals, adding or changing a scope, permission, resource type, block or dimension in `registry.Definitions` (`authz/internal/registry/definitions.go`), system role defaults, agent-safe scopes (`SafeSince`, `AgentUnsafe`), `mise run gen:authz`, `refs_gen.go`, `scopes_gen.go`, `tables_gen.go`, the `norawauthzchecks` lint, "invalid authz check", `ErrInvalidCheck`, `CodeForbidden` from authz, or RBAC state in the dashboard (`useRBAC`, `RequireScope`, access pages). metadata: relevant_files: - "server/internal/authz/**/*.go" - "server/internal/authztest/**/*.go" - "server/internal/access/**/*.go" - "server/internal/access/**/*.sql" - "server/internal/agents/runtimepolicy/**/*.go" - "server/design/access/**" - "client/dashboard/src/pages/access/**" - "client/dashboard/src/hooks/useRBAC.ts" - "glint/no_raw_authz_checks.go" --- # Speakeasy RBAC The whole permission model is one Go value, `registry.Definitions` in `server/internal/authz/internal/registry/definitions.go`. It is build-time input only: `mise run gen:authz` validates it and writes the scope constants (`scopes_gen.go`), the typed request refs (`refs_gen.go`, including a project collection for `mcp`, `environment` and `assistant` and methods such as `ToolCall` declared by a permission's `DimensionSets`; `ids.go` holds their shared helpers) and every derived table (`tables_gen.go`: expansions and blocks, selector key allowlists, the keys each permission opens, the scope catalogue, system role scopes, agent eligibility) into package `authz`, which never imports the registry. The registry imports nothing from `authz` either: generated Go is all that passes between them, so the generator runs even when the generated files are missing or broken. The names both sides use (selector keys, categories, grant sources, dispositions, built-in role names) are declared once, in one registry file per subject (`scopes.go` for kinds, the closed list of actions and categories; `selectors.go`; `sensitivity.go`; `grant_source.go`; `roles.go`), and each is copied into `authz` as a `*_gen.go` file. The scope enum in the Goa design and the `docs/rbac.md` scope table come from the generated values. One server-side evaluator, `authz.Engine`, is canonical. Two list queries still mirror most of its matching and precedence in SQL (`ListAccessibleMCPServersForUser`, `ListAccessibleSkillsForUser`); a change to matching or blocks must update them too, until the SQL prefilter replaces them. They are not exact mirrors: the skill list leaves out a skill whose only grant is `skill:write` blocked by `skill:blocked_write`, although the engine still allows `skill:read` on it (kept on purpose; see the query's comment). **Change the model, regenerate, and let the tests tell you what else moved.** Never hand-edit a derived table. ## Mental model | Term | Meaning | | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Resource type | A `ResourceType` in the model: `Kind` (`mcp`, `environment`, `project`, ...), optional `Parent` (`project`), its `Dimensions`, and its `Permissions`. | | Permission | One action on a type (`read`, `write`, `connect`). Its scope is `:`; `Implies` lists the actions a grant of it also satisfies; `DimensionSets` adds ref methods that take some of the type's dimensions as arguments (connect's `ToolCall`). | | Block | A permission's `Exclusions: Blocked(...)` generate `:blocked_`. A block also takes away every permission that implies it. | | Grant | Scope + selector held by a principal (user, role, `user:all`, agent, API key). Build with `authz.NewGrant` / `NewGrantWithSelector`. | | Check | What a request asks for. Build it with a typed ref, never by hand. | | Dimension values | A concrete value matches an equal grant value or `*`. A grant key the check does not carry never matches: absence is not permission. The only exceptions are the keys a permission lists in `Open` in the registry, for three kinds of check: a probe (marked with `Probe()`, discovery only; `Require` refuses it), and two the constructor sets, never the call site: a connection (`Connect()`, which leaves out `tool` and `disposition`) and the risk policy audience question (`RiskPolicyEvaluateCheck`, which leaves out the server). `TestOpenKeys_Golden` lists every open key. Auth clients and root open none. Blocks, exemptions, containment and the direct override of a tool call always match exactly. A `Require` refusal caused only by a missing key is logged as an error naming the key. | | Precedence | A user's direct grant naming a concrete resource outranks a block inherited from a role or `user:all`. Lives in `precedence.go`. | ## Gating a handler ```go // one resource if err := s.authz.Require(ctx, authz.MCPServer(id, project).Write()); err != nil { return err } // no single resource to name (create), or a lookup that missed (do not leak existence); a list uses Read() if err := s.authz.Require(ctx, authz.Environments(p).Write()); err != nil { return err } if err := s.authz.Require(ctx, authz.Environments(p).Read()); err != nil { return err } // either of two permissions on the resource, and a block on either refuses // (a wildcard grant already covers one resource, so never pair those) if err := s.authz.Require(ctx, authz.Either(authz.MCPServer(id, p).Write(), authz.MCPServer(id, p).Connect())); err != nil { return err } // a branch, not a denial (no challenge logged) canRead, err := s.authz.Decide(authz.WithoutChallenges(ctx), authz.Chat(id).Read()) if err != nil { return err } if canRead.AllAllowed { // show the chat } // discovery: "could they act on any matching resource?" canConnect, err := s.authz.Decide(authz.WithoutChallenges(ctx), authz.MCPServer(id, p).Connect().Probe()) if err != nil { return err } if canConnect.AllAllowed { // offer the connect button } // a list: one decision per row, in order, and one challenge row for the call decisions, err := s.authz.Decide(ctx, checks...) ``` | Need | Use | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Refuse unless allowed | `Require(ctx, checks...)` (all must pass) | | Any one of several grants | `Require(ctx, authz.Either(...))`: one alternative is enough, but a block on any alternative refuses the group | | Branch on the answer | `Decide(authz.WithoutChallenges(ctx), ...)` and read `AllAllowed`. Accepts `Either` groups and probes. Returns an error, not false, for an invalid check. | | Narrow a list | `Decide(ctx, checks...)` and keep the rows whose `Each[i].Allowed` is true. A refused tool call's `Each[i].Reason` is `read_only` or `disposition` when another disposition would pass. | | MCP tool call | `authz.MCPServer(id, p).ToolCall(tool, disposition)`, with `authz.DispositionFromHints`. A tool with no annotations is `unannotated`. | Ref constructors take typed ids, never a raw string or `uuid.UUID`: `authz.Environment(authz.EnvironmentIDOf(env.ID), authz.ProjectIDOf(projectID))`. Each kind that has a ref has an id type generated in `ids_gen.go` with two constructors, `IDOf(uuid.UUID)` and `IDFrom(string)`, so ids of different kinds cannot be swapped. The hand-written `mcp_auth_client`, `risk_policy` and `inference` checks keep their own constructors, listed below. An id that cannot name a resource (the nil uuid, an empty string, `*`, a `$` marker, a string containing whitespace) is kept as absent, and every check built from it is refused with `ErrInvalidCheck`: an absent id never grants. In the examples here `id`, `envID`, `p` and `project` are such typed ids, already built with `IDOf` or `IDFrom`. The argument order is always the resource, then its project. A project collection (`authz.Environments(p)`, `authz.MCPServers(p)`, `authz.Assistants(p)`) builds a check on the resource type whose resource id is the project id, so project-wide grants match it and `Decide` answers it with project-wide grants. Chats are the exception. Chat has no project dimension, and every chat grant the dashboard saves covers every chat, so the id in a chat check is a placeholder. `authz.Chats(p)`, `authz.OrgChats(org)` and `authz.UnrestrictedChats()` all ask whether the caller holds chat:read on every chat, and differ only in the placeholder they carry. None of them limits access to a project or an organization. A check about one real chat, such as a chat being read or unmasked, uses `authz.Chat(authz.ChatIDOf(chatID)).Read()` (or `.Write()`) instead, as `chat/session_access.go` and `risk/unmask_ch.go` do. Keep `Require` and its `CodeForbidden` branch where the code already has one. Swapping it for `Decide` under `WithoutChallenges` keeps enforcement the same but stops logging the challenge, so do that only where the denial is not a refusal the user sees. Refs exist for every kind in the model except `mcp_auth_client` (`MCPAuthClientCheck`), `risk_policy` (`RiskPolicyApplies` / bypass checks) and `inference` (`InferenceExecuteCheck`). The list sits at the end of `refs_gen.go`. For a list endpoint, load the candidate rows, build one ref per row, call `Decide`, and rebuild the response from the allowed rows. Never call `Require` per item. In the handler's test, add one case without the grant that asserts `oops.CodeForbidden`, and one case with it through `authztest.WithExactGrants(t, ctx, authz.NewGrant(scope, resourceID))`. A typed id proves an id is well formed, not that the resource is the caller's. That rests on the handler loading the row inside the caller's project, so keep a handler test in which a caller from another project and organization names the resource (`environments/tenant_binding_test.go`). The engine itself only compares org checks: one about an organization other than the caller's is refused for every caller, so check an org permission on the organization the caller is acting in. ## Adding or changing a permission 1. Edit `registry.Definitions` in `authz/internal/registry/definitions.go`: a `Permission` on the right type (with `Label`, `Description`, `Implies`, `Exclusions`, `Agent`, `Source`), or a new `ResourceType`. Add it to `SystemRoles[authz.SystemRoleAdmin]` too, and to member only if every user should have it. Its `Action` is one of the constants in `registry/scopes.go` (`ActionRead`, `ActionWrite`, ...); a verb that is not there is added to `Actions` first, and the compound names in `LegacyActions` are not to be extended. The generator refuses an invalid registry, and `TestDefinitions_IsValid` fails on one. A new permission's scope is `:`, so leave `LegacyScope` empty. Only the three permissions that predate the registry (`plugin:write`, `log:read`, `mcp:auth`) set it, and they keep it until those scopes are deliberately renamed; validation rejects it anywhere else. 2. `mise run gen:authz`. This rewrites `scopes_gen.go`, `refs_gen.go` and `tables_gen.go`, and `TestGeneratedFilesAreCurrent` fails until you run it. The diff of `tables_gen.go` is the review surface: it shows exactly which scopes now satisfy, block or are managed by what. 3. Update the snapshots from `server/`, then review their diffs, because they are the change: - `go test ./internal/authz -run DocTable -args -update-docs` (writes `docs/rbac.md`) - `go test ./internal/access -run TestListScopes_DashboardFixture -args -update` (writes the dashboard's `listScopes.fixture.json`) 4. `mise run gen:goa-server`, then `mise run gen:sdk`. The design's scope enum reads `authz.ScopeNames()`. 5. The dashboard reads its tables and check constructors from `client/dashboard/src/lib/authz.gen.ts`, which `gen:authz` writes. Each constructor is the Go ref of the same name with the same required arguments (`authz.mcpServer(id, projectId).write()` is `authz.MCPServer(id, project).Write()`); a page asks `useRBAC().can(check)` or ``, and `.probe()` asks about any resource of a collection. Its matcher in `client/dashboard/src/hooks/useRBAC.ts` is checked against the server by `useRBAC.server-cases.test.ts`, which replays `authz-cases.gen.json` (sets of effective grants with the server evaluator's answers, also written by `gen:authz`). The cases' `calls` are answered by calling each constructor's Go twin (`authzcases/constructors_gen.go`) and replayed through the TypeScript constructor, so a constructor that asks a different question fails too. If that test fails after a change, never edit the cases: fix the matcher in `useRBAC.ts` when a `checks` or plain `calls` answer disagrees, and fix the generator in `authzgen/dashboard_checks.go` (then rerun `gen:authz`) when a constructor builds a different check than its Go twin. Fix the "Dashboard Grant Reference" in `docs/rbac.md` if a page's gate changes. 6. Assess Platform MCP (`maintaining-platform-mcp`) and Command K (`maintaining-command-palette`) if the permission gates a user-facing capability. 7. `mise run lint:server`, `mise run test:server ./internal/authz/... ./internal/access/...`, and `aube run -F dashboard test src/hooks/useRBAC` (includes the server-cases parity test). The invariant suite (`authz/registry_invariants_test.go`) checks every permission automatically: implications hold, nothing else is satisfied, and blocks win. Do not add per-scope tests for those properties. ## Agents `Agent: AgentUnsafe()` means no agent policy may ever hold the permission. Use it by default. `SafeSince(N)` makes the permission agent-safe from delegated policy version `N`, and policies stored at an older version keep reading it as unsafe. Making a permission agent-safe therefore means adding a delegated policy version in `server/internal/agents/runtimepolicy/delegated_policy.go`: N is `CurrentDelegatedPolicyVersion` + 1. Add the version constants in both `delegated_policy.go` and `runtimepolicy/scopes.go`, and move both `CurrentDelegatedPolicyVersion` and `CurrentRuntimeScopeRegistryVersion` to N; `SafeSince` panics past the runtime registry's current version. The issuer constants (`IssuedDelegatedPolicyVersion`, `AssistantIssuedPolicyVersion`, `InferenceIssuedPolicyVersion`) are separate contracts; raise one only when that issuer should start carrying the permission. Then commit the new version's stored-policy fixture: ``` go test ./internal/agents/runtimepolicy -run TestStoredPolicyFixtures -args -write-stored-policy-fixture=N ``` The flag refuses to overwrite a fixture. Never regenerate an existing one, because those fixtures are what old stored policies are decoded against. A credential that acts for a user also carries that user's live policy. Today it decides auth-client checks only. For every other check, the engine logs one warning per engine call (`authz check passes the credential's policies but not the live policy of the user it acts for`) when the call is allowed a check that policy would refuse. `Require(Either(...))` and `Decide(Either(...))` log only when it refuses every allowed alternative. After the logging window those checks will be refused. A workload session acts for nobody and is bounded by its owner only. ## Never - **A tool or disposition goes on a tool call and nowhere else.** `ToolCall` marks the check as a tool call. A check that carries `tool` or `disposition` without being built that way is an invalid check, and so is a tool call you build on any scope but `mcp:connect` (the engine derives the matching `mcp:blocked_connect` check itself). The engine reads that mark, not which dimensions happen to be present, so a tool call can never be evaluated as a connection. - **A tool or disposition limit goes on a connect rule or a connect block and nowhere else.** The registry declares `tool` and `disposition` on `mcp:connect` only, so `ValidateSelector` refuses them on `mcp:read`, `mcp:write` and their blocks. - **A check with a scope the registry does not know, a resource kind that is not its scope's, or a dimension its scope does not declare is an invalid check.** `resource_kind` and `resource_id` are never dimensions. - **Never build a raw `authz.Check{...}` outside `internal/authz`.** The `norawauthzchecks` glint rule reports it in every package but `internal/authz` itself, outside `_test.go` files. Only a check rebuilt from data may carry `//nolint:glint // norawauthzchecks: `: stored data whatever its kind (a recorded challenge, a stored grant's own selector), or a scope a tool declares (a platform tool's `RequiredScope`). The zero `authz.Check{}` returned beside a non-nil error is allowed. - **Never pass a probe to `Require`, and never pass a group (`Either`) to `Require` next to other checks.** `Decide` accepts both. Each misuse is an invalid check, which maps to an unexpected error rather than a 403. - **Never build a ref with an empty project.** An empty dimension is an invalid check. Take the project from the row you loaded, not from the request, when they can differ. - **Never decide whether a risk policy applies from `RiskPolicyApplies(...).Evaluate(...).Satisfied`.** Call `authz.EvaluateRiskPolicy(grants, policyID, dims)` and use `.Applies()`. It names the two reasons a policy leaves a caller alone (`RiskPolicyExempt`, `RiskPolicyNotInAudience`); anything else, including grants that could not be read or a policy that could not be evaluated, means the policy applies. The caller decides how to report the error and never uses it to skip the policy: the realtime scanner logs it and scans, `policycore` returns it. - **Never hand-edit a `*_gen.go` file in `authz`.** Change `registry.Definitions` (or the registry file that declares the name, such as `registry/scopes.go` or `registry/selectors.go`) and regenerate. - **Never evaluate grants outside `authz`.** The two SQL list queries in `access/queries.sql` (`ListAccessibleMCPServersForUser`, `ListAccessibleSkillsForUser`) mirror the matcher and precedence. If you change either, change both. - **Never read a `principal_grants` row for authorization without `(expires_at IS NULL OR expires_at > clock_timestamp())`.** Temporary grants expire in place. ## Reference [reference.md](reference.md) covers the rest: the `access` management API, grant loading and temporary grants, provisioning, scope overrides, auth-client checks, the dashboard's `useRBAC` and ``, and inspecting a caller's grants.