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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Address code review findings on the RBAC surface
Damian Legawiecb23f8a2566a2
diff --git a/docs/plans/5.5-admin-api-key-scopes.md b/docs/plans/5.5-admin-api-key-scopes.mdindex 94d0e78534..c18fe7c6be 100644--- a/docs/plans/5.5-admin-api-key-scopes.md+++ b/docs/plans/5.5-admin-api-key-scopes.md@@ -16,8 +16,8 @@ This plan introduces **scopes** on `Spree::ApiKey` so secret keys can carry thei> **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+> staff roles and API keys alike (permission sets are deleted with no+> compatibility bridge). `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@@ -30,7 +30,7 @@ This plan introduces **scopes** on `Spree::ApiKey` so secret keys can carry thei- **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).+- **Scopes apply to API keys only.** JWT admin users keep CanCanCan-based authorization (they have `Spree::Role`s; that surface is unchanged). *Superseded at 6.0: JWT staff pass the same key gate — see the notice above.*- **No backward compatibility for legacy admin keys** — Admin API hasn't shipped to production yet; all secret keys created from this point require explicit scopes.- **Resource granularity, not action granularity.** No separate `cancel_orders`, `approve_orders`, etc. — `write_orders` covers all writes including state transitions and member actions.- **Action mapping:** `index`/`show` → `read_<resource>`, every other action (including custom member actions like `cancel`/`approve`) → `write_<resource>`.@@ -245,7 +245,7 @@ Work in progress that should account for this plan:- **Any new admin controller** must call `scoped_resource :name` after this plan ships. Reviewers should reject admin PRs that don't.- **Don't add per-action scopes** (`cancel_orders`, etc.) without revisiting this plan. Resource granularity is the agreed default.-- **Don't add scope checks to JWT-authenticated paths.** Scopes are an API-key concept only.+- **Don't add scope checks to JWT-authenticated paths.** Scopes are an API-key concept only. *Superseded at 6.0: the generalized key gate covers JWT staff — see the notice above.*- **OpenAPI specs** added before this ships should expect a future `security` enrichment — don't manually duplicate scope info in descriptions.## Open Questionsdiff --git a/docs/plans/6.0-admin-api.md b/docs/plans/6.0-admin-api.mdindex c835d33486..1f9339f3fb 100644--- a/docs/plans/6.0-admin-api.md+++ b/docs/plans/6.0-admin-api.md@@ -809,15 +809,16 @@ API key scopes: `read_vendors` / `write_vendors`, `read_commissions` / `write_co> **6.0:** `Spree::LegacyAdminUser` → `Spree::AdminUser`. Owns auth stack (no Devise). See `6.0-platform-auth.md`.### Roles-- [x] `GET /api/v3/admin/roles` — read-only (feeds role pickers on invitations + admin users)+- [x] `GET /api/v3/admin/roles` — feeds role pickers + the roles settings page- [x] `GET /api/v3/admin/roles/:id`-- [ ] `POST /api/v3/admin/roles`-- [ ] `PATCH /api/v3/admin/roles/:id`-- [ ] `DELETE /api/v3/admin/roles/:id`--> 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.+- [x] `POST /api/v3/admin/roles`+- [x] `PATCH /api/v3/admin/roles/:id`+- [x] `DELETE /api/v3/admin/roles/:id`+- [x] `GET /api/v3/admin/permissions` — the permission catalog (grant vocabulary discovery)++> Shipped with `6.0-admin-rbac.md`: DB-backed role permissions (catalog keys),+> `/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.mdindex d4ec105c1c..c91e959c8d 100644--- a/docs/plans/6.0-admin-rbac.md+++ b/docs/plans/6.0-admin-rbac.md@@ -302,7 +302,7 @@ conditions into grants.### Admin API-```+```textGET /api/v3/admin/permissions # catalog discoveryGET /api/v3/admin/roles # existingGET /api/v3/admin/roles/:id # existingdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 067b083dc6..51f82281a8 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1565,7 +1565,7 @@ permissions become database-backed as flat `read_<resource>` /declarative catalog (resource → CanCanCan subjects → UI group) is the singlesource of truth: `Spree::ApiKey::SCOPES` derives from it, and the dashboardrole editor and API-key scope picker share one `PermissionPicker` fed by-`GET /admin/permissions`. **Permission sets are deleted at 6.0 with NO+`GET /api/v3/admin/permissions`. **Permission sets are deleted at 6.0 with NOcompatibility bridge** — a deliberate exception to the one-release-bridgeconvention: this is a system removal, not a rename, and a shim would carry theruntime-union machinery the removal exists to kill. Old initializers faildiff --git a/packages/dashboard-core/src/providers/permission-provider.tsx b/packages/dashboard-core/src/providers/permission-provider.tsxindex 82954f79f9..54932b1219 100644--- a/packages/dashboard-core/src/providers/permission-provider.tsx+++ b/packages/dashboard-core/src/providers/permission-provider.tsx@@ -6,6 +6,7 @@ import {useContext,useEffect,useMemo,+ useRef,useState,} from 'react'import { adminClient } from '../client'@@ -93,50 +94,39 @@ export function PermissionProvider({ children }: { children: ReactNode }) {const [rules, setRules] = useState<PermissionRule[]>([])const [permissionKeys, setPermissionKeys] = useState<string[]>([])const [isLoading, setIsLoading] = useState(false)+ // Guards against out-of-order `/me` responses: a rapid store switch (or a+ // logout) bumps the generation, and any response from a superseded request+ // is dropped instead of overwriting the current store's permissions.+ const requestGeneration = useRef(0)const refresh = useCallback(async () => {+ const generation = ++requestGeneration.currentsetIsLoading(true)try {const res = await adminClient.me.get()+ if (generation !== requestGeneration.current) returnsetRules(res.permissions)setPermissionKeys(res.permission_keys ?? [])} catch {+ if (generation !== requestGeneration.current) returnsetRules([])setPermissionKeys([])} finally {- setIsLoading(false)+ if (generation === requestGeneration.current) setIsLoading(false)}}, [])useEffect(() => {if (!isAuthenticated) {+ requestGeneration.current += 1setRules([])setPermissionKeys([])+ setIsLoading(false)return}- let cancelled = false- setIsLoading(true)- adminClient.me- .get()- .then((res) => {- if (cancelled) return- setRules(res.permissions)- setPermissionKeys(res.permission_keys ?? [])- })- .catch(() => {- if (cancelled) return- setRules([])- setPermissionKeys([])- })- .finally(() => {- if (!cancelled) setIsLoading(false)- })-- return () => {- cancelled = true- }- }, [isAuthenticated])+ void refresh()+ }, [isAuthenticated, refresh])const permissions = useMemo(() => (rules.length > 0 ? buildPermissions(rules) : EMPTY_PERMISSIONS),diff --git a/packages/dashboard/src/components/spree/role-form.tsx b/packages/dashboard/src/components/spree/role-form.tsxindex a8b5e9695f..6fa41f39e9 100644--- a/packages/dashboard/src/components/spree/role-form.tsx+++ b/packages/dashboard/src/components/spree/role-form.tsx@@ -87,7 +87,9 @@ export function submitRole(toast.error(err.message)return}- throw err+ // Network and other unexpected failures still deserve feedback —+ // rethrowing from a submit handler would surface nothing.+ toast.error(i18n.t('admin.roles.errors.failed_to_save'))}})}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 23abf35c8a..bd81966fa4 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -3104,7 +3104,8 @@},"duplicate_name": "نسخة {{name}}","errors": {- "failed_to_delete": "فشل حذف الدور"+ "failed_to_delete": "فشل حذف الدور",+ "failed_to_save": "فشل حفظ الدور"},"form": {"details_section": "التفاصيل",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 71f2c91cca..56126d0184 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -3098,7 +3098,8 @@},"duplicate_name": "{{name}} Kopie","errors": {- "failed_to_delete": "Rolle konnte nicht gelöscht werden"+ "failed_to_delete": "Rolle konnte nicht gelöscht werden",+ "failed_to_save": "Rolle konnte nicht gespeichert werden"},"form": {"details_section": "Details",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 86c8a459f0..9b546ef9fe 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -3098,7 +3098,8 @@},"duplicate_name": "{{name}} copy","errors": {- "failed_to_delete": "Failed to delete role"+ "failed_to_delete": "Failed to delete role",+ "failed_to_save": "Failed to save role"},"form": {"details_section": "Details",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 3ce5c1d112..a5b8a56b03 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -3098,7 +3098,8 @@},"duplicate_name": "{{name}} copie","errors": {- "failed_to_delete": "Échec de la suppression du rôle"+ "failed_to_delete": "Échec de la suppression du rôle",+ "failed_to_save": "Échec de l'enregistrement du rôle"},"form": {"details_section": "Détails",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 894300c787..7921ed4fe7 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -3140,7 +3140,8 @@},"duplicate_name": "{{name}} kopia","errors": {- "failed_to_delete": "Nie udało się usunąć roli"+ "failed_to_delete": "Nie udało się usunąć roli",+ "failed_to_save": "Nie udało się zapisać roli"},"form": {"details_section": "Szczegóły",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex a0bb93647e..03472f1743 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -3098,7 +3098,8 @@},"duplicate_name": "{{name}} 副本","errors": {- "failed_to_delete": "删除角色失败"+ "failed_to_delete": "删除角色失败",+ "failed_to_save": "保存角色失败"},"form": {"details_section": "详情",diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/api-keys.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/api-keys.tsxindex 4d584873a0..3af066c4d4 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/api-keys.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/api-keys.tsx@@ -1,6 +1,6 @@import { zodResolver } from '@hookform/resolvers/zod'import { type ApiKey, type ApiKeyCreateParams, SpreeError } from '@spree/admin-sdk'-import { mapSpreeErrorsToForm, PageHeader } from '@spree/dashboard-core'+import { mapSpreeErrorsToForm, PageHeader, usePermissions } from '@spree/dashboard-core'import {Badge,Button,@@ -68,7 +68,7 @@ import {PencilIcon,PlusIcon,} from 'lucide-react'-import { useEffect, useState } from 'react'+import { useEffect, useMemo, useState } from 'react'import { Controller, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'@@ -862,9 +862,25 @@ function ScopePicker({}) {const { t } = useTranslation()const { data: catalog } = usePermissionCatalog()+ const { permissionKeys } = usePermissions()const hasWriteAll = value.includes('write_all')const hasReadAll = value.includes('read_all')+ // A staffer can only mint scopes within their own grant (the server's+ // anti-amplification guard) — don't offer keys it would reject. A caller+ // holding the whole catalog (admin) is unrestricted, including the aliases.+ const blockedKeys = useMemo(() => {+ if (!catalog) return undefined+ const blocked = new Set(+ catalog.data.filter((entry) => !permissionKeys.includes(entry.key)).map((entry) => entry.key),+ )+ return blocked.size > 0 ? blocked : undefined+ }, [catalog, permissionKeys])+ const writeAllBlocked = blockedKeys !== undefined+ const readAllBlocked =+ !!catalog &&+ catalog.data.some((entry) => entry.kind === 'read' && !permissionKeys.includes(entry.key))+function setAllRead(checked: boolean) {let next = value.filter((v) => v !== 'read_all' && !v.startsWith('read_'))if (checked) next = [...next, 'read_all']@@ -892,7 +908,7 @@ function ScopePicker({id="scope-write-all"checked={hasWriteAll}onCheckedChange={setAllWrite}- disabled={disabled}+ disabled={disabled || writeAllBlocked}/><span className="font-medium">{t('admin.api_keys.scope_picker.full_access_label')}</span><span className="text-xs text-muted-foreground">@@ -904,7 +920,7 @@ function ScopePicker({id="scope-read-all"checked={hasReadAll}onCheckedChange={setAllRead}- disabled={disabled || hasWriteAll}+ disabled={disabled || hasWriteAll || readAllBlocked}/><span className="font-medium">{t('admin.api_keys.scope_picker.read_all_label')}</span><span className="text-xs text-muted-foreground">@@ -922,6 +938,7 @@ function ScopePicker({value={value}onChange={(next) => onChange?.(next)}disabled={disabled}+ disabledKeys={blockedKeys}/>) : (<div className="flex flex-col gap-2 p-3">diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/roles/$roleId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/roles/$roleId.tsxindex 5cecc094e0..ca52c90a4d 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/roles/$roleId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/roles/$roleId.tsx@@ -1,4 +1,4 @@-import { PageHeader } from '@spree/dashboard-core'+import { PageHeader, usePermissions } from '@spree/dashboard-core'import { Badge, Button, ErrorState, Skeleton } from '@spree/dashboard-ui'import { createFileRoute, useNavigate } from '@tanstack/react-router'import { useEffect } from 'react'@@ -15,6 +15,7 @@ function EditRolePage() {const { t } = useTranslation()const navigate = useNavigate()const { storeId, roleId } = Route.useParams()+ const { permissions } = usePermissions()const { data: role, isLoading, isError } = useRole(roleId)const updateMutation = useUpdateRole()const deleteMutation = useDeleteRole()@@ -67,7 +68,7 @@ function EditRolePage() {)}- const readOnly = !role.mutable+ const readOnly = !role.mutable || permissions.cannot('update', 'Spree::Role')return (<div className="flex flex-col gap-6">@@ -79,7 +80,11 @@ function EditRolePage() {readOnly ? <Badge variant="secondary">{t('admin.roles.badges.protected')}</Badge> : null}resource={role}- onDelete={role.mutable && role.users_count === 0 ? handleDelete : undefined}+ onDelete={+ role.mutable && role.users_count === 0 && permissions.can('destroy', 'Spree::Role')+ ? handleDelete+ : undefined+ }actions={!readOnly && (<Buttondiff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/roles/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/roles/index.tsxindex 1e5a3ab15e..fa96faacb6 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/roles/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/roles/index.tsx@@ -34,6 +34,7 @@ function RolesSettingsPage() {const { t } = useTranslation()const navigate = useNavigate()const { storeId } = Route.useParams()+ const { permissions } = usePermissions()const { data, isLoading } = useRoles()const roles = data?.data ?? []@@ -43,13 +44,15 @@ function RolesSettingsPage() {title={t('admin.pages.roles.title')}subtitle={t('admin.pages.roles.subtitle')}actions={- <Button- size="sm"- onClick={() => navigate({ to: '/$storeId/settings/roles/new', params: { storeId } })}- >- <PlusIcon className="size-4" />- {t('admin.pages.roles.add_cta')}- </Button>+ permissions.can('create', 'Spree::Role') && (+ <Button+ size="sm"+ onClick={() => navigate({ to: '/$storeId/settings/roles/new', params: { storeId } })}+ >+ <PlusIcon className="size-4" />+ {t('admin.pages.roles.add_cta')}+ </Button>+ )}/>@@ -152,6 +155,7 @@ function RoleRow({ role }: { role: Role }) {key: 'duplicate',label: t('admin.actions.duplicate'),icon: <CopyIcon className="size-4" />,+ visible: permissions.can('create', 'Spree::Role'),onSelect: () =>navigate({to: '/$storeId/settings/roles/new',diff --git a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rbindex efd741c0cf..40dc319458 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb@@ -173,14 +173,24 @@ module Spree# Names the catalog permission the failed request needed, derived from# the controller's `scoped_resource` declaration — the JWT twin of the- # scope check's `required_scope` (docs/plans/6.0-admin-rbac.md).+ # scope check's `required_scope` (docs/plans/6.0-admin-rbac.md). Only+ # reported when the caller genuinely lacks the key: a denial the caller+ # is capability-authorized for is a record- or store-level condition,+ # and naming a permission they already hold would mislead.def access_denied_detailsreturn unless respond_to?(:scoped_resource_name, true)resource = scoped_resource_namereturn unless resource- { required_permission: "#{action_kind}_#{resource}" }+ required = "#{action_kind}_#{resource}"+ return unless Spree.permissions.key?(required)++ ability = current_ability+ return unless ability.respond_to?(:permission_keys)+ return if ability.permission_keys.include?(required)++ { required_permission: required }enddef handle_gateway_error(exception)diff --git a/spree/core/app/models/spree/ability.rb b/spree/core/app/models/spree/ability.rbindex 03c58ba344..92d385202a 100644--- a/spree/core/app/models/spree/ability.rb+++ b/spree/core/app/models/spree/ability.rb@@ -67,11 +67,8 @@ module Spree@store = options[:store] || Spree::Current.store@permission_keys = []- if staff_principal?- apply_staff_permissions- else- apply_storefront_permissions- end+ apply_storefront_permissions if storefront_principal?+ apply_staff_permissions if staff_principal?merge_registered_abilitiesend@@ -103,6 +100,14 @@ module Spree@user.persisted? && @user.is_a?(Spree.admin_user_class)end+ # Customers and guests get the storefront baseline. When the host shares+ # one class between customers and admin users (the install generator does+ # this when only `user_class` is provided), a persisted user is both — the+ # baseline applies alongside staff role resolution.+ def storefront_principal?+ !staff_principal? || Spree.admin_user_class == Spree.customer_class+ end+# --- staff ---def apply_staff_permissionsdiff --git a/spree/core/app/models/spree/role.rb b/spree/core/app/models/spree/role.rbindex 1a23b3fe7e..83ff487aa4 100644--- a/spree/core/app/models/spree/role.rb+++ b/spree/core/app/models/spree/role.rb@@ -12,6 +12,12 @@ module Spree# always grants everything.attribute :permissions, default: []+ # Rows predating the column (or raw inserts) hold NULL — the array+ # contract holds regardless.+ def permissions+ super || []+ end+def permissions=(value)super(Array(value).map(&:to_s).reject(&:blank?).uniq)end@@ -30,6 +36,7 @@ module Spreevalidate :permissions_must_be_known, if: :permissions_changed?validate :name_immutable, on: :update, if: :name_changed?validate :permissions_immutable, on: :update, if: :permissions_changed?+ validate :description_immutable, on: :update, if: :description_changed?## Callbacks@@ -92,6 +99,10 @@ module Spreeerrors.add(:permissions, Spree.t(:role_immutable)) unless mutable_was_and_not_admin?end+ def description_immutable+ errors.add(:description, Spree.t(:role_immutable)) unless mutable_was_and_not_admin?+ end+# Guards compare against the persisted state so flipping `mutable` in the# same save cannot smuggle a change past them.def mutable_was_and_not_admin?diff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rbindex 061e5a7bfc..a9cfcf964b 100644--- a/spree/core/lib/spree/core/permission_configuration.rb+++ b/spree/core/lib/spree/core/permission_configuration.rb@@ -78,6 +78,10 @@ module Spree# @param write [Boolean]# @return [Resource]def register_resource(name, group:, subjects:, write: true)+ # `read_all` / `write_all` are the API-key wildcard aliases — a resource+ # named `all` would silently mint keys that grant the whole catalog.+ raise ArgumentError, "the permission resource name 'all' is reserved" if name.to_s == 'all'+resource = Resource.new(name: name, group: group, subjects: subjects, write: write)@resources[resource.name] = resourceenddiff --git a/spree/core/spec/lib/spree/core/permission_configuration_spec.rb b/spree/core/spec/lib/spree/core/permission_configuration_spec.rbindex b8ea1ae941..49358d8a3c 100644--- a/spree/core/spec/lib/spree/core/permission_configuration_spec.rb+++ b/spree/core/spec/lib/spree/core/permission_configuration_spec.rb@@ -37,6 +37,12 @@ RSpec.describe Spree::PermissionConfiguration doexpect(configuration.resource(:reviews).group).to eq(:marketing)end++ it 'reserves all — its keys would collide with the wildcard aliases' do+ expect {+ configuration.register_resource(:all, group: :catalog, subjects: [Spree::Product])+ }.to raise_error(ArgumentError, /reserved/)+ endenddescribe '#unregister_resource' dodiff --git a/spree/core/spec/models/spree/ability_spec.rb b/spree/core/spec/models/spree/ability_spec.rbindex 887b13ed47..915b97e4cb 100644--- a/spree/core/spec/models/spree/ability_spec.rb+++ b/spree/core/spec/models/spree/ability_spec.rb@@ -157,6 +157,40 @@ describe Spree::Ability, type: :model doendend+ describe 'shared customer/admin user class' do+ # The install generator falls back to `user_class` for the admin user class+ # when a host provides only one — persisted customers are then admin-class+ # principals and must keep the storefront baseline alongside role resolution.+ around do |example|+ original = Spree.admin_user_class(constantize: false)+ Spree.admin_user_class = Spree.customer_class.to_s+ example.run+ ensure+ Spree.admin_user_class = original+ end++ it 'keeps the storefront baseline for persisted customers' do+ customer = create(:user)+ shared_ability = Spree::Ability.new(customer, store: store)++ expect(shared_ability).to be_able_to :read, Spree::Product+ expect(shared_ability).to be_able_to :create, Spree::Order+ expect(shared_ability).not_to be_able_to :manage, Spree::Order.new+ end++ it 'resolves staff roles without losing the storefront baseline' do+ manager = create(:user)+ manager.role_users.create!(+ role: create(:role, name: 'shared_manager', permissions: %w[write_orders]),+ resource: store+ )+ shared_ability = Spree::Ability.new(manager, store: store)++ expect(shared_ability).to be_able_to :manage, Spree::Order.new+ expect(shared_ability).to be_able_to :read, Spree::Product+ end+ end+describe '.register_ability' dolet(:custom_ability_class) doClass.new dodiff --git a/spree/core/spec/models/spree/role_spec.rb b/spree/core/spec/models/spree/role_spec.rbindex 5fa66ec265..bfa1aba44c 100644--- a/spree/core/spec/models/spree/role_spec.rb+++ b/spree/core/spec/models/spree/role_spec.rb@@ -30,6 +30,13 @@ describe Spree::Role doexpect(role.permissions).to eq(%w[read_orders write_products])end+ it 'reads NULL column values as an empty array' do+ role = create(:role)+ role.update_column(:permissions, nil)++ expect(role.reload.permissions).to eq([])+ end+it 'rejects unknown catalog keys' dorole = build(:role, permissions: %w[read_orders write_bogus])@@ -84,6 +91,12 @@ describe Spree::Role doexpect(locked_role).not_to be_validend+ it 'cannot change its description' do+ locked_role.description = 'edited'++ expect(locked_role).not_to be_valid+ end+it 'cannot change permissions' dolocked_role.permissions = %w[write_orders]