Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

chore(skills): add authz-configurator skill (#13261)

Vikrant Guptafe9165447fae
diff --git a/.claude/skills/authz-configurator/SKILL.md b/.claude/skills/authz-configurator/SKILL.md
new file mode 100644
index 0000000000..13802ba2cd
--- /dev/null
+++ b/.claude/skills/authz-configurator/SKILL.md
@@ -0,0 +1,142 @@
+---
+name: authz-configurator
+description: Add authorization (authz) to a SigNoz backend feature end-to-end — register kinds/resources, grant managed-role permissions, wire routes with ResourceDefs, backfill tuples for existing orgs, and write the authz integration tests. Use this whenever the user mentions authz, authorization, permissions, access control, managed roles (admin/editor/viewer), OpenFGA, ResourceDef, CheckResources, 403/forbidden behavior on an endpoint, wiring or protecting a new route, registering a new resource/kind, or writing integration tests that assert role-based allow/deny. Also use it when a new API endpoint is being added and its access control hasn't been decided yet — every route needs an authz decision even if the user didn't say the word.
+---
+
+# SigNoz Authz Workflow
+
+This skill automates the procedure documented in `docs/contributing/go/authz.md`. Read that doc first — it is the canonical explanation of the concepts (types, verbs, kinds, resources, selectors, tuples, the community/enterprise split). This skill tells you what to do; the doc tells you why it works.
+
+The core model in one paragraph: permissions are never attached to users. They are attached to **roles** as OpenFGA tuples, and users/service accounts are made **assignees** of roles. You declare everything in code registries under `pkg/types/coretypes/`; tuples for new organizations are derived from those registries at org bootstrap. Routes declare what resource+verb they touch via `ResourceDef`s, and middleware turns that into a check that works in both community (role gate) and enterprise (per-resource FGA) editions.
+
+## Before you start
+
+Figure out what shape the work is. Ask the user if unclear:
+
+- **New resource** (new kind + routes) → all steps below.
+- **New route on an existing resource** → step 4 only (maybe step 3 if roles need new verbs).
+- **Changing what a role can do** → steps 3, 5, 6, 7.
+- **Just tests** → steps 6, 7.
+
+Almost every feature resource is a `metaresource` (dashboards, rules, pipelines) or a `telemetryresource` (logs, traces, metrics). If the feature genuinely needs a brand-new FGA **type**, stop and flag it to the user — that requires editing both `pkg/authz/openfgaschema/base.fga` and `ee/authz/openfgaschema/base.fga` together and is almost never the right call. A new **kind** never touches the schema.
+
+## Step 1: Register the kind
+
+Edit `pkg/types/coretypes/registry_kind.go`. Add a var and append it to the `Kinds` slice (both are required — the slice is what gets validated and iterated):
+
+```go
+KindThing = MustNewKind("thing")
+```
+
+Kind names are lowercase, hyphen-separated (`quick-filter`, `trace-funnel`, `notification-channel`).
+
+Also add the kind to `Kind.Enum()` in `pkg/types/coretypes/kind.go` — a second hand-maintained list mirroring `Kinds` that feeds the OpenAPI enum. It is easy to miss because nothing fails at build time without it; the drift only shows up in the generated spec.
+
+## Step 2: Register the resource
+
+Edit `pkg/types/coretypes/registry_resource.go`. Add a var and append it to the `Resources` slice:
+
+```go
+ResourceMetaResourceThing = NewResourceMetaResource(KindThing)
+```
+
+Use `NewResourceTelemetryResource(KindThing)` for telemetry data resources. Pass an explicit verb list only when the resource supports fewer verbs than the type default — see `ResourceMetaResourceFactorAPIKey` in that file for the shape.
+
+## Step 3: Grant permissions to managed roles
+
+Edit `pkg/types/coretypes/registry_managed_role.go`. Add `Transaction` entries to `ManagedRoleToTransactions` for each role that may act on the resource:
+
+```go
+{Verb: VerbCreate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindThing}, WildCardSelectorString)},
+```
+
+The convention: **admin** gets everything; **editor** gets full CRUD only on day-to-day observability resources (dashboards, rules, saved views — not access control or org settings); **viewer** gets `read`/`list`; **anonymous** gets nothing (public dashboards are the only exception). Match the file's existing style, including its one-line grouping comment per resource block (e.g. `// thing — editors manage, viewers read`) — that file uses grouping comments as structure; do not add comments anywhere else.
+
+This map is the single source of truth: changing it affects only organizations created afterwards (see step 5 for existing orgs), and the integration suite asserts its contents via a golden file (see step 6).
+
+## Step 4: Wire the route
+
+Register routes in the existing domain file under `pkg/apiserver/signozapiserver/` — do not create new per-sub-resource route files. Each route needs three coordinated pieces:
+
+1. **`provider.authzMiddleware.CheckResources(handlerFn, roles...)`** — the role list is the community-edition fallback gate (which managed roles may call this route when per-resource checks are unavailable).
+2. **`handler.WithResourceDefs(...)`** — declares resource, verb, audit category, ID extractor, and selector.
+3. **`SecuritySchemes: newScopedSecuritySchemes([]string{resource.Scope(verb)})`** — advertises the scope in the OpenAPI spec.
+
+Selector rules (getting these wrong silently over- or under-authorizes):
+
+| Operation | Selector | ID extractor |
+|---|---|---|
+| create | `WildcardSelector` | `ResponseJSONPath("data.id")` (ID exists only after the handler runs; recorded for audit) |
+| list | `WildcardSelector` | none |
+| read/update/delete of one instance | `IDSelector` | `PathParam("id")` or `BodyJSONPath(...)` |
+| request ID ≠ FGA selector (e.g. route has a role UUID, FGA objects use role names) | custom `SelectorFunc` | as appropriate |
+
+Routes that link two resources check **both** sides. Read `references/route-wiring.md` before wiring any create route, linking route (attach/detach, parent-child), or custom selector — it has complete real examples from `serviceaccount.go`.
+
+Prefer `CheckResources` + `ResourceDef` for anything resource-shaped. The legacy gates `ViewAccess`/`EditAccess`/`AdminAccess` are coarse role-only checks — do not use them for new routes. `OpenAccess` means no authorization (authentication still applies); `CheckWithoutClaims` serves anonymous routes.
+
+## Step 5: Backfill existing organizations (only if needed)
+
+New organizations derive their tuples from the registries at creation — no migration needed for them. If **existing** organizations must get the new permissions, add a migration in `pkg/sqlmigration/` that does two things per org:
+
+1. **Insert the FGA tuples** — follow `083_add_role_crud_tuples.go`: one `tuple` row (+ `changelog` row) per role/verb/object, with `ON CONFLICT ... DO NOTHING` so it stays idempotent, handling both the Postgres and SQLite tuple column layouts as that file does.
+2. **Refresh the managed roles' JSON record** — since `099_add_role_transaction_groups.go`, each role row carries a `transaction_groups` JSON column that mirrors its permissions. Tuples and JSON must move together or the stored record drifts from the registry. Follow 099's managed-role loop: marshal `authtypes.NewTransactionGroupsFromTransactions(coretypes.ManagedRoleToTransactions[roleName])` and `UPDATE role SET transaction_groups = ? WHERE org_id = ? AND type = 'managed' AND name = ?`. Serializing from the registry (which already contains your new grants) makes this step self-updating. Custom roles need no changes — only managed roles mirror the registry.
+
+Register the new migration factory in `NewSQLMigrationProviderFactories` in `pkg/signoz/provider.go`, appended after the existing entries. The factory name passed to `factory.MustNewName` must match `^[a-z][a-z0-9_-]{0,30}$` — at most 31 characters, or it panics at startup; prefer a short name like `notification_template_tuples` over `add_notification_template_tuples`.
+
+Ask the user whether backfill is needed rather than assuming — shipping a feature to existing orgs almost always means yes.
+
+## Step 6: Update the golden testdata and regenerate CI-checked artifacts
+
+If you changed `ManagedRoleToTransactions`, update `tests/integration/testdata/role/managed_role_transactions.json` to match — the `role/01_register.py` integration test compares each managed role's verb/type/kind matrix against this file and will fail otherwise.
+
+If you touched the registries or `Kind.Enum()`, regenerate the derived artifacts. The `goci` GitHub workflow reruns each of these and fails the PR on any uncommitted diff:
+
+```bash
+go run cmd/enterprise/*.go generate openapi # docs/api/openapi.yml
+go run cmd/enterprise/*.go generate authz # frontend/src/lib/authz/hooks/useAuthZ/permissions.type.ts
+go run cmd/enterprise/*.go generate config transaction-groups # frontend/src/schemas/generated/transactionGroups.schema.json
+```
+
+Commit whatever they change; never hand-edit these generated files.
+
+`generate authz` is allowlist-based: it only emits resources listed in the `allowedResources` map inside `runGenerateAuthz` in `cmd/authz.go`. For the new resource to surface in the UI's permission gating (AuthZButton and friends), add it there —
+
+```go
+coretypes.NewResourceRef(coretypes.ResourceMetaResourceThing).String(): true,
+```
+
+— then rerun `generate authz` and commit the regenerated `permissions.type.ts`. If the resource has no UI surface yet, skip the allowlist entry and the command produces no diff; that is expected.
+
+## Step 7: Write integration tests
+
+Read `references/integration-tests.md` for the suite layout, fixtures, and canonical allow/deny test shapes. The minimum bar for a new authz'd resource: each managed role's expected 200-vs-403 matrix on the new routes, and (if enterprise/FGA behavior matters) per-object scoping with a custom role — granted instance succeeds, non-granted instance gets 403, revoke flips it back to 403.
+
+Python test conventions that are hard rules in this repo: inline `requests.*` calls directly (never wrap single API calls in helpers), always pass `timeout=`, and run `make py-fmt && make py-lint` before finishing.
+
+## Verification
+
+Run these before declaring the work done:
+
+```bash
+make go-build-community
+```
+
+Consistency greps — every one of these must hold:
+
+- the new `Kind` var appears in BOTH the `Kinds` slice (`registry_kind.go`) and `Kind.Enum()` (`kind.go`)
+- the three `generate` commands from step 6 have been run and leave `git diff` clean when re-run
+- if the resource is UI-gated, it appears in `allowedResources` in `cmd/authz.go` and `permissions.type.ts` was regenerated
+- the new `Resource` var appears in the `Resources` slice (`registry_resource.go`)
+- every `ResourceDef` in the route file references the registered resource and one of its allowed verbs
+- every route's `SecuritySchemes` scope matches its `ResourceDef` verb
+- if `ManagedRoleToTransactions` changed, `managed_role_transactions.json` changed with it
+
+Then run the relevant integration suites (`make py-test-setup` from the repo root boots the environment; pytest runs from `tests/`):
+
+```bash
+uv run pytest --basetemp=./tmp/ -vv --reuse integration/tests/role/
+uv run pytest --basetemp=./tmp/ -vv --reuse integration/tests/<your-suite>/
+```
+
+General repo conventions apply throughout: no code comments (the grouping comments in `registry_managed_role.go` are the sole exception), complete descriptive names, and never commit without an explicit ask.
diff --git a/.claude/skills/authz-configurator/references/integration-tests.md b/.claude/skills/authz-configurator/references/integration-tests.md
new file mode 100644
index 0000000000..bec0d242fa
--- /dev/null
+++ b/.claude/skills/authz-configurator/references/integration-tests.md
@@ -0,0 +1,114 @@
+# Authz Integration Tests Reference
+
+Existing authz suites to imitate: `integration/tests/role/` (managed roles, custom-role CRUD, FGA scoping), `integration/tests/serviceaccount/` (API-key auth by role, role assignment), `integration/tests/passwordauthn/04_role.py` (user role changes, editor denied on admin endpoints).
+
+## Where a new test goes
+
+- Suite package: `tests/integration/tests/<suite>/` — pick the existing suite matching the feature's domain, or create a new package when the feature is its own domain.
+- File name: two-digit ordered prefix, `NN_<topic>.py` (`03_fga.py`, `04_roles.py`). Files in a suite run in order; setup tests early in the file establish state that later tests use.
+- Golden/testdata JSON: `tests/integration/testdata/<suite>/`, loaded via `fixtures.fs.get_testdata_file_path`.
+- If the change touched `ManagedRoleToTransactions`, update `tests/integration/testdata/role/managed_role_transactions.json` — `role/01_register.py` asserts every managed role's verb/type/kind matrix against it.
+
+## Environment and running
+
+`make` targets run from the repo root; direct `uv run pytest` commands run from `tests/`:
+
+```bash
+make py-test-setup # repo root — boot the stack once (~4 min), keep it with --reuse
+cd tests
+uv run pytest --basetemp=./tmp/ -vv --reuse integration/tests/<suite>/
+uv run pytest --basetemp=./tmp/ -vv --reuse integration/tests/role/03_fga.py::test_read_scoped_to_granted_role
+make py-test-teardown # repo root — destroy when done; never mix --reuse and --teardown
+make py-fmt && make py-lint # repo root — mandatory before finishing
+```
+
+## Fixtures you'll need
+
+From `tests/fixtures/auth.py` (registered via `pytest_plugins` in `tests/conftest.py`):
+
+- `signoz: types.SigNoz` — the running stack; build URLs with `signoz.self.host_configs["8080"].get("/api/v1/...")`.
+- `create_user_admin` — package-scoped; registers the first admin (`USER_ADMIN_EMAIL` / `USER_ADMIN_PASSWORD`). Take it as an unused argument in every test that needs the org to exist.
+- `get_token(email, password) -> str` — bearer token for a user.
+- `add_license(signoz, make_http_mocks, get_token)` — custom roles are enterprise-only; call it in a `test_apply_license` at the top of any suite that creates custom roles.
+- `create_active_user(signoz, admin_token, email=..., role="signoz-viewer", password=..., name=...) -> user_id` — invite + activate. `role` is a managed role name looked up verbatim (e.g. `signoz-viewer`).
+- `change_user_role(signoz, admin_token, user_id, old_role, new_role)` — e.g. `"signoz-viewer"` → your custom role name.
+
+From `tests/fixtures/role.py`:
+
+- `create_role(token, name, transaction_groups=None, description="") -> role_id` (fixture).
+- `find_role_by_name(signoz, token, name) -> role_id` — plain function, import `from fixtures.role import find_role_by_name`.
+- `transaction_group(relation, type_name, kind_name, selectors)` — builds one permission entry, e.g. `transaction_group("read", "metaresource", "thing", ["*"])` or with a specific instance name/ID as selector.
+
+From `tests/fixtures/serviceaccount.py`:
+
+- `create_service_account_with_key(signoz, token, name, role="signoz-admin") -> (sa_id, api_key)`.
+- Service accounts authenticate with the header `SIGNOZ-API-KEY: <key>`; users with `Authorization: Bearer <token>`.
+
+Hard rule: inline `requests.get/post/put/delete` calls directly in tests — do not wrap single API calls in helper functions or fixtures. Always pass `timeout=5`. Include the response text in assertion messages so failures are diagnosable.
+
+## Shape 1: managed-role matrix (community-safe)
+
+For each role, assert the expected status on each new route. Pattern from `serviceaccount/03_auth.py`:
+
+```python
+def test_editor_forbidden_on_admin_endpoint(signoz, create_user_admin, get_token):
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ _, api_key = create_service_account_with_key(signoz, token, "sa-role-editor", role="signoz-editor")
+
+ resp = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/service_accounts"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert resp.status_code == HTTPStatus.FORBIDDEN, f"expected 403, got {resp.status_code}: {resp.text}"
+```
+
+The user-token variant creates an editor/viewer via `create_active_user` and asserts 403 on the route, 200 for admin.
+
+## Shape 2: per-object FGA scoping (enterprise, custom role)
+
+Grant instance verbs on one object only; assert the other stays forbidden. Structure from `role/03_fga.py`:
+
+```python
+def test_apply_license(signoz, create_user_admin, make_http_mocks, get_token):
+ add_license(signoz, make_http_mocks, get_token)
+
+
+def test_setup_actor(signoz, create_user_admin, get_token, create_role):
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ create_role(
+ admin_token,
+ "thing-fga-actor",
+ [
+ transaction_group("read", "metaresource", "thing", [_TARGET_A_ID]),
+ transaction_group("list", "metaresource", "thing", ["*"]),
+ ],
+ )
+ user_id = create_active_user(signoz, admin_token, email=_ACTOR_EMAIL, role="signoz-viewer", password=_ACTOR_PASSWORD, name="thing fga actor")
+ change_user_role(signoz, admin_token, user_id, "signoz-viewer", "thing-fga-actor")
+
+
+def test_read_scoped_to_grant(signoz, create_user_admin, get_token):
+ token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)
+
+ resp = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/things/{_TARGET_A_ID}"), headers={"Authorization": f"Bearer {token}"}, timeout=5)
+ assert resp.status_code == HTTPStatus.OK, resp.text
+
+ resp = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/things/{_TARGET_B_ID}"), headers={"Authorization": f"Bearer {token}"}, timeout=5)
+ assert resp.status_code == HTTPStatus.FORBIDDEN, f"expected 403, got {resp.status_code}: {resp.text}"
+```
+
+Key semantics to test (they mirror the selector rules on the route side):
+
+- `read`/`update`/`delete` granted on a specific selector authorize only that instance; `*` authorizes all.
+- `create` and `list` are collection-scoped — only a `*` grant makes them pass, and `list` on `*` returns every instance including ones the caller can't `read` individually.
+- Revoking the grant (update the role's transaction groups, or `change_user_role` back) flips the previously-allowed call to 403.
+
+Module-level constants for names/emails (see `role/03_fga.py` — `_ACTOR_ROLE_NAME`, `_TARGET_A`) keep the setup test and the assertion tests in sync.
+
+## What "done" looks like
+
+- Every new route appears in at least one allow case and one deny case.
+- Suites that create custom roles start with `test_apply_license`.
+- `make py-fmt && make py-lint` pass.
+- The suite passes against a `--reuse` stack: `uv run pytest --basetemp=./tmp/ -vv --reuse integration/tests/<suite>/`.
diff --git a/.claude/skills/authz-configurator/references/route-wiring.md b/.claude/skills/authz-configurator/references/route-wiring.md
new file mode 100644
index 0000000000..cd8fc43522
--- /dev/null
+++ b/.claude/skills/authz-configurator/references/route-wiring.md
@@ -0,0 +1,155 @@
+# Route Wiring Reference
+
+All examples below are real code from `pkg/apiserver/signozapiserver/serviceaccount.go`. Match this style exactly.
+
+## Basic route: create (wildcard selector, response-phase ID)
+
+```go
+if err := router.Handle("/api/v1/service_accounts", handler.New(
+ provider.authzMiddleware.CheckResources(provider.serviceAccountHandler.Create, authtypes.SigNozAdminRoleName),
+ handler.OpenAPIDef{
+ ID: "CreateServiceAccount",
+ Tags: []string{"serviceaccount"},
+ Summary: "Create service account",
+ Description: "This endpoint creates a service account",
+ Request: new(serviceaccounttypes.PostableServiceAccount),
+ Response: new(types.Identifiable),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusCreated,
+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusConflict},
+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceServiceAccount.Scope(coretypes.VerbCreate)}),
+ },
+ handler.WithResourceDefs(handler.BasicResourceDef{
+ Resource: coretypes.ResourceServiceAccount,
+ Verb: coretypes.VerbCreate,
+ Category: coretypes.ActionCategoryAccessControl,
+ ID: coretypes.ResponseJSONPath("data.id"),
+ Selector: coretypes.WildcardSelector,
+ }),
+)).Methods(http.MethodPost).GetError(); err != nil {
+ return err
+}
+```
+
+Create checks the wildcard (can the caller create *any* instance?) but still records the new instance's ID for audit via `ResponseJSONPath` — the ID only exists after the handler runs.
+
+Instance routes (read/update/delete) differ only in verb, `ID: coretypes.PathParam("id")`, and `Selector: coretypes.IDSelector`. List routes use `WildcardSelector` and omit `ID` entirely.
+
+Pick the `Category` matching the resource's domain — grep `ActionCategory` in `pkg/types/coretypes/` for the registered values (`ActionCategoryAccessControl` is for access-control resources; observability resources use their own categories).
+
+## ID extractors (`pkg/types/coretypes/extractor.go`)
+
+| Extractor | Phase | Use for |
+|---|---|---|
+| `PathParam("id")` | request | ID in the URL path |
+| `BodyJSONPath("data.id")` | request | ID in the request body (gjson path) |
+| `BodyJSONArray("ids")` | request | multiple IDs in a body array |
+| `ResponseJSONPath("data.id")` | response | ID known only after the handler (create) |
+| `NewResourceIDExtractor(phase, fn)` | either | ID needs a lookup (see below) |
+| `OneID(extractor)` | — | lifts a single-ID extractor where a multi-ID one is required (`SourceIDs`/`TargetIDs`/`ChildIDs`) |
+
+Custom extractor example — the route path carries a service-account-role ID but the check needs the underlying role ID, so the extractor resolves it through the module:
+
+```go
+func (provider *provider) roleIDExtractor() coretypes.ResourceIDExtractor {
+ return coretypes.NewResourceIDExtractor(coretypes.PhaseRequest, func(ec coretypes.ExtractorContext) (string, error) {
+ if ec.Request == nil {
+ return "", nil
+ }
+
+ claims, err := authtypes.ClaimsFromContext(ec.Request.Context())
+ if err != nil {
+ return "", err
+ }
+
+ serviceAccountRoleID, err := valuer.NewUUID(mux.Vars(ec.Request)["id"])
+ if err != nil {
+ return "", err
+ }
+
+ serviceAccountRole, err := provider.serviceAccountGetter.GetServiceAccountRole(ec.Request.Context(), valuer.MustNewUUID(claims.OrgID), serviceAccountRoleID)
+ if err != nil {
+ return "", err
+ }
+
+ return serviceAccountRole.RoleID.String(), nil
+ })
+}
+```
+
+## Custom SelectorFunc
+
+Use one when the extracted ID is not what FGA objects use. Roles are the canonical case: routes receive a role UUID, but FGA role objects are keyed by role *name*. Always include the wildcard alongside the specific selector — authorization on `*` implies authorization on every instance:
+
+```go
+func (provider *provider) roleSelector(ctx context.Context, resource coretypes.Resource, id string, orgID valuer.UUID) ([]coretypes.Selector, error) {
+ roleID, err := valuer.NewUUID(id)
+ if err != nil {
+ return nil, err
+ }
+
+ role, err := provider.authzService.Get(ctx, orgID, roleID)
+ if err != nil {
+ return nil, err
+ }
+
+ return []coretypes.Selector{
+ resource.Type().MustSelector(role.Name),
+ resource.Type().MustSelector(coretypes.WildCardSelectorString),
+ }, nil
+}
+```
+
+## Linking routes: siblings (peer-to-peer)
+
+Attaching a role to a service account requires `attach` on **both** resources — the same verb checked on each side. Advertise both scopes:
+
+```go
+SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceServiceAccount.Scope(coretypes.VerbAttach), coretypes.ResourceRole.Scope(coretypes.VerbAttach)}),
+// ...
+handler.WithResourceDefs(handler.AttachDetachSiblingResourceDef{
+ Verb: coretypes.VerbAttach,
+ Category: coretypes.ActionCategoryAccessControl,
+ SourceResource: coretypes.ResourceServiceAccount,
+ SourceIDs: coretypes.OneID(coretypes.BodyJSONPath("serviceAccountId")),
+ SourceSelector: coretypes.IDSelector,
+ TargetResource: coretypes.ResourceRole,
+ TargetIDs: coretypes.OneID(coretypes.BodyJSONPath("roleId")),
+ TargetSelector: provider.roleSelector,
+}),
+```
+
+The detach route (`DELETE .../service_account_roles/{id}`) uses `VerbDetach`, and its path `{id}` identifies the **assignment** (the service account role), not the role. Both IDs are resolved from it via lookup-helper extractors — `provider.serviceAccountIDExtractor()` and `provider.roleIDExtractor()` fetch the assignment and return its service account ID and role ID.
+
+## Linking routes: parent-child
+
+Creating an API key *under* a service account checks two different things: `create` on the child resource, and `attach` on the parent. Declare both defs in the same `WithResourceDefs`:
+
+```go
+handler.WithResourceDefs(
+ handler.BasicResourceDef{
+ Resource: coretypes.ResourceMetaResourceFactorAPIKey,
+ Verb: coretypes.VerbCreate,
+ Category: coretypes.ActionCategoryAccessControl,
+ ID: coretypes.ResponseJSONPath("data.id"),
+ Selector: coretypes.WildcardSelector,
+ },
+ handler.AttachDetachParentChildResourceDef{
+ Verb: coretypes.VerbAttach,
+ Category: coretypes.ActionCategoryAccessControl,
+ ParentResource: coretypes.ResourceServiceAccount,
+ ParentID: coretypes.PathParam("id"),
+ ParentSelector: coretypes.IDSelector,
+ ChildResource: coretypes.ResourceMetaResourceFactorAPIKey,
+ ChildIDs: coretypes.OneID(coretypes.ResponseJSONPath("data.id")),
+ },
+),
+```
+
+Within the parent-child def, the child is only recorded for audit — the authz check on the child comes from its own `BasicResourceDef`. Deletion mirrors this with `VerbDelete` on the child and `VerbDetach` on the parent (see the `/api/v1/service_accounts/{id}/keys/{fid}` DELETE route).
+
+## Legacy gates — do not use for new routes
+
+`ViewAccess`/`EditAccess`/`AdminAccess` only check "does the caller hold one of these roles". They give up per-resource granularity, produce no audit resources, and don't advertise scopes. They exist for old routes; new routes use `CheckResources` + `ResourceDef`. `OpenAccess` performs no authorization at all (authentication still applies — used for `/me`-style routes); `CheckWithoutClaims` is for anonymous routes such as public dashboards.
+
+Full def types live in `pkg/http/handler/resourcedef.go`; middleware behavior in `pkg/http/middleware/authz.go` and `pkg/http/middleware/resource.go`.