Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Add the 6.0 admin RBAC plan (spree/spree#14164)

Damian Legawiecd673e306f495
diff --git a/CLAUDE.md b/CLAUDE.md
index 8f5ace30df..da347ced4e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -16,6 +16,7 @@ Active plans (6.0 target, work pending):
- `6.0-cart-order-split.md` — Cart/Order model separation, dual-FK owner everywhere (`cart_id`/`order_id` exactly-one, `#owner` as method — NOT polymorphic), idempotent copy-on-completion (`Order#cart_id` unique, order-before-payment), Order state machine removed (Checkout::Requirements for steps; payment/fulfillment statuses derived-then-persisted via one recompute service). **Shipped to 6-0-dev (feature/6-0-core-rewrite Waves 1+5):** Cart owns checkout end to end, machine + `spree_orders.state` gone, `Carts::Complete` three-phase pipeline live, `Orders::UpdateStatuses` sole status writer; only Wave 7 data migration (incomplete orders → carts) remains
- `6.0-admin-api.md` — Admin REST API conventions, auth, endpoint list (~300 endpoints)
- `6.0-admin-spa.md` — React admin architecture, extension points, table registry, i18n + server-error mapping
+- `6.0-admin-rbac.md` — First-class admin RBAC (spree/spree#14164; design finalized 2026-08-07): **one grant system, staff-only**. The permission catalog IS the API-key scope vocabulary (`read_*`/`write_*` per resource; `ApiKey::SCOPES` derives from the catalog; new `staff` pair split from `settings`); **permission sets are deleted at 6.0 with NO bridge** (recorded exception to the bridges convention — `assign` raises an upgrade tripwire; record-level custom rules → `register_ability`). **Roles are pure data** — no code-managed roles, no runtime merge; roles-as-code = seeds or Admin API; extensions register catalog resources, never roles. Enforcement unifies on the key gate for JWT staff AND secret keys (`ScopedAuthorization` generalized); CanCanCan demoted to internal plumbing. DB: JSON key array + `description` + `mutable` on `spree_roles` (admin seeded immutable — NamedType pattern; hosts can lock compliance roles the same way); roles CRUD + `GET /admin/permissions` + `/me.permission_keys` + 403 `details.required_permission`; full-page role editor (`/settings/roles/$roleId`) sharing one PermissionPicker with the API-keys page (client-side templates, no seeds). Storefront has NO roles — customer baseline is internal ability code, scope-fetching is the enforcement; B2B company roles are a separate future Enterprise system (never share the vocabulary); catalog visibility per group/company is data scoping, never a permission key. **Constraints now:** no new `PermissionSets::` classes or `Spree.permissions.assign` calls; models authorized by new admin controllers must be covered by a catalog entry; new sensitive resources get their own catalog resource, never ride `settings`; storefront code never consults `Spree::Role` or the catalog.
- `6.0-product-types.md` — Prototype → ProductType rename, custom-field schema enforcement. **Creation-time template (2026-08-06):** type edits never mutate existing products (custom-field form/validation + `fulfillment_types` are live by reference; option types/categories seed additively at attach; explicit previewed `ApplyToProducts` job is the only bulk path); per-product type detach/reassign allowed (non-destructive), `required` on a type's custom field is **advisory only** (dashboard marker; no server validation — Spree writes product + fields in two steps), no Store API exposure. **Fully shipped** (all phases, Phase 2 rescoped + delivered 2026-08-06)
- `6.0-remove-master-variant.md` — Eliminate is_master, add default_variant_id FK on Product. **Shipped to 6-0-dev (PR #14265):** is_master removed from all models, default_variant_id + `spree:remove_master_variant` data-migration rake landed; only the physical is_master column drop remains (6.1 cleanup).
- `6.0-typed-stock-movements.md` — Replace generic StockMovement with typed kinds + concrete FKs
diff --git a/docs/plans/5.5-admin-api-key-scopes.md b/docs/plans/5.5-admin-api-key-scopes.md
index 9329169b8f..94d0e78534 100644
--- a/docs/plans/5.5-admin-api-key-scopes.md
+++ b/docs/plans/5.5-admin-api-key-scopes.md
@@ -14,6 +14,20 @@ This plan introduces **scopes** on `Spree::ApiKey` so secret keys can carry thei
## Key Decisions (do not deviate without discussion)
+> **Superseded in part (2026-08-07 — see `6.0-admin-rbac.md`):** at 6.0 the scope
+> vocabulary becomes THE permission catalog — the single grant vocabulary for
+> staff roles and API keys alike (permission sets are deleted, with one-release
+> bridges). `Spree::ApiKey::SCOPES` derives from that catalog instead of a frozen
+> literal (extension-registered resources become mintable scopes), and the staff
+> endpoints (`/admin_users`, `/invitations`, `/roles`) move off `settings` into a
+> new `read_staff`/`write_staff` pair. The "don't add scope checks to
+> JWT-authenticated paths" decision below is also superseded: the key gate
+> generalizes to JWT staff (their role keys play the role scopes play for keys),
+> becoming the primary admin enforcement for both principals. Still standing:
+> resource granularity, `write_*` implies `read_*`, the aliases, per-controller
+> `scoped_resource` declarations (now additionally the source of 403
+> `required_permission` diagnostics), and scope immutability on secret keys.
+
- **Scope vocabulary is `read_<resource>` / `write_<resource>` per top-level admin resource** (~15 scopes). `write_*` implies `read_*`.
- **Convenience aliases `read_all` and `write_all`** for full read or full read+write. Aliases expand at check time, not at storage time, so admins can re-toggle later without rewriting stored values.
- **Scopes apply to API keys only.** JWT admin users keep CanCanCan-based authorization (they have `Spree::Role`s; that surface is unchanged).
diff --git a/docs/plans/6.0-admin-api.md b/docs/plans/6.0-admin-api.md
index 7137f6555e..c835d33486 100644
--- a/docs/plans/6.0-admin-api.md
+++ b/docs/plans/6.0-admin-api.md
@@ -815,7 +815,9 @@ API key scopes: `read_vendors` / `write_vendors`, `read_commissions` / `write_co
- [ ] `PATCH /api/v3/admin/roles/:id`
- [ ] `DELETE /api/v3/admin/roles/:id`
-> Custom-role CRUD is deferred; roles are currently seeded/predefined and exposed read-only.
+> Custom-role CRUD ships with `6.0-admin-rbac.md`: DB-backed role permissions
+> (catalog keys), a `GET /permissions` catalog endpoint, `/me.permission_keys`,
+> and the `settings` → `staff` scope split for this whole staff group.
### Invitations
- [x] `GET /api/v3/admin/invitations`
diff --git a/docs/plans/6.0-admin-rbac.md b/docs/plans/6.0-admin-rbac.md
new file mode 100644
index 0000000000..d4ec105c1c
--- /dev/null
+++ b/docs/plans/6.0-admin-rbac.md
@@ -0,0 +1,488 @@
+# Admin RBAC and Permission Management
+
+**Status:** Design Finalized
+**Target:** Spree 6.0
+**Depends on:** `5.5-admin-api-key-scopes.md` (shipped), `6.0-admin-api.md`, `6.0-admin-spa.md`, `6.0-platform-auth.md` (Customer/Staff split)
+**Author:** Damian (from spree/spree#14164 by @caspianlwoods)
+**Last updated:** 2026-08-07
+
+## Summary
+
+Merchants should be able to create staff roles and edit their permissions from the
+dashboard, without writing Ruby in an initializer. This plan replaces the
+permission-set system with **one grant model**: a flat catalog of
+`read_<resource>` / `write_<resource>` keys — the same vocabulary secret API keys
+already use ([5.5-admin-api-key-scopes.md](5.5-admin-api-key-scopes.md)). **Roles
+are pure data**: keys live on the role row, edited in the dashboard, via the Admin
+API, or seeded with plain ActiveRecord — there is no code-managed role concept and
+no runtime merge. Code defines the *vocabulary* (catalog registrations, including
+extensions'); data defines the roles. One catalog powers the role editor, the
+API-key scope picker, `/me`, endpoint enforcement, and authorization-failure
+diagnostics.
+
+The system is **staff-only**. The storefront has no roles: customer authorization
+is ownership (scope-fetching: `current_user.addresses`, cart tokens) plus a fixed
+internal baseline — not something a merchant edits. B2B company accounts (multiple
+users per company, buyer/approver roles, hierarchies, spend limits) are a separate
+future Enterprise system with its own vocabulary and are explicitly out of scope
+here; sharing a registry with them would poison the meaning of every key
+(`write_orders` means "manage the store's orders" to staff and "place my company's
+orders" to a purchaser — those must never be the same token).
+
+Much of what issue #14164 asks for already exists and only needs to be surfaced:
+store-scoped role assignments work end to end (`Spree::RoleUser` + per-store
+resolution in `Spree::Ability` + the staff API), `RoleGrantGuard` already blocks
+privilege-escalating grants, and `/me` already feeds the dashboard's permission
+mirror. What is genuinely new: the catalog registry, a `permissions` column on
+`Spree::Role`, role CRUD in the Admin API, model-level protection of the admin
+role, unified key-based enforcement for both admin principals, and the dashboard
+pages.
+
+## Key Decisions (do not deviate without discussion)
+
+### The grant model
+
+- **The permission catalog is the API-key scope vocabulary.** Grantable units are
+ `read_<resource>` / `write_<resource>` keys, exactly the tokens in
+ `Spree::ApiKey::SCOPES`. No parallel `orders.read` dot-grammar — the scope
+ tokens shipped in 5.5 and are public API. The UI shows translated labels, not
+ raw keys.
+- **Resource granularity, not action granularity** — reaffirming the 5.5 scopes
+ decision. No `cancel_orders` / `approve_orders` keys. The motivating example
+ ("customer service reads orders but cannot refund") already falls out of
+ resource granularity because `payments`, `refunds`, `gift_cards`, and
+ `store_credits` are separate resources from `orders`.
+- **Permission sets are deleted at 6.0 — with no compatibility bridge
+ (2026-08-07).** This is a deliberate exception to the "every 6.0 rename keeps
+ a one-release bridge" convention: it is a system removal, not a rename, and a
+ behavior-preserving shim would have to carry the runtime-union machinery the
+ removal exists to kill. Old initializers fail loudly at boot (`NameError` on
+ the deleted set constants; `Spree.permissions.assign` raises with an
+ upgrade-guide pointer — a tripwire, not a bridge). Migration is genuinely
+ trivial: delete the initializer lines, recreate the role in the editor.
+ Fail-closed is the right failure mode for permissions — nothing boots with
+ staff silently over- or under-privileged. Custom rules that mixed
+ record-level conditions into sets migrate to
+ `Spree::Ability.register_ability` — the single remaining low-level escape
+ hatch. (Two earlier same-day drafts — sets kept as "bundles" over the
+ catalog, then a one-release `assign` bridge with an import task — were both
+ rejected as complexity serving only back-compat comfort in the breaking
+ window.)
+- **Roles are pure data — there is no code-managed role concept (2026-08-07).**
+ No `Spree.permissions.grant`, no runtime merge, no union semantics, no
+ "granted in code" locked rows: the editor is WYSIWYG and the row is the whole
+ truth. "Roles as code" is served by seeds
+ (`Spree::Role.find_or_create_by!(name: 'support').update!(permissions: [...])`
+ is plain ActiveRecord) or by the Admin API with a secret key. Extensions
+ register catalog resources — never roles. This matches the entire field:
+ Saleor (permission groups via dashboard/GraphQL only), Vendure (roles are DB
+ entities; code defines only the permission catalog and optional initial
+ seeds), Medusa (no OSS RBAC at all), Shopify/commercetools (UI/API only).
+- **Role permissions are a JSON array of concrete keys on `spree_roles`,**
+ mirroring `Spree::ApiKey#scopes` storage exactly (native JSON column,
+ `attribute` default `[]`, known-key validation). No join table, no stored
+ aliases (`read_all` / `write_all` stay API-key conveniences; the editor offers
+ select-all client-side).
+- **Locked roles use a `mutable` column — the NamedType pattern applied to
+ roles (2026-08-07).** The admin role seeds with `mutable: false` (plus a
+ belt-and-braces guard on the `admin` name); a host that needs a
+ compliance-locked role sets `mutable: false` from seeds or console and the
+ editor renders it read-only. This covers the one legitimate thing the code
+ path used to provide — roles staff cannot edit — without a second grant
+ source.
+
+### Scope of the system
+
+- **Staff-only (2026-08-07).** The catalog, the editor, `Spree.permissions`, and
+ role resolution apply to admin-user principals only. `Spree::Ability` resolves
+ roles solely for `Spree.admin_user_class` principals; customer principals get
+ the storefront baseline directly — which also drops a per-request `role_users`
+ query for logged-in customers and aligns with the platform-auth Customer/Staff
+ split (a customer holding the admin role stops being a concept at 6.0).
+- **The storefront baseline is internal code, not a registry entry
+ (2026-08-07).** `:default` and `DefaultCustomer` cease to be public concepts.
+ What remains is a fixed storefront ability (ownership hash conditions, guest
+ cart tokens, invitation acceptance) behind the Store API, with scope-fetching
+ as the primary enforcement — which it already is. Merchants never configure
+ customer permissions; there is nothing to configure.
+- **B2B company roles are out of scope and must stay a separate system
+ (2026-08-07).** Company-account permissions (buyer/approver, location roles,
+ hierarchies, spend limits, order approvals) are ownership-scoped and
+ workflow-shaped — what the flat catalog deliberately cannot express — and they
+ are an Enterprise feature. Industry precedent is unanimous on separation:
+ commercetools Business Unit associate roles, Shopify B2B company-contact
+ permissions, and Medusa's B2B employee/spend-limit models are all distinct from
+ staff RBAC. The polymorphic seams (`RoleUser#user`, `RoleUser#resource`) stay
+ as-is and uncommitted — Enterprise may reuse the storage or ship its own
+ models; this plan promises nothing.
+- **Catalog/product visibility per customer group or company is data scoping,
+ never a permission key.** "Can see catalog B" is a property of what the
+ storefront query returns (channels/catalogs work, `6.1-channels-catalogs-b2b.md`),
+ not of an authorization registry. Non-goal here, recorded so nobody models it
+ as one later.
+
+### Enforcement
+
+- **The key gate is the primary check for both admin principals (2026-08-07).**
+ `ScopedAuthorization` generalizes: every admin request resolves a principal key
+ set — a JWT staffer's expanded role keys, a secret key's scopes — and checks
+ `<read|write>_<scoped_resource>` against it. The per-controller
+ `scoped_resource` declaration becomes the enforcement contract for everyone,
+ which is what actually fixes the issue's "menus, API and CanCanCan drift apart"
+ complaint. This supersedes the 5.5 constraint "don't add scope checks to
+ JWT-authenticated paths" (noted there).
+- **CanCanCan is demoted to internal plumbing, not dropped (2026-08-07).** Keys
+ compile to CanCanCan rules behind the gate, because three things still need it:
+ the storefront baseline's record-level rules, `register_ability` host rules,
+ and sixty-odd admin controllers plus the SPA mirror that speak
+ `authorize!`/rules today — rewriting the enforcement layer and the grant model
+ in one release doubles the risk. Nothing public configures CanCanCan anymore.
+ Removing the gem from the admin path becomes a mechanical 6.1+ cleanup option,
+ not a 6.0 goal.
+- **Role protection lives on the model, not in the ability layer.** Rename,
+ permission changes, and destroy are blocked by `Spree::Role` guards keyed off
+ `mutable` (plus the `admin`-name guard), following the 2026-08-05 NamedType
+ decision — ability rules don't fire for secret-key principals, so protection
+ must live where every path hits it.
+- **A role in use cannot be deleted.** `can_be_deleted?` is false while
+ `role_users` or pending invitations reference the role. Reassign staff first.
+- **Role CRUD gets the same escalation guard as role assignment.** Creating or
+ updating a role may only grant keys the caller effectively holds (expanded:
+ `write_x` implies `read_x` before comparison). `RoleGrantGuard` switches its
+ comparison from permission-set classes to expanded key sets; secret-key callers
+ are bounded by their own scopes — the anti-amplification rule API keys already
+ have.
+- **403 diagnostics reuse the scope declaration.** `handle_access_denied` adds
+ `details: { required_permission: "<read|write>_<scoped_resource>" }` — the JWT
+ twin of the shipped `details.required_scope`. Development logs additionally
+ include the caller's roles and effective keys.
+
+### Interactively settled 2026-08-07
+
+- **`staff` splits out of the `settings` scope.** New `read_staff` /
+ `write_staff` pair covers `/admin_users`, `/invitations`, `/roles` and the
+ AdminUser/Invitation/Role/RoleUser subjects; those controllers re-scope from
+ `settings` to `staff`. Team management is the escalation path and must be
+ grantable separately from store configuration. **Accepted trade-off:** secret
+ keys minted with `settings` before 6.0 lose the staff endpoints — Developer
+ Preview breakage, called out in the release notes.
+- **`Spree::ApiKey::SCOPES` derives from the catalog.** Key validation,
+ `ScopedAuthorization`, and the OpenAPI scope docs read the registry; an
+ extension registering a resource gets the role-editor row and mintable
+ `read_x`/`write_x` scopes in one step. **Accepted trade-off:** the scope list
+ is boot-dynamic — auditing "what can keys do" means consulting the running
+ catalog (`/permissions`), not a frozen constant.
+- **The role editor is a full page** — `/settings/roles/$roleId` +
+ `/settings/roles/new`, not a sheet. The grouped matrix, presets, and a members
+ panel need the room; Shopify/Vendure set the pattern.
+- **No seeded roles; the create flow offers client-side templates.** "Order
+ manager" / "Merchandiser" / "Support" presets pre-fill the matrix; nothing
+ lands in the DB until saved. **Accepted trade-off:** templates are
+ dashboard-only — headless/API consumers start from the bare protected `admin`
+ role.
+
+### Already true, kept deliberately
+
+- **Store-scoped role assignment ships as-is; no new scoping model.** Per-store
+ roles already work (`RoleUser` + ability + staff API). Vendor-scoped
+ assignments arrive with `6.0-multi-vendor-marketplace.md` through the same
+ polymorphic `resource`.
+- **`/me` keeps the CanCanCan rules dump and adds `permission_keys`.** The SPA's
+ `can(action, subject)` API stays stable — the catalog knows which resource owns
+ each subject, so dashboard-core resolves subject → key internally; the rules
+ dump remains for record-level hints while any remain.
+
+## Design Details
+
+### Permission catalog
+
+A registry on `Spree.permissions` (the existing `PermissionConfiguration`
+object), populated by core at boot and open to extensions:
+
+```ruby
+# core registration (engine initializer)
+Spree.permissions.register_resource(:orders, group: :orders, subjects: -> {
+ [Spree::Order, Spree::LineItem, Spree::TaxLine, Spree::Discount, Spree::Fee,
+ Spree::Return, Spree::Exchange, Spree::Claim]
+})
+
+# an extension — one call yields the role-editor row AND mintable key scopes
+Spree.permissions.register_resource(:reviews, group: :catalog, subjects: -> {
+ [SpreeReviews::Review]
+})
+```
+
+Each registration yields two catalog entries — `read_<resource>` (compiles to
+`can [:read, :admin], subject` per subject) and `write_<resource>`
+(`can :manage, subject`) — unless `write: false` (dashboard). Subjects are
+lambdas for load-order safety. Labels and descriptions resolve through `Spree.t`
+(`spree.permissions.<key>.{label,description}`), so backend extensions localize
+without touching the SPA.
+
+Core registers one entry per resource of the current scope vocabulary:
+
+| Resource | Group | Subjects (canonical) |
+|---|---|---|
+| `orders` | Orders | Order, LineItem, TaxLine, Discount, Fee, Return, Exchange, Claim |
+| `payments` | Orders | Payment |
+| `fulfillments` | Orders | Fulfillment |
+| `refunds` | Orders | Refund |
+| `gift_cards` | Orders | GiftCard, GiftCardBatch |
+| `store_credits` | Orders | StoreCredit |
+| `products` | Catalog | Product, ProductType, Variant, OptionType, OptionValue, Price, PriceList, PriceRule, Asset, ProductPublication |
+| `categories` | Catalog | Category, Taxonomy, ProductCategory |
+| `collections` | Catalog | Collection, ProductCollection, CollectionRule |
+| `stock` | Catalog | StockItem, StockLocation, StockMovement, StockTransfer, StockReservation |
+| `promotions` | Marketing | Promotion, PromotionRule, PromotionAction, PromotionCategory, CouponCode |
+| `customers` | Customers | `Spree.customer_class`, Address, CreditCard, CustomerGroup |
+| `settings` | Settings | Store, PaymentMethod, DeliveryMethod, DeliveryZone, Market, Channel, TaxCategory, TaxRate, reasons, MetafieldDefinition, Policy, AllowedOrigin, OrderRoutingRule, … (today's ConfigurationManagement list minus webhooks) |
+| `webhooks` | Settings | WebhookEndpoint, WebhookDelivery |
+| `api_keys` | Access | ApiKey |
+| `staff` *(new at 6.0)* | Access | `Spree.admin_user_class`, Invitation, Role, RoleUser |
+| `dashboard` (read-only) | Analytics | `:dashboard` |
+
+Notes:
+
+- Today `AdminUser` and `Invitation` subjects are grantable only through
+ SuperUser's `manage :all`. The `staff` entry closes that gap so a "Store
+ manager" custom role can manage the team without full admin.
+- `Spree::ApiKey::SCOPES` becomes catalog-derived: known-scope validation,
+ `ScopedAuthorization`, and OpenAPI docs enumerate
+ `Spree.permissions.catalog.keys` plus the `read_all`/`write_all` aliases. Keys
+ minted under a vocabulary that later shrinks stay revocable (the existing
+ `scopes_enforceable?` guard covers this).
+- Catalog entries are pure Axis A: flat capability grants, no block conditions,
+ no domain-invariant `cannot` rules (see `decisions.md` 2026-08-05). The
+ `allow_cancel?` / `can_be_deleted?` block rules currently inside
+ `OrderManagement`/`SuperUser` move to model/workflow guards as part of this
+ work (guard + spec first, then drop the ability condition).
+
+### Roles are data
+
+```ruby
+# the only "roles as code" story — plain ActiveRecord in db/seeds.rb (or the Admin API):
+Spree::Role.find_or_create_by!(name: 'support')
+ .update!(permissions: %w[read_orders read_customers], description: 'Read-only support')
+```
+
+`Spree::Role` gains:
+
+```ruby
+add_column :spree_roles, :description, :string
+add_column :spree_roles, :permissions, <jsonb|json>, default: [], null: false
+add_column :spree_roles, :mutable, :boolean, default: true, null: false
+```
+
+- `attribute :permissions, default: []` + normalizing setter — the exact
+ `ApiKey#scopes` pattern.
+- Validation: every key must be a concrete catalog key (no aliases).
+- Guards keyed off `mutable` (NamedType pattern): name, permissions, and
+ destroy are blocked while `mutable` is false. The `admin` role seeds with
+ `mutable: false` and additionally can never be renamed or deleted by name
+ guard. `can_be_deleted?` also requires no `role_users` and no pending
+ invitations.
+- The `admin` role reports the full catalog as its permissions (display); other
+ roles report exactly their stored keys — there is no computed merge.
+
+`Spree.permissions` ends up doing exactly one thing: catalog registration.
+`assign` raises with an upgrade-guide pointer (tripwire for 5.x initializers);
+there is no `grant`, no bridge, no union.
+
+The storefront baseline moves out of the registry entirely: `Spree::Ability`
+applies it directly for customer/guest principals (ownership hash conditions,
+guest tokens — today's `DefaultCustomer` body, now internal). Role resolution
+(`determine_role_names` + key activation from the role rows) runs only for
+admin-user principals. The `admin` role activates the full catalog; its former
+safety rules are model guards by then.
+
+`Spree::Ability.register_ability` remains the single low-level escape hatch for
+host rules that don't fit keys ("support sees only their region's orders") and
+the migration target for custom permission sets that mixed record-level
+conditions into grants.
+
+### Admin API
+
+```
+GET /api/v3/admin/permissions # catalog discovery
+GET /api/v3/admin/roles # existing
+GET /api/v3/admin/roles/:id # existing
+POST /api/v3/admin/roles # new
+PATCH /api/v3/admin/roles/:id # new
+DELETE /api/v3/admin/roles/:id # new
+```
+
+- **`/permissions`** returns the catalog:
+ `[{ key, resource, kind, group, label, description }]`. Authenticated,
+ `skip_scope_check!` (vocabulary, not data — same class as `/tags`), localized,
+ HTTP-cacheable per boot. Replaces the dashboard's hardcoded `SCOPE_GROUPS`
+ array and its "keep in sync with the server" comment.
+- **Roles CRUD** on the existing controller (re-scoped to `staff`):
+ `permitted_params` are `name`, `description`, `permissions: []` (read/write
+ symmetry with the serializer). Create/update run the key-set escalation check;
+ destroy surfaces the model-guard errors as 422.
+- **Serializer** grows `description`, `permissions`, `mutable` (boolean — false
+ renders read-only in the editor), `users_count` (assignments on the current
+ store).
+- **`/me`** adds `permission_keys` (expanded effective keys for the current
+ store) alongside the existing rules dump.
+- **Enforcement:** the generalized key gate checks every admin request's
+ principal key set against `<read|write>_<scoped_resource>`; CanCanCan runs
+ behind it (compiled from the same keys + `register_ability` rules), so
+ `authorize!`/`accessible_by` in controllers keep working unchanged during 6.0.
+- **403 diagnostics:** `details.required_permission` from the `scoped_resource`
+ declaration; development logs include roles + effective keys.
+
+### Dashboard
+
+- **Subject constants:** add `Role: 'Spree::Role'` to `dashboard-core`'s
+ `lib/permissions.ts`. `can(action, subject)` keeps its signature; dashboard-core
+ resolves subject → owning resource key via the catalog.
+- **Navigation:** `settings.roles` in the `team` group (position 150, between
+ Staff and API keys), gated by `subject: Subject.Role`.
+- **Roles list** (`/settings/roles`): name, description, permission summary (the
+ `ScopeList` badge treatment: "Full access" for admin, first N keys + overflow),
+ members count, lock icon on immutable roles. Row actions: edit,
+ duplicate (opens the new-role page pre-filled), delete (confirm; disabled with
+ tooltip while `can_be_deleted?` is false).
+- **Role editor** (`/settings/roles/$roleId`, full page; `/settings/roles/new`):
+ name, description, then the permission matrix grouped by catalog group — one
+ row per resource with a **None / View / Full** segmented control (View =
+ `read_x`, Full = `write_x`; read-only resources render View/None). Group-level
+ select-all plus "Read only" / "Full access" presets. A summary sidebar shows
+ the effective permission count and the role's members on this store.
+ Immutable roles (`mutable: false`) render the whole editor read-only. Keys
+ outside the caller's own grant render disabled (the API would reject them —
+ don't offer them). The create
+ page opens with a template picker — Blank / Order manager / Merchandiser /
+ Support — pre-filling the matrix client-side; templates are dashboard
+ constants, never DB rows.
+- **Shared picker:** the matrix extracts as
+ `components/spree/permission-picker.tsx`, driven by `usePermissionCatalog()`
+ (GET `/permissions`, store-keyed query). The API-keys page's `ScopePicker`
+ becomes a consumer and drops its hardcoded list.
+- **PermissionProvider:** refetch `/me` when the active store changes — rules
+ and keys are store-scoped. Expose `permissionKeys`.
+- **Staff page polish:** role badges get a permission-summary tooltip; the edit
+ sheet links to the roles page ("Manage roles").
+- **i18n:** all new keys in all six locales (en, de, fr, pl, ar, zh-CN) in both
+ `dashboard` and `dashboard-core` as appropriate. Core key labels translate
+ client-side; unknown (extension) keys fall back to the server-provided
+ localized label.
+- **E2E:** `e2e/roles.spec.ts` — create a role with a permission subset, assign
+ it, verify the editor round-trip and the guard (non-admin cannot grant beyond
+ own keys).
+
+### SDK and type generation
+
+`admin-sdk` gains `roles.create/update/delete` and `permissions.list`; the `Role`
+type grows the new attributes. Standard pipeline (typelizer → zod → rswag →
+OpenAPI regen); rswag integration specs follow the settings resources' pattern.
+
+## Migration Path
+
+Phase 1 — backend (core + api):
+
+1. Catalog registry + core resource registrations (including `staff`);
+ `PermissionSets::*` deleted outright; `assign` raises with the upgrade-guide
+ pointer; the install generator's initializer template drops its permission
+ lines **in the same change** (the template references the deleted constants).
+2. Storefront baseline internalized in `Spree::Ability`; role resolution gated
+ to admin-user principals; DB-key activation; Axis A/B extraction
+ (`Order#cancel/destroy` guards, `Spree::Role` protection guards) — guard +
+ spec first, ability rule removal after.
+3. `spree_roles` migration (`description`, `permissions`, `mutable`) + model
+ guards + known-key validation; admin role seeded `mutable: false`.
+4. `Spree::ApiKey::SCOPES` re-pointed at the catalog; `admin_users` /
+ `invitations` / `roles` controllers re-scoped `settings` → `staff`;
+ `ScopedAuthorization` generalized to JWT principals (release-note both
+ Developer Preview breakages).
+5. Roles CRUD + `/permissions` endpoint + `/me.permission_keys`;
+ `RoleGrantGuard` key-set comparison; 403 `required_permission` enrichment.
+6. Typegen + admin-sdk resources + rswag/OpenAPI.
+
+Phase 2 — dashboard:
+
+7. `usePermissionCatalog` + shared `PermissionPicker`; migrate the API-keys
+ scope picker onto it.
+8. Roles list + editor pages (with the template picker), nav entry,
+ `Subject.Role`; PermissionProvider store-change refetch; staff page polish.
+9. Locales ×6; `roles.spec.ts` e2e.
+
+Phase 3 — docs + cleanup:
+
+10. Rewrite `docs/developer/customization/permissions.mdx` around the editor,
+ the Admin API, and seeds (with `register_ability` as the advanced escape
+ hatch); write the 6.0 upgrade-guide entry (below).
+11. 6.1: evaluate removing CanCanCan from the admin path (the storefront keeps
+ it).
+
+No data migration and no bridge. The upgrade-guide entry for hosts coming from
+5.x: delete the permission lines from `config/initializers/spree.rb` (they
+raise/`NameError` at boot otherwise) and recreate any custom roles in
+Settings → Roles — or in seeds — **before deploying**: pre-existing custom role
+rows come up with empty `permissions`, so their staff are locked out (fail
+closed) until the matrix is filled in.
+
+## Constraints on Current Work
+
+- **No new permission sets, anywhere — and no compatibility shims for them.**
+ New capabilities are catalog resource registrations; roles in examples/docs
+ are data (editor, Admin API, or seeds). Reviewers should reject PRs adding
+ `PermissionSets::` classes, `assign`/`grant`-style role config, or a bridge
+ resurrecting any of it — the no-bridge removal is a recorded decision, not an
+ oversight.
+- **Every new admin-visible model must appear in a catalog entry.** Declaring
+ `scoped_resource` (existing rule) is not enough — the models the controller
+ authorizes must be in that resource's subject list, or custom roles cannot
+ reach the endpoint. Reviewers should reject admin PRs that add subjects no
+ entry covers.
+- **Grants stay flat.** Record-level conditions belong on models/workflows
+ (Axis B) or in `register_ability` — never in the catalog.
+- **Don't remove the `cannot …, Spree::Role, name: ['admin']` ability rules**
+ until the model guards land with specs (extraction order: guard first).
+- **New sensitive resources get their own catalog resource** rather than riding
+ `settings` — splitting later is a breaking vocabulary change.
+- **Storefront authorization must not grow role dependence.** Scope-fetching
+ stays the primary enforcement; nothing storefront-side may consult
+ `Spree::Role` or the catalog.
+
+## Open Questions
+
+The design questions raised while drafting (staff scope split, editor container,
+SCOPES derivation, starter roles, replace-vs-wrap, storefront/B2B boundary,
+code-managed roles and the migration bridge — the last two dropped entirely) were
+all resolved 2026-08-07 and live in Key Decisions. Genuinely deferred:
+
+- **Per-action keys** (`approve_orders`-style) stay out, reaffirming the 5.5
+ scopes decision. Unblocked by: a concrete merchant/partner case resource
+ granularity cannot express — revisit both plans together, since the vocabulary
+ is shared.
+- **Store-scoped role *definitions*** (a role visible in only one store) — roles
+ stay global reference data; only assignments are store-scoped. Unblocked by:
+ SaaS multi-tenant demand where tenant A's custom roles must be invisible to
+ tenant B.
+- **Vendor-scoped assignments in the UI** — the model supports it
+ (`RoleUser#resource` is polymorphic); the surface ships with
+ `6.0-multi-vendor-marketplace.md`, not here.
+- **Audit trail for role/permission changes** — rides a future admin audit-log
+ feature; not blocking the editor.
+- **CanCanCan-free admin path** — becomes possible once nothing public speaks
+ it; evaluate in 6.1 with real data on `register_ability` usage.
+
+## References
+
+- spree/spree#14164 — the RFC this plan answers
+- `5.5-admin-api-key-scopes.md` — scope vocabulary, `scoped_resource`, guard
+ precedent (partially superseded: catalog-derived SCOPES, `staff` split,
+ JWT key gate)
+- `6.0-admin-api.md` — `/me` shape, endpoint inventory (roles block)
+- `6.0-admin-spa.md` — PermissionProvider, nav registries, `<Can>`
+- `6.0-platform-auth.md` — Customer/Staff split (role resolution gated to staff)
+- `6.1-channels-catalogs-b2b.md` — catalog visibility as data scoping; Company
+ models (B2B roles are a separate future Enterprise system)
+- `6.0-multi-vendor-marketplace.md` — future vendor-scoped role assignments
+- `docs/plans/decisions.md` 2026-08-05 — model-level immutability guards
+ (NamedType precedent) · 2026-08-07 — this plan's catalog/replacement decision
+- Prior art: Saleor permission groups, Vendure roles, Shopify staff permissions;
+ commercetools Business Unit associate roles / Shopify B2B contact permissions /
+ Medusa B2B module (all keep account roles separate from staff RBAC)
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 0279198957..067b083dc6 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1556,3 +1556,65 @@ classes. Both tables drop in 6.1 alongside `spree_adjustments`.
**Kept:** `Spree::PaymentCaptureEvent` — functional money data, not audit:
`Payment#captured_amount` sums it, partial capture and capture-on-dispatch
depend on it, and the Admin API exposes `captured_amount`.
+
+## 2026-08-07 — Admin RBAC: one grant system, staff-only, catalog = scope vocabulary
+
+**Decision:** (from spree/spree#14164; plan `6.0-admin-rbac.md`) Role
+permissions become database-backed as flat `read_<resource>` /
+`write_<resource>` keys — the same vocabulary secret API keys use. One
+declarative catalog (resource → CanCanCan subjects → UI group) is the single
+source of truth: `Spree::ApiKey::SCOPES` derives from it, and the dashboard
+role editor and API-key scope picker share one `PermissionPicker` fed by
+`GET /admin/permissions`. **Permission sets are deleted at 6.0 with NO
+compatibility bridge** — a deliberate exception to the one-release-bridge
+convention: this is a system removal, not a rename, and a shim would carry the
+runtime-union machinery the removal exists to kill. Old initializers fail
+loudly at boot (`NameError` on the deleted constants; `assign` raises with an
+upgrade-guide pointer). **Roles are pure data:** no `Spree.permissions.grant`,
+no runtime merge, no union — the editor is WYSIWYG; "roles as code" is seeds
+(plain ActiveRecord) or the Admin API; extensions register catalog resources,
+never roles (matching Saleor/Vendure/Shopify — roles are rows everywhere). A
+`mutable` column (NamedType pattern) covers locked roles: admin seeds
+`mutable: false`; hosts can lock compliance roles the same way. Record-level
+custom rules migrate to `register_ability`, the single low-level escape hatch.
+Upgrade is fail-closed: pre-existing custom role rows come up with empty
+permissions until filled in the editor. Enforcement unifies on
+the key gate: `ScopedAuthorization` generalizes so every admin request — JWT
+staff or secret key — checks its principal key set against
+`<read|write>_<scoped_resource>`; CanCanCan is demoted to internal plumbing
+behind it (still compiled from keys; nothing public configures it; dropping it
+from the admin path is a 6.1 option, not a goal). A new `staff` pair splits
+out of `settings`; admin-role protection moves onto the `Spree::Role` model
+(NamedType precedent — sk principals never consult CanCanCan). Resource
+granularity reaffirmed; full-page editor; client-side templates, no seeds.
+
+**The system is staff-only.** The storefront has no roles: `:default` /
+`DefaultCustomer` cease to be public concepts and the customer baseline
+(ownership conditions, guest tokens) becomes internal ability code, with
+scope-fetching the primary enforcement. Role resolution runs only for
+admin-user principals (aligns with the platform-auth Customer/Staff split, and
+drops a per-request `role_users` query for customers). B2B company-account
+roles (buyer/approver, hierarchies, spend limits — Enterprise) are explicitly
+a separate future system: the vocabulary must not be shared (`write_orders`
+means "manage the store's orders" to staff and "place my company's orders" to
+a purchaser), matching commercetools/Shopify B2B/Medusa, which all keep
+account roles apart from staff RBAC. Catalog/product visibility per customer
+group or company is data scoping, never a permission key.
+
+**Why:** the hard parts already shipped — the scope vocabulary and
+per-controller `scoped_resource` declarations (5.5), the `RoleGrantGuard`
+escalation check, store-scoped `RoleUser` assignments resolved per store by
+`Spree::Ability`, and the `/me` rules dump the SPA mirrors. Unifying on them
+turns "build an RBAC system" into "expose the one that exists". Two softer
+designs were drafted and rejected the same day: sets kept as bundles over the
+catalog, then a one-release `assign` bridge with an import task — each
+preserved grant-source duality (union semantics, locked "granted in code"
+rows, mixed escalation math) purely for back-compat comfort, in the release
+whose point is the breaking window, for a migration that is genuinely a
+five-minute UI task.
+
+**Reviewer constraints:** no new `PermissionSets::` classes or `assign` calls
+anywhere; every model a new admin controller authorizes must be covered by a
+catalog entry, or custom roles cannot reach the endpoint; new sensitive
+resources get their own catalog resource instead of riding `settings`;
+storefront code must never consult `Spree::Role` or the catalog.