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.

Apply RBAC review feedback: upgrade tripwires, human labels, docs split

Damian Legawieceb46e5741e88
diff --git a/docs/developer/customization/permissions.mdx b/docs/developer/customization/permissions.mdx
index 043854bf23..0b85f53590 100644
--- a/docs/developer/customization/permissions.mdx
+++ b/docs/developer/customization/permissions.mdx
@@ -2,122 +2,266 @@
title: Permissions
---
-Spree authorizes staff through **roles** that hold flat **permission keys** from a single catalog. Merchants manage everything in the dashboard — no Ruby required — and the same vocabulary powers secret API key scopes, so a role grant and a key scope always mean the same thing.
+Spree uses [CanCanCan](https://github.com/CanCanCommunity/cancancan) for authorization. The permission system allows you to define granular access control for different user roles.
-## The permission catalog
+## Permission Sets (Recommended)
-Every grantable capability is a key of the form `read_<resource>` or `write_<resource>` — `read_orders`, `write_products`, `write_staff`, and so on. Each resource covers a slice of the Admin API and the models behind it; `write_*` implies the matching `read_*`.
+Permission Sets provide a clean, modular way to manage permissions. Each permission set is a reusable group of permissions that can be assigned to roles.
-Discover the catalog at runtime:
+### How It Works
-```bash
-GET /api/v3/admin/permissions
-```
-
-Each entry describes the key, its resource, its `read`/`write` kind, a UI group, and localized labels — the role editor and the API-key scope picker are both rendered from this endpoint.
+1. **Roles** - Determine which permission sets govern a user's access (e.g., `admin`, `customer_service`)
+2. **Permission Sets** - Contain the logic defining what actions users can perform on resources
+3. **Role Configuration** - Associates roles with their corresponding permission sets
-The important granularity choice: keys are **per resource, not per action**. There is no `cancel_orders` — `write_orders` covers all order writes. The money-adjacent areas are separate resources (`payments`, `refunds`, `gift_cards`, `store_credits`), so "customer service can view orders but cannot refund" is simply `read_orders` without `write_refunds`.
+### Configuring Roles
-## Managing roles
+In your `config/initializers/spree.rb`, configure which permission sets are assigned to each role:
-Roles are data. Create and edit them in the dashboard under **Settings → Roles**: each role has a name, a description, and a permission grid; staff are assigned roles per store from **Settings → Staff**.
+```ruby
+Rails.application.config.after_initialize do
+ # Default permissions for all users (guests and logged-in customers)
+ Spree.permissions.assign(:default, [Spree::PermissionSets::DefaultCustomer])
+
+ # Full admin access
+ Spree.permissions.assign(:admin, [Spree::PermissionSets::SuperUser])
+
+ # Custom role with specific permissions
+ Spree.permissions.assign(:customer_service, [
+ Spree::PermissionSets::DashboardDisplay,
+ Spree::PermissionSets::OrderManagement,
+ Spree::PermissionSets::UserDisplay
+ ])
+
+ # Merchandiser role for product management
+ Spree.permissions.assign(:merchandiser, [
+ Spree::PermissionSets::DashboardDisplay,
+ Spree::PermissionSets::ProductManagement,
+ Spree::PermissionSets::StockManagement
+ ])
+end
+```
-The same surface exists on the Admin API:
+### Built-in Permission Sets
+
+| Permission Set | Description |
+|---------------|-------------|
+| `SuperUser` | Full admin access with safety restrictions |
+| `DefaultCustomer` | Basic storefront permissions (browse, checkout, manage own account) |
+| `DashboardDisplay` | View admin dashboard |
+| `OrderDisplay` | Read-only access to orders |
+| `OrderManagement` | Full order management (view, edit, refund, etc.) |
+| `ProductDisplay` | Read-only access to products and catalog |
+| `ProductManagement` | Full catalog management (products, variants, taxonomies) |
+| `UserDisplay` | Read-only access to users |
+| `UserManagement` | Full user management |
+| `StockDisplay` | Read-only access to inventory |
+| `StockManagement` | Full inventory management |
+| `PromotionManagement` | Manage promotions and coupon codes |
+| `ConfigurationManagement` | Manage store settings, shipping, taxes, etc. |
+| `RoleManagement` | Manage roles (except the protected admin role) |
+
+### Creating Custom Permission Sets
+
+Create a new permission set in `app/models/spree/permission_sets/`:
-```bash
-GET /api/v3/admin/roles
-POST /api/v3/admin/roles # { name, description, permissions: ["read_orders", ...] }
-PATCH /api/v3/admin/roles/:id
-DELETE /api/v3/admin/roles/:id
+```ruby
+# app/models/spree/permission_sets/warehouse_management.rb
+module Spree
+ module PermissionSets
+ class WarehouseManagement < Base
+ def activate!
+ can :manage, Spree::StockItem
+ can :manage, Spree::StockLocation
+ can :manage, Spree::StockMovement
+ can :manage, Spree::Shipment
+ can [:read, :admin], Spree::Order
+ end
+ end
+ end
+end
```
-For reproducible environments, seed roles with plain ActiveRecord:
+Then assign it to a role:
```ruby
-# db/seeds.rb
-Spree::Role.find_or_create_by!(name: 'support')
- .update!(permissions: %w[read_orders read_customers], description: 'Read-only support')
+Spree.permissions.assign(:warehouse_staff, [
+ Spree::PermissionSets::DashboardDisplay,
+ Spree::PermissionSets::WarehouseManagement
+])
```
-A few rules the server enforces everywhere:
+### Permission Set API
-- **The `admin` role is protected.** It always grants everything and cannot be renamed, re-permissioned, or deleted.
-- **Locked roles.** A role with `mutable: false` (set from seeds or the console) renders read-only in the dashboard — for roles a host application does not want store staff to edit.
-- **A role in use cannot be deleted.** Reassign staff and revoke pending invitations first.
-- **No privilege escalation.** A caller can only grant permissions they effectively hold — when creating or editing roles, assigning roles to staff, inviting staff, or minting API keys. Only admins can grant the `admin` role.
+Within a permission set, you have access to:
-## How enforcement works
+- `can(action, subject, conditions = {})` - Grant permission
+- `cannot(action, subject, conditions = {})` - Deny permission
+- `can?(action, subject)` - Check if permission exists
+- `user` - The current user
+- `store` - The current store (for multi-store setups)
-Every Admin API controller declares the resource it belongs to. On each request the principal's keys — a staff member's role permissions, or a secret key's scopes — are checked against `read_<resource>` or `write_<resource>` depending on the action. A missing key produces a 403 that names it:
+```ruby
+module Spree
+ module PermissionSets
+ class OrderManagementForOwnOrders < Base
+ def activate!
+ # Users can only manage orders they created
+ can :manage, Spree::Order, created_by_id: user.id
+
+ # But cannot cancel any order
+ cannot :cancel, Spree::Order
+
+ # Unless it's cancellable
+ can :cancel, Spree::Order, &:allow_cancel?
+ end
+ end
+ end
+end
+```
+
+### Managing Permission Configuration
-```json
-{
- "error": {
- "code": "access_denied",
- "message": "Missing permission: write_orders",
- "details": { "required_permission": "write_orders" }
- }
-}
+```ruby
+# Assign permission sets to a role
+Spree.permissions.assign(:customer_service, [
+ Spree::PermissionSets::OrderDisplay,
+ Spree::PermissionSets::UserManagement
+])
+
+# Add more permission sets to an existing role
+Spree.permissions.assign(:customer_service, [
+ Spree::PermissionSets::StockDisplay
+])
+
+# Clear all permission sets from a role
+Spree.permissions.clear(:customer_service)
+
+# Check what permission sets a role has
+Spree.permissions.permission_sets_for(:customer_service)
+# => [Spree::PermissionSets::OrderDisplay, ...]
+
+# Check if a role is configured
+Spree.permissions.role_configured?(:customer_service)
+# => true
```
-Behind that gate, keys compile to [CanCanCan](https://github.com/CanCanCommunity/cancancan) rules (a read key grants `can [:read, :admin]` on the resource's models; a write key grants `can :manage`), which handle record-level concerns. `GET /api/v3/admin/me` returns both views — the rule dump the dashboard mirrors for UI gating, and `permission_keys`, the flat list of keys the user holds on the current store.
+## Users and Roles
-Storefront customers are **not** part of this system. Customer authorization is ownership — carts and orders by token or account, addresses by `user_id` — enforced by a fixed internal baseline and the Store API's scoped lookups. There is nothing to configure.
+Spree comes with an `admin` role by default. You can create more roles in the Admin Panel or via Rails console:
-## Extensions: registering permissions
+```ruby
+Spree::Role.find_or_create_by(name: 'customer_service')
+Spree::Role.find_or_create_by(name: 'merchandiser')
+Spree::Role.find_or_create_by(name: 'warehouse_staff')
+```
-An extension registers its resources into the catalog once. The keys appear in the role editor, become mintable API-key scopes, and gate the extension's admin endpoints — no further wiring:
+Assign a role to a user:
```ruby
-# in your engine's initializer
-Spree.permissions.register_resource(:reviews, group: :catalog, subjects: -> {
- [SpreeReviews::Review]
-})
+user = Spree.user_class.find_by(email: '[email protected]')
+role = Spree::Role.find_by(name: 'customer_service')
+user.spree_roles << role
```
-- `group` places the row in the permission pickers (`:orders`, `:catalog`, `:marketing`, `:customers`, `:settings`, `:access`, `:analytics` — or your own).
-- `subjects` is a lambda returning the CanCanCan subjects the keys grant; it resolves lazily, so load order does not matter.
-- Pass `write: false` for read-only resources (like the analytics dashboard).
+### Default Role Behavior
+
+- Users with **no roles assigned** automatically get the `:default` role permissions
+- No `RoleUser` records are created for regular customers
+- Only users with special permissions need explicit role assignments
+
+## Legacy Approach: Custom Ability Classes
+
+<Note>
+The permission sets approach above is recommended for new projects. The legacy approach below is supported for backward compatibility.
+</Note>
+
+### Adding Custom Permissions via Decorator
+
+Create a new ability class in `app/models/customer_service_ability.rb`:
-Localize the labels in your engine's locale file:
+```ruby
+class CustomerServiceAbility
+ include CanCan::Ability
-```yaml
-en:
- spree:
- permissions_catalog:
- resources:
- reviews:
- label: Reviews
- description: Moderate and reply to product reviews
+ def initialize(user)
+ if user.respond_to?(:has_spree_role?) && user.has_spree_role?('customer_service')
+ can :manage, Spree::Order
+ end
+ end
+end
```
-Your admin controllers then declare the same resource:
+Register it via a decorator in `app/models/spree/ability_decorator.rb`:
```ruby
-class SpreeReviews::Admin::ReviewsController < Spree::Api::V3::Admin::ResourceController
- scoped_resource :reviews
+module Spree
+ module AbilityDecorator
+ def abilities_to_register
+ [CustomerServiceAbility]
+ end
+ end
+
+ Ability.prepend(AbilityDecorator)
end
```
-## Advanced: record-level custom rules
+### Replacing the Ability Class
-The catalog is deliberately flat. When a host application needs rules the catalog cannot express — regional restrictions, ownership conditions — register a plain `CanCan::Ability` class; its rules merge into every ability:
+You can replace the entire ability class via [Dependencies](/developer/customization/dependencies):
```ruby
-# app/models/regional_support_ability.rb
-class RegionalSupportAbility
- include CanCan::Ability
+# config/initializers/spree.rb
+Spree::Dependencies.ability_class = 'CustomAbility'
+```
- def initialize(user)
- return unless user.respond_to?(:market_id) && user.market_id
+```ruby
+# app/models/custom_ability.rb
+class CustomAbility < Spree::Ability
+ def initialize(user, options = {})
+ alias_cancan_delete_action
+
+ @user = user || Spree.user_class.new
+ @store = options[:store] || Spree::Current.store
+
+ if @user.respond_to?(:has_spree_role?) && @user.has_spree_role?('admin')
+ apply_admin_permissions(@user, options)
+ elsif @user.respond_to?(:has_spree_role?) && @user.has_spree_role?(:customer_service)
+ apply_customer_service_permissions(@user)
+ else
+ apply_user_permissions(@user, options)
+ end
+
+ protect_admin_role
+ end
+
+ protected
- cannot :manage, Spree::Order
- can [:read, :admin], Spree::Order, market_id: user.market_id
+ def apply_customer_service_permissions(user)
+ can :manage, Spree::Order
+ can [:read, :admin], Spree.user_class
end
end
+```
-# config/initializers/spree.rb
-Spree::Ability.register_ability(RegionalSupportAbility)
+## CanCanCan Reference
+
+Spree's permission system is built on CanCanCan. Key concepts:
+
+- `can :action, Subject` - Grant permission
+- `can :manage, Subject` - Grant all actions (create, read, update, destroy)
+- `cannot :action, Subject` - Explicitly deny permission
+- `can :action, Subject, conditions` - Conditional permission
+
+```ruby
+# Examples
+can :read, Spree::Product # Can read any product
+can :manage, Spree::Order, user_id: user.id # Can manage own orders
+can :update, Spree::Order do |order| # Block conditions
+ order.user == user && !order.completed?
+end
+cannot :destroy, Spree::Order # Cannot destroy any order
+can :destroy, Spree::Order, &:can_be_deleted? # Unless it's deletable
```
-Keep record-state rules ("a completed order cannot be deleted") out of abilities entirely — they belong on models and workflows, where every caller hits them, including secret API keys that never consult CanCanCan.
+See the [CanCanCan documentation](https://github.com/CanCanCommunity/cancancan) for more details.
diff --git a/docs/developer/dashboard/customization/permissions.mdx b/docs/developer/dashboard/customization/permissions.mdx
index 410d802ac6..18585043d8 100644
--- a/docs/developer/dashboard/customization/permissions.mdx
+++ b/docs/developer/dashboard/customization/permissions.mdx
@@ -103,16 +103,7 @@ The same `permissions` object backs the nav registry's `if` predicate, so you ca
## Custom permissions
-If your customization introduces a new model on the backend, register it as a permission catalog resource so its keys become grantable to roles (and mintable as API-key scopes):
-
-```ruby
-# in your engine's initializer (host app or extension)
-Spree.permissions.register_resource(:reports, group: :analytics, subjects: -> {
- [MyApp::Report]
-})
-```
-
-After that, any role granted `read_reports` makes `permissions.can('read', 'MyApp::Report')` resolve in the dashboard exactly like a first-party check — the abilities ship to the dashboard with the current-user response (`GET /api/v3/admin/me`) at sign-in, alongside `permission_keys`, the flat key list. For record-level rules the catalog can't express, register a plain `CanCan::Ability` class via `Spree::Ability.register_ability` — see [Permissions](/developer/customization/permissions).
+If your customization introduces a new model on the backend, register it as a permission catalog resource there (`Spree.permissions.register_resource` in your engine's initializer). Its keys then appear in the role editor and the API-key scope picker, and any role granted them makes `permissions.can('read', 'MyApp::Report')` resolve in the dashboard exactly like a first-party check — the abilities ship with the current-user response (`GET /api/v3/admin/me`) at sign-in, alongside `permission_keys`, the flat key list the role editor grants from.
## Reference
diff --git a/docs/docs.json b/docs/docs.json
index 77d29e4d2b..4af72430f0 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -1092,6 +1092,7 @@
"pages": [
"v6/developer/customization/quickstart",
"v6/developer/customization/configuration",
+ "v6/developer/customization/permissions",
"developer/customization/workflows",
"developer/customization/api",
"developer/customization/model-preferences",
diff --git a/docs/plans/6.0-admin-rbac.md b/docs/plans/6.0-admin-rbac.md
index c91e959c8d..2ce55b9d88 100644
--- a/docs/plans/6.0-admin-rbac.md
+++ b/docs/plans/6.0-admin-rbac.md
@@ -461,9 +461,19 @@ all resolved 2026-08-07 and live in Key Decisions. Genuinely deferred:
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.
+- **Vendor-scoped assignments** — the schema already carries them: a vendor
+ staffer is a `RoleUser` with `resource: vendor` (whose `store_id` binds it to
+ the vendor's store), invitations accept the same polymorphic resource, and
+ the roles + catalog keys are the same rows and vocabulary (a vendor "Catalog
+ manager" holds `write_products`). What the marketplace plan must add when
+ vendors ship, per the Axis A/B split: the vendor *boundary* is tenancy, not
+ new keys — vendor-panel endpoints scope-fetch through `current_vendor`
+ exactly as admin endpoints scope through `current_store`, and the store-admin
+ ability must activate keys only from store-resourced assignments (today
+ `staff_roles` matches on `store_id`, which would also pick up
+ vendor-resourced rows and grant a vendor staffer store-wide capability).
+ Surface and enforcement ship 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
diff --git a/docs/v6/developer/customization/permissions.mdx b/docs/v6/developer/customization/permissions.mdx
new file mode 100644
index 0000000000..49a7446fbc
--- /dev/null
+++ b/docs/v6/developer/customization/permissions.mdx
@@ -0,0 +1,66 @@
+---
+title: Permissions
+description: The permission catalog, staff roles, and how extensions register their own permissions.
+---
+
+Staff roles and their permissions are managed as data — in the dashboard under **Settings → Roles**, through the Admin API (`/api/v3/admin/roles`), or in seeds. There is nothing to configure in Ruby for day-to-day permission management. This page covers what extension and host-application developers can plug into.
+
+## The permission catalog
+
+Every grantable capability is a flat key of the form `read_<resource>` or `write_<resource>` — the same vocabulary secret API keys use as scopes. `write_*` implies the matching `read_*`. Discover the catalog at runtime with `GET /api/v3/admin/permissions`; the role editor and the API-key scope picker are both rendered from it.
+
+Keys are per resource, not per action. The money-adjacent areas (`payments`, `refunds`, `gift_cards`, `store_credits`) are separate resources from `orders`, so "view orders but don't refund" needs no special casing.
+
+Roles as code is plain ActiveRecord:
+
+```ruby
+# db/seeds.rb
+Spree::Role.find_or_create_by!(name: 'support')
+ .update!(permissions: %w[read_orders read_customers], description: 'Read-only support')
+```
+
+A role with `mutable: false` (set from seeds or the console) renders read-only in the dashboard — for roles the application does not want store staff to edit. The `admin` role is always protected.
+
+## Registering extension permissions
+
+Register your models as a catalog resource once; the keys appear in the role editor and become mintable API-key scopes with no further wiring:
+
+```ruby
+# in your engine's initializer
+Spree.permissions.register_resource(:reviews, group: :catalog, subjects: -> {
+ [SpreeReviews::Review]
+})
+```
+
+- `group` places the row in the permission pickers (`:orders`, `:catalog`, `:marketing`, `:customers`, `:settings`, `:access`, `:analytics` — or your own).
+- `subjects` is a lambda returning the CanCanCan subjects the keys grant; it resolves lazily, so load order does not matter.
+- Pass `write: false` for read-only resources.
+
+Localize the labels in your engine's locale file under `spree.permissions_catalog.resources.<name>` (`label` and `description`), and declare the same resource on your admin controllers with `scoped_resource :reviews`.
+
+## Record-level custom rules
+
+The catalog is deliberately flat. For rules it cannot express — regional restrictions, ownership conditions — register a plain `CanCan::Ability` class; its rules merge into every ability:
+
+```ruby
+class RegionalSupportAbility
+ include CanCan::Ability
+
+ def initialize(user)
+ return unless user.respond_to?(:market_id) && user.market_id
+
+ cannot :manage, Spree::Order
+ can [:read, :admin], Spree::Order, market_id: user.market_id
+ end
+end
+
+Spree::Ability.register_ability(RegionalSupportAbility)
+```
+
+Keep record-state rules ("a completed order cannot be deleted") on models and workflows instead — they must bind every caller, including secret API keys that never consult CanCanCan.
+
+## How enforcement works
+
+Every Admin API controller declares its resource (`scoped_resource :orders`). Each request checks the principal's keys — a staff member's role permissions on the current store, or a secret key's scopes — against `read_<resource>` or `write_<resource>` for the action. A missing key produces a 403 naming it in `details.required_permission`. Behind that gate, keys compile to CanCanCan rules for record-level concerns, and `GET /api/v3/admin/me` returns both the rule dump the dashboard mirrors and `permission_keys`, the flat key list.
+
+Storefront customers are not part of this system — customer authorization is ownership, enforced by the Store API's scoped lookups, with nothing to configure.
diff --git a/packages/dashboard/e2e/roles.spec.ts b/packages/dashboard/e2e/roles.spec.ts
index ec83fbf9c1..f579343ab6 100644
--- a/packages/dashboard/e2e/roles.spec.ts
+++ b/packages/dashboard/e2e/roles.spec.ts
@@ -32,11 +32,11 @@ test.describe('roles', () => {
await page.getByRole('checkbox', { name: /view customers/i }).check()
await page.getByRole('button', { name: /^save$/i }).click()
- // Back on the list with the new role and its permission badges.
+ // Back on the list with the new role and its human-readable permission badges.
await expect(page.getByRole('cell', { name: new RegExp(name, 'i') })).toBeVisible({
timeout: 15_000,
})
- await expect(page.getByText('read_orders')).toBeVisible()
+ await expect(page.getByText('View Orders').first()).toBeVisible()
// Round-trip: open the editor, grant manage on orders, save.
await page.getByRole('cell', { name: new RegExp(name, 'i') }).click()
diff --git a/packages/dashboard/src/components/spree/permission-picker.tsx b/packages/dashboard/src/components/spree/permission-picker.tsx
index fdb5b8044f..3592423fa7 100644
--- a/packages/dashboard/src/components/spree/permission-picker.tsx
+++ b/packages/dashboard/src/components/spree/permission-picker.tsx
@@ -1,5 +1,6 @@
import type { Permission } from '@spree/admin-sdk'
import { Checkbox, cn } from '@spree/dashboard-ui'
+import type { TFunction } from 'i18next'
import { Fragment } from 'react'
import { useTranslation } from 'react-i18next'
@@ -49,6 +50,25 @@ export function allWriteKeys(entries: Permission[]): string[] {
return buildPermissionRows(entries).map((row) => row.writeKey ?? row.readKey)
}
+/**
+ * Human label for a catalog key — "View Orders", "Manage Products" — in the
+ * admin's UI language, falling back to the raw key while the catalog loads or
+ * for keys it no longer knows.
+ */
+export function permissionKeyLabel(
+ t: TFunction,
+ entries: Permission[] | undefined,
+ key: string,
+): string {
+ const entry = entries?.find((candidate) => candidate.key === key)
+ if (!entry) return key
+
+ const resource = t(`admin.permissions.resources.${entry.resource}`, {
+ defaultValue: entry.label,
+ })
+ return t(`admin.permissions.labels.${entry.kind}`, { resource, defaultValue: key })
+}
+
/**
* Shared read/write permission grid over the catalog — used by the role
* editor and the API-key scope picker (which layers its `read_all`/`write_all`
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index bd81966fa4..61a6fc019f 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -2559,6 +2559,10 @@
"orders": "الطلبات",
"settings": "الإعدادات"
},
+ "labels": {
+ "read": "عرض {{resource}}",
+ "write": "إدارة {{resource}}"
+ },
"resources": {
"api_keys": "API مفاتيح",
"categories": "فئات",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 56126d0184..2399b3859d 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -2559,6 +2559,10 @@
"orders": "Bestellungen",
"settings": "Einstellungen"
},
+ "labels": {
+ "read": "{{resource}} ansehen",
+ "write": "{{resource}} verwalten"
+ },
"resources": {
"api_keys": "API-Schlüssel",
"categories": "Kategorien",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 9b546ef9fe..757385fd29 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -2559,6 +2559,10 @@
"orders": "Orders",
"settings": "Settings"
},
+ "labels": {
+ "read": "View {{resource}}",
+ "write": "Manage {{resource}}"
+ },
"resources": {
"api_keys": "API keys",
"categories": "Categories",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index a5b8a56b03..ed0d0b0807 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -2559,6 +2559,10 @@
"orders": "Commandes",
"settings": "Paramètres"
},
+ "labels": {
+ "read": "Voir {{resource}}",
+ "write": "Gérer {{resource}}"
+ },
"resources": {
"api_keys": "Clés API",
"categories": "Catégories",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 7921ed4fe7..7f0c96ef6b 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -2591,6 +2591,10 @@
"orders": "Zamówienia",
"settings": "Ustawienia"
},
+ "labels": {
+ "read": "Podgląd: {{resource}}",
+ "write": "Zarządzanie: {{resource}}"
+ },
"resources": {
"api_keys": "Klucze API",
"categories": "Kategorie",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 03472f1743..e779b0f6ae 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -2559,6 +2559,10 @@
"orders": "订单",
"settings": "设置"
},
+ "labels": {
+ "read": "查看{{resource}}",
+ "write": "管理{{resource}}"
+ },
"resources": {
"api_keys": "API keys",
"categories": "分类",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/roles/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/roles/index.tsx
index fa96faacb6..21f7b56db8 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/roles/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/roles/index.tsx
@@ -24,7 +24,8 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { CopyIcon, LockIcon, PlusIcon, ShieldIcon } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
-import { useDeleteRole, useRoles } from '../../../../../hooks/use-roles'
+import { permissionKeyLabel } from '../../../../../components/spree/permission-picker'
+import { useDeleteRole, usePermissionCatalog, useRoles } from '../../../../../hooks/use-roles'
export const Route = createFileRoute('/_authenticated/$storeId/settings/roles/')({
component: RolesSettingsPage,
@@ -186,6 +187,7 @@ const PERMISSION_PREVIEW_COUNT = 3
function PermissionSummary({ role }: { role: Role }) {
const { t } = useTranslation()
+ const { data: catalog } = usePermissionCatalog()
if (role.name === 'admin') {
return <Badge>{t('admin.roles.badges.full_access')}</Badge>
@@ -199,8 +201,8 @@ function PermissionSummary({ role }: { role: Role }) {
return (
<div className="flex flex-wrap items-center gap-1">
{preview.map((key) => (
- <Badge key={key} className="font-mono text-[10px]">
- {key}
+ <Badge key={key} variant="secondary">
+ {permissionKeyLabel(t, catalog?.data, key)}
</Badge>
))}
{overflow > 0 && (
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb
index 1d51df5975..d23dd28706 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb
@@ -87,6 +87,31 @@ RSpec.describe Spree::Api::V3::Admin::MeController, type: :controller do
end
end
+ context 'as a staffer with different roles on different stores' do
+ let(:store_b) { create(:store) }
+ let(:staffer) do
+ create(:admin_user, :without_admin_role).tap do |user|
+ user.role_users.create!(role: create(:role, name: 'a_orders', permissions: %w[write_orders]), resource: store)
+ user.role_users.create!(role: create(:role, name: 'b_products', permissions: %w[read_products]), resource: store_b)
+ end
+ end
+ let(:headers) do
+ { 'Authorization' => "Bearer #{Spree::Api::V3::TestingSupport.generate_jwt(staffer, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN)}" }
+ end
+
+ it 'returns only the current store keys' do
+ subject
+ expect(json_response['permission_keys']).to eq(%w[read_orders write_orders])
+ end
+
+ it 'returns the other store keys under that store context' do
+ allow_any_instance_of(Spree::Api::V3::BaseController).to receive(:current_store).and_return(store_b)
+
+ subject
+ expect(json_response['permission_keys']).to eq(%w[read_products])
+ end
+ end
+
it 'exposes the user avatar_url (null when no photo is attached)' do
subject
expect(json_response['user']).to have_key('avatar_url')
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/roles_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/roles_controller_spec.rb
index 54e2314a69..05a43f810f 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/roles_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/roles_controller_spec.rb
@@ -76,6 +76,20 @@ RSpec.describe Spree::Api::V3::Admin::RolesController, type: :controller do
expect(json_response.dig('error', 'details', 'excess_permissions')).to include('write_products')
expect(Spree::Role.find_by(name: 'sneaky')).to be_nil
end
+
+ # Privileges held on OTHER stores don't count: the caller's grant is
+ # their roles on the store the request runs against.
+ it 'ignores keys the caller holds only on a different store' do
+ store_b = create(:store)
+ staffer.role_users.create!(
+ role: create(:role, name: 'b_products', permissions: %w[write_products]),
+ resource: store_b
+ )
+
+ post :create, params: { name: 'sneaky', permissions: %w[write_products] }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ end
end
context 'via a secret API key with limited scopes' do
diff --git a/spree/core/app/models/spree/permission_sets.rb b/spree/core/app/models/spree/permission_sets.rb
new file mode 100644
index 0000000000..f602748d04
--- /dev/null
+++ b/spree/core/app/models/spree/permission_sets.rb
@@ -0,0 +1,17 @@
+module Spree
+ # Removed in Spree 6.0 — roles are data now (docs/plans/6.0-admin-rbac.md).
+ # The module survives only so 5.x initializers referencing the old set
+ # classes fail at boot with directions instead of a bare NameError.
+ module PermissionSets
+ UPGRADE_GUIDE_URL = 'https://spreecommerce.org/docs/developer/upgrades/5.6-to-6.0'
+
+ def self.const_missing(name)
+ raise Spree::PermissionConfiguration::PermissionSetsRemovedError,
+ "Spree::PermissionSets::#{name} was removed in Spree 6.0. Roles and their " \
+ 'permissions are data now — manage them in the dashboard (Settings → Roles), ' \
+ 'via the Admin API, or in seeds. Remove the permission lines from ' \
+ "config/initializers/spree.rb and recreate custom roles before deploying. " \
+ "Upgrade guide: #{UPGRADE_GUIDE_URL}"
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/role_user.rb b/spree/core/app/models/spree/role_user.rb
index 70b2afbe4f..337a75ccdc 100644
--- a/spree/core/app/models/spree/role_user.rb
+++ b/spree/core/app/models/spree/role_user.rb
@@ -30,10 +30,25 @@ module Spree
private
- # Set the default resource to the default store if the resource is not set
- # this will allow a graceful migration from the old roles system to the new one
+ # Set the default resource to the assignment's store (falling back to the
+ # default store) if the resource is not set — this allows a graceful
+ # migration from the old roles system to the new one.
def set_default_resource
- self.resource ||= Spree::Store.current
+ self.resource ||= store || Spree::Store.current
+ end
+
+ # Overrides the SingleStoreResource fallback: the store binding follows
+ # the resource — a store-resourced assignment applies on that store, a
+ # vendor-resourced one on the vendor's store. Without this, a console or
+ # seed assignment for another store would silently bind to
+ # Spree::Current.store. An explicitly assigned store still wins, and
+ # resources without a store keep the Current.store fallback.
+ def ensure_store
+ self.store ||= resource_bound_store || Spree::Current.store
+ end
+
+ def resource_bound_store
+ resource.is_a?(Spree::Store) ? resource : resource.try(:store)
end
end
end
diff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rb
index a9cfcf964b..8e036e453e 100644
--- a/spree/core/lib/spree/core/permission_configuration.rb
+++ b/spree/core/lib/spree/core/permission_configuration.rb
@@ -217,11 +217,11 @@ module Spree
# Kept only to fail loudly with directions instead of a bare NoMethodError.
def assign(*)
raise PermissionSetsRemovedError,
- 'Permission sets were removed in Spree 6.0. Create roles and edit their ' \
- 'permissions in the dashboard (Settings → Roles), via the Admin API, or in ' \
- 'seeds (`Spree::Role#permissions` holds catalog keys). For record-level ' \
- 'custom rules use Spree::Ability.register_ability. ' \
- 'See https://spreecommerce.org/docs/developer/customization/permissions'
+ 'Permission sets were removed in Spree 6.0. Remove the permission lines from ' \
+ 'config/initializers/spree.rb — roles and their permissions are data now, ' \
+ 'managed in the dashboard (Settings → Roles), via the Admin API, or in seeds. ' \
+ 'For record-level custom rules use Spree::Ability.register_ability. ' \
+ "Upgrade guide: https://spreecommerce.org/docs/developer/upgrades/5.6-to-6.0"
end
private
diff --git a/spree/core/spec/models/spree/ability_spec.rb b/spree/core/spec/models/spree/ability_spec.rb
index 915b97e4cb..6bab0073db 100644
--- a/spree/core/spec/models/spree/ability_spec.rb
+++ b/spree/core/spec/models/spree/ability_spec.rb
@@ -155,6 +155,87 @@ describe Spree::Ability, type: :model do
expect(staff_ability.permission_keys).to eq(Spree.permissions.catalog_keys)
end
end
+
+ context 'with overlapping keys across roles' do
+ before do
+ admin.role_users.create!(role: create(:role, name: 'viewer', permissions: %w[read_orders]), resource: store)
+ admin.role_users.create!(role: create(:role, name: 'manager', permissions: %w[write_orders read_orders]), resource: store)
+ end
+
+ it 'deduplicates into one expanded key set' do
+ expect(staff_ability.permission_keys).to eq(%w[read_orders write_orders])
+ expect(staff_ability).to be_able_to :manage, Spree::Order.new
+ end
+ end
+
+ context 'with roles held on different stores' do
+ let(:store_b) { create(:store) }
+
+ before do
+ admin.role_users.create!(role: create(:role, name: 'a_orders', permissions: %w[write_orders]), resource: store)
+ admin.role_users.create!(role: create(:role, name: 'b_products', permissions: %w[write_products]), resource: store_b)
+ end
+
+ it 'activates only the current store assignments' do
+ expect(staff_ability).to be_able_to :manage, Spree::Order.new
+ expect(staff_ability).not_to be_able_to :read, store.products.new
+ expect(staff_ability.permission_keys).to eq(%w[read_orders write_orders])
+ end
+
+ it 'flips with the store context' do
+ ability_b = Spree::Ability.new(admin, store: store_b)
+
+ expect(ability_b).to be_able_to :manage, store.products.new
+ expect(ability_b).not_to be_able_to :read, Spree::Order.new
+ expect(ability_b.permission_keys).to eq(%w[read_products write_products])
+ end
+ end
+
+ context 'as admin on one store and limited staff on another' do
+ let(:store_b) { create(:store) }
+
+ before do
+ admin.role_users.create!(role: Spree::Role.default_admin_role, resource: store)
+ admin.role_users.create!(role: create(:role, name: 'b_viewer', permissions: %w[read_orders]), resource: store_b)
+ end
+
+ it 'does not leak admin authority into the limited store' do
+ expect(staff_ability).to be_able_to :manage, :all
+
+ ability_b = Spree::Ability.new(admin, store: store_b)
+ expect(ability_b).not_to be_able_to :manage, :all
+ expect(ability_b).not_to be_able_to :update, Spree::Order.new
+ expect(ability_b.permission_keys).to eq(%w[read_orders])
+ end
+ end
+
+ context 'with the same role assigned on two stores' do
+ let(:store_b) { create(:store) }
+ let(:role) { create(:role, name: 'shared', permissions: %w[write_orders]) }
+
+ before do
+ admin.role_users.create!(role: role, resource: store)
+ admin.role_users.create!(role: role, resource: store_b)
+ end
+
+ it 'grants the same keys on each store' do
+ expect(staff_ability.permission_keys).to eq(%w[read_orders write_orders])
+ expect(Spree::Ability.new(admin, store: store_b).permission_keys).to eq(%w[read_orders write_orders])
+ end
+ end
+
+ context 'with stale keys the catalog no longer knows' do
+ before do
+ role = create(:role, name: 'stale', permissions: %w[read_orders])
+ role.update_column(:permissions, %w[read_orders write_bogus])
+ admin.role_users.create!(role: role, resource: store)
+ end
+
+ it 'activates the known keys and drops the rest' do
+ expect(staff_ability).to be_able_to :read, Spree::Order.new
+ expect(staff_ability.permission_keys).to eq(%w[read_orders])
+ end
+ end
end
describe 'shared customer/admin user class' do
diff --git a/spree/core/spec/models/spree/role_user_spec.rb b/spree/core/spec/models/spree/role_user_spec.rb
index c427ec1f28..96e368d97d 100644
--- a/spree/core/spec/models/spree/role_user_spec.rb
+++ b/spree/core/spec/models/spree/role_user_spec.rb
@@ -51,6 +51,22 @@ describe Spree::RoleUser do
expect(role_user.store).to eq(store)
end
+
+ it 'binds the store to a store resource, not the current store' do
+ other_store = create(:store)
+ role_user = described_class.new(role: role, user: spree_user, resource: other_store)
+ expect(role_user.valid?).to be_truthy
+
+ expect(role_user.store).to eq(other_store)
+ end
+
+ it 'defaults the resource to an explicitly assigned store' do
+ store = create(:store)
+ role_user = described_class.new(role: role, user: spree_user, store: store)
+ expect(role_user.valid?).to be_truthy
+
+ expect(role_user.resource).to eq(store)
+ end
end
end