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
Fix the dashboard shell for roles without settings access
Damian Legawiec0f81b8da59f7
diff --git a/packages/dashboard-core/src/components/settings-sidebar.tsx b/packages/dashboard-core/src/components/settings-sidebar.tsxindex 8a88bb6149..c4e51c6e6c 100644--- a/packages/dashboard-core/src/components/settings-sidebar.tsx+++ b/packages/dashboard-core/src/components/settings-sidebar.tsx@@ -132,7 +132,7 @@ function filterByPermissions(const groups = snapshot.groups.map(({ group, entries }) => ({group,- entries: entries.filter((e) => !e.subject || permissions.can('read', e.subject)),+ entries: entries.filter((e) => !e.subject || permissions.can(e.action ?? 'read', e.subject)),})).filter((g) => g.entries.length > 0)return {diff --git a/packages/dashboard-core/src/lib/settings-nav-registry.ts b/packages/dashboard-core/src/lib/settings-nav-registry.tsindex b9a6c93998..db07d3ba41 100644--- a/packages/dashboard-core/src/lib/settings-nav-registry.ts+++ b/packages/dashboard-core/src/lib/settings-nav-registry.ts@@ -1,6 +1,6 @@import type { LucideIcon } from 'lucide-react'import { useSyncExternalStore } from 'react'-import type { SubjectName } from './permissions'+import type { ActionName, SubjectName } from './permissions'/*** Registry for the settings sub-shell sidebar. Mirrors `nav-registry.ts` but@@ -36,6 +36,13 @@ export interface SettingsNavEntry {position?: number/** CanCanCan subject required to see this item. Omit for always-visible. */subject?: SubjectName+ /**+ * Action checked against `subject`. Defaults to `'read'`. Settings pages+ * that only exist to *change* something (store settings, emails) should+ * declare `'update'` — every staff member can read the store record for+ * shell data, so a read check would show them a page they cannot use.+ */+ action?: ActionName/** When true, the page is disabled in the sidebar with a "Soon" badge. */comingSoon?: boolean}@@ -150,6 +157,21 @@ export function useSettingsNav() {return useSyncExternalStore(subscribe, getSnapshot, getSnapshot)}+/**+ * Whether any settings entry is reachable for these permissions. The Settings+ * launcher in the primary sidebar uses this so a role with no settings+ * authority never opens an empty shell.+ */+export function hasVisibleSettingsEntries(permissions: unknown): boolean {+ const can = (permissions as { can?: (action: string, subject: string) => boolean } | undefined)+ ?.can+ if (typeof can !== 'function') return false++ return getSnapshot().all.some(+ (entry) => !entry.subject || can(entry.action ?? 'read', entry.subject),+ )+}+/** Test-only: clear the registry. */export function __resetSettingsNavRegistry(): void {entries.length = 0diff --git a/packages/dashboard-core/tests/settings-nav-permissions.test.ts b/packages/dashboard-core/tests/settings-nav-permissions.test.tsnew file mode 100644index 0000000000..2fc17326bd--- /dev/null+++ b/packages/dashboard-core/tests/settings-nav-permissions.test.ts@@ -0,0 +1,83 @@+import { afterEach, describe, expect, it } from 'vitest'+import {+ __resetSettingsNavRegistry,+ hasVisibleSettingsEntries,+ settingsNav,+} from '../src/lib/settings-nav-registry'++/** Minimal stand-in for the PermissionProvider's matcher. */+function permissionsFor(granted: Array<[string, string]>) {+ return {+ can: (action: string, subject: string) =>+ granted.some(([a, s]) => a === action && s === subject),+ }+}++function registerSettingsPages() {+ settingsNav.addGroup({ key: 'store', label: 'Store' })+ settingsNav.addGroup({ key: 'team', label: 'Team' })+ // Every staff member can read the store (shell data), so the store settings+ // page declares `update` — a read gate would show it to everyone.+ settingsNav.add({+ key: 'settings.store',+ label: 'Store',+ path: '/store',+ group: 'store',+ subject: 'Spree::Store',+ action: 'update',+ })+ settingsNav.add({+ key: 'settings.roles',+ label: 'Roles',+ path: '/roles',+ group: 'team',+ subject: 'Spree::Role',+ })+}++afterEach(() => __resetSettingsNavRegistry())++describe('settings nav visibility', () => {+ it('hides update-gated pages from a role that can only read the subject', () => {+ registerSettingsPages()++ // An order manager: reads the store for shell data, manages nothing here.+ const orderManager = permissionsFor([+ ['read', 'Spree::Store'],+ ['manage', 'Spree::Order'],+ ])++ expect(hasVisibleSettingsEntries(orderManager)).toBe(false)+ })++ it('shows the page to a role that can update the subject', () => {+ registerSettingsPages()++ const settingsManager = permissionsFor([+ ['read', 'Spree::Store'],+ ['update', 'Spree::Store'],+ ])++ expect(hasVisibleSettingsEntries(settingsManager)).toBe(true)+ })++ it('shows read-gated pages to a role holding that read', () => {+ registerSettingsPages()++ expect(hasVisibleSettingsEntries(permissionsFor([['read', 'Spree::Role']]))).toBe(true)+ })++ it('treats entries without a subject as always visible', () => {+ settingsNav.addGroup({ key: 'audit', label: 'Audit' })+ settingsNav.add({ key: 'settings.open', label: 'Open', path: '/open', group: 'audit' })++ expect(hasVisibleSettingsEntries(permissionsFor([]))).toBe(true)+ })++ it('is false when nothing is registered or permissions are missing', () => {+ expect(hasVisibleSettingsEntries(permissionsFor([]))).toBe(false)++ registerSettingsPages()+ expect(hasVisibleSettingsEntries(undefined)).toBe(false)+ })+})diff --git a/packages/dashboard/src/nav/default.ts b/packages/dashboard/src/nav/default.tsindex fd3b1c1b89..7539dd4f6a 100644--- a/packages/dashboard/src/nav/default.ts+++ b/packages/dashboard/src/nav/default.ts@@ -1,5 +1,5 @@import type { Store } from '@spree/admin-sdk'-import { i18n, nav, Subject } from '@spree/dashboard-core'+import { hasVisibleSettingsEntries, i18n, nav, Subject } from '@spree/dashboard-core'import {BarChart3Icon,HomeIcon,@@ -177,7 +177,10 @@ nav.add({label: i18n.t('admin.nav.settings'),path: '/settings',icon: SettingsIcon,- subject: Subject.Store,+ // No `subject`: every staff member can read the store record (shell data),+ // so a Store check would show Settings to roles with nothing inside it.+ // Visible only when at least one settings page is reachable.+ if: ({ permissions }) => hasVisibleSettingsEntries(permissions),section: 'bottom',position: 100,})diff --git a/packages/dashboard/src/nav/settings.ts b/packages/dashboard/src/nav/settings.tsindex 99efcc6e1f..9465c04170 100644--- a/packages/dashboard/src/nav/settings.ts+++ b/packages/dashboard/src/nav/settings.ts@@ -46,6 +46,9 @@ settingsNav.add({group: 'store',position: 100,subject: Subject.Store,+ // Every staff member can READ the store (shell data: name, logo, timezone,+ // currencies); only settings managers should see the page that edits it.+ action: 'update',})settingsNav.add({@@ -56,6 +59,7 @@ settingsNav.add({group: 'store',position: 125,subject: Subject.Store,+ action: 'update',})settingsNav.add({@@ -208,8 +212,9 @@ settingsNav.add({subject: Subject.AllowedOrigin,})-// No `subject`: the page spans import types and the API already filters what-// the caller can see.+// The page spans import types and the API filters rows per type, but a+// merchant with no write permission anywhere can't run any import — gate the+// entry on products, the most common import subject.settingsNav.add({key: 'settings.imports',labelKey: 'admin.settings_nav.items.imports',@@ -217,4 +222,6 @@ settingsNav.add({icon: UploadIcon,group: 'audit',position: 100,+ subject: Subject.Product,+ action: 'update',})diff --git a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rbindex 1f8e029987..20dcbe9be1 100644--- a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb@@ -5,6 +5,12 @@ module Spreeclass StoreController < Admin::BaseControllerscoped_resource :settings+ # Reading the current store is shell data — the dashboard needs the+ # name, logo, timezone, currency and locales to render anything at+ # all, so every authenticated staff member can read it regardless of+ # their permissions. Writing still requires `write_settings`.+ skip_scope_check! only: :show+# GET /api/v3/admin/storedef showauthorize! :show, current_storediff --git a/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rbindex c4e11b5826..57140d6164 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb@@ -19,6 +19,52 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller doexpect(response).to have_http_status(:ok)end+ # The dashboard shell (store name, logo, timezone, currencies, locales)+ # can't render without this, so reading the store is not gated on the+ # settings permission — only writing is.+ context 'as a staffer without any settings permission' do+ let(:staffer) do+ create(:admin_user, :without_admin_role).tap do |user|+ user.role_users.create!(+ role: create(:role, name: 'orders_only', permissions: %w[write_orders]),+ resource: store+ )+ end+ end+ let(:headers) do+ { 'Authorization' => "Bearer #{Spree::Api::V3::TestingSupport.generate_jwt(staffer, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN)}" }+ end++ it 'still reads the store' do+ subject+ expect(response).to have_http_status(:ok)+ expect(json_response['name']).to eq(store.name)+ end++ it 'cannot update it' do+ patch :update, params: { name: 'Renamed' }, as: :json++ expect(response).to have_http_status(:forbidden)+ expect(store.reload.name).not_to eq('Renamed')+ end+ end++ context 'via a secret API key without a settings scope' do+ let(:secret_api_key) { create(:api_key, :secret, store: store, scopes: %w[read_orders]) }+ let(:headers) { { 'x-spree-api-key' => secret_api_key.plaintext_token } }++ it 'still reads the store' do+ subject+ expect(response).to have_http_status(:ok)+ end++ it 'cannot update it' do+ patch :update, params: { name: 'Renamed' }, as: :json++ expect(response).to have_http_status(:forbidden)+ end+ end+it 'serializes the prefixed id, not the raw integer DB id' do# Regression: a previous version of the serializer listed `:id` in# `attributes`, which overrode `BaseSerializer#id` and exposed the