# Roles, permissions, scopes and desks (Prompt 2)

Authorization runs through `AccessService`: role permissions plus direct allows,
minus active direct denies. Expired overrides do not affect access, even before the
cleanup job runs. An active super-admin bypasses permission and scope checks.
Inactive users fail permission checks.

Sanctum authenticates both CMS cookie sessions and bearer tokens using the `users`
provider. Both clients share the canonical Spatie `web` permission catalogue and
role assignments; `sanctum` is explicitly configured with the same provider. There
is no separate token-only permission matrix. Spatie's cache uses Redis, except for
the test suite's array store.

## Endpoints

All paths below start with `/api/v1`. CMS routes require Sanctum authentication,
an active account, a token with the `cms` ability (or a first-party cookie session),
role-based 2FA enrollment, and the CMS rate limiter. Dangerous permissions also
require a token/session-specific 2FA confirmation within 15 minutes.

| Method and path | Permission | Input |
| --- | --- | --- |
| `GET cms/permissions` | `access.permissions.view` | Catalogue grouped by module |
| `GET cms/roles` | `access.permissions.view` or `access.roles.manage` | Roles, permission names, user counts |
| `POST cms/roles` | `access.roles.manage` | `name`, translated `label`, `permissions[]`, optional metadata |
| `PATCH cms/roles/{name}` | `access.roles.manage` | Translated label/description, default scope, 2FA requirement |
| `DELETE cms/roles/{name}` | `access.roles.manage` | Custom roles only |
| `PUT cms/roles/{name}/permissions` | `access.roles.manage` | `permissions[]` |
| `PUT cms/users/{uid}/roles` | `access.users.assign-roles` | `roles[]` |
| `POST cms/users/{uid}/permissions` | `access.users.assign-permissions` | `permission`, `effect: allow|deny`, `reason`, optional future `expires_at` |
| `DELETE cms/users/{uid}/permissions/{name}` | `access.users.assign-permissions` | Optional `reason` |
| `PUT cms/users/{uid}/scopes` | `access.users.manage-scopes` | `scopes: [{type, key}]`; empty list removes restrictions |
| `GET cms/users/{uid}/effective-permissions` | `access.users.view` | Effective flags, sources and scopes |
| `GET cms/desks` | `access.users.view` or `access.users.manage-scopes` | Desks and member counts |
| `POST cms/desks` | `access.users.manage-scopes` | Translated `name`, `slug`, `type`, optional district/head |
| `PATCH cms/desks/{uid}` | `access.users.manage-scopes` | Desk fields |
| `PUT cms/desks/{uid}/members` | `access.users.manage-scopes` | `members[]` of user ULIDs |
| `GET me/permissions` | Signed-in active user | Flat permissions, dangerous names, roles, public scope keys |

Role and permission routes use natural names; users and desks use ULIDs. Numeric
database IDs remain internal. Scope keys are geographic slugs or desk ULIDs/slugs.
The category/content-type resolvers are registered by later content prompts.

## Guard rails

Actors cannot grant permissions they do not hold, assign a role that grants them,
edit their own access, or edit a role they hold (except the super-admin). Only a
super-admin changes super-admin membership. Seeded system roles cannot be deleted
or renamed, and the super-admin role cannot be edited. Demotion and suspension
serialize through the super-admin role row and preserve an active super-admin.
The mandatory 2FA requirement on super-admin, system-admin, desk-head and editor
cannot be disabled through role metadata updates.

Assigning a role through ordinary user create/update requires
`access.users.assign-roles` and recent 2FA as well as the endpoint's user permission.
Horizon, Telescope and Scramble use `system.horizon`, `system.telescope` and
`api-docs.view` respectively.

## Scope integration for later models

Use `HasScopedVisibility`, implement its public static `scopeColumns()` mapping,
and apply `Model::query()->visibleTo($user)` in the repository. Call
`AccessService::can($user, $permission, $model)` from its policy. Gate catalogue
abilities also pass the model through, for example `$user->can('media.view', $item)`.

Values of a scope type combine with OR; non-geographic types combine with AND.
Geographic scopes form a union across provinces, districts and local levels and
expand downward. Models without a local-level column use its district. Active
desk membership adds desk scope. `ReporterApplication` already integrates the
geographic restriction; content models are built in later prompts.

## Cache, audit and expiry

`CachedUserAccessRepository` stores `perm:user:{id}` under tags `permissions` and
`permissions:user:{id}`, for at most one hour or the next override expiry. Its
request/job-scoped memo checks expiry at every read. Spatie attachment events and
role/permission/override/scope/desk model events invalidate access synchronously
and after commit. Desk member changes invalidate both added and removed users.
Use the access and desk services for audited mutations rather than direct writes.

`ExpirePermissionOverrides` runs every five minutes on the `default` queue. It
removes expired overrides and associated direct allows and records
`permission_override_expired`. Service writes record `roles_synced`,
`permission_granted`, `permission_denied`, `permission_revoked`, `scopes_set`,
`role_created/updated/deleted`, `role_permissions_synced`, and
`desk_created/updated/members_synced` through `AuditService`.

## Seeders and reference status

`PermissionsSeeder` upserts catalogue entries without deleting custom permissions.
`RolesSeeder` creates 16 system roles; existing permission matrices are preserved
unless `ROLES_SEED_FORCE=true` (read through configuration). `DesksSeeder` creates
national/beat desks and the nine Sudurpaschim district desks, preserving heads and
members. `DemoUsersSeeder` supplies one user per role with representative scopes
and refuses environments other than local/staging. Its password comes from
`DEMO_USER_PASSWORD`. `ReferenceDataSeeder` is the test/reference entry point.

The supplied SRS PDF section 3.1 confirms the 16 roles. The PDF contains no Appendix
B or C with the exact permission catalogue/matrix referenced by the build prompt.
The existing catalogues are retained pending those detailed appendices; this is
recorded in [prompt2.md](prompt2.md).
