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
Follow-ups to the Store and Admin API security fixes (#14952)
Damian Legawieccaaaee2915d5
diff --git a/docs/api-reference/admin-api/endpoints.mdx b/docs/api-reference/admin-api/endpoints.mdxindex 8bf321dce0..7bd73af1bc 100644--- a/docs/api-reference/admin-api/endpoints.mdx+++ b/docs/api-reference/admin-api/endpoints.mdx@@ -23,11 +23,11 @@ Endpoints marked — are exempt from scope checks (authentication and session en| Method | Path | Required scope | Summary ||---|---|---|---|-| `GET` | `/allowed_origins` | `read_staff` | List allowed origins |-| `POST` | `/allowed_origins` | `write_staff` | Create an allowed origin |-| `GET` | `/allowed_origins/{id}` | `read_staff` | Get an allowed origin |-| `PATCH` | `/allowed_origins/{id}` | `write_staff` | Update an allowed origin |-| `DELETE` | `/allowed_origins/{id}` | `write_staff` | Delete an allowed origin |+| `GET` | `/allowed_origins` | `read_api_keys` | List allowed origins |+| `POST` | `/allowed_origins` | `write_api_keys` | Create an allowed origin |+| `GET` | `/allowed_origins/{id}` | `read_api_keys` | Get an allowed origin |+| `PATCH` | `/allowed_origins/{id}` | `write_api_keys` | Update an allowed origin |+| `DELETE` | `/allowed_origins/{id}` | `write_api_keys` | Delete an allowed origin |## Api keysdiff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yamlindex 218329c20f..a2d7b9e0dc 100644--- a/docs/api-reference/admin.yaml+++ b/docs/api-reference/admin.yaml@@ -2019,7 +2019,7 @@ paths:`docs/plans/5.5-admin-auth-cookie-refresh.md`).- **Required scope:** `read_staff` (for API-key authentication).+ **Required scope:** `read_api_keys` (for API-key authentication).x-codeSamples:- lang: javascriptlabel: Spree Admin SDK@@ -2164,7 +2164,7 @@ paths:`https`.- **Required scope:** `write_staff` (for API-key authentication).+ **Required scope:** `write_api_keys` (for API-key authentication).x-codeSamples:- lang: javascriptlabel: Spree Admin SDK@@ -2245,7 +2245,7 @@ paths:description: |-Returns a single allowed origin by prefixed ID.- **Required scope:** `read_staff` (for API-key authentication).+ **Required scope:** `read_api_keys` (for API-key authentication).x-codeSamples:- lang: javascriptlabel: Spree Admin SDK@@ -2311,7 +2311,7 @@ paths:description: |-Updates an existing allowed origin.- **Required scope:** `write_staff` (for API-key authentication).+ **Required scope:** `write_api_keys` (for API-key authentication).x-codeSamples:- lang: javascriptlabel: Spree Admin SDK@@ -2389,7 +2389,7 @@ paths:admin API from a browser.- **Required scope:** `write_staff` (for API-key authentication).+ **Required scope:** `write_api_keys` (for API-key authentication).x-codeSamples:- lang: javascriptlabel: Spree Admin SDK@@ -7224,12 +7224,10 @@ paths:<Accordion title="Filters through associations">- Prefix an associated record's attribute with the association, as in `q[created_by_id_eq]`. The same predicates apply.+ Prefix an associated record's attribute with the association, as in `q[customer_id_eq]`. The same predicates apply.| Prefix | Attributes ||---|---|- | `created_by_` | `created_at`, `email`, `first_name`, `id`, `last_name`, `updated_at` |- | `created_by_spree_roles_` | `created_at`, `id`, `name`, `updated_at` || `customer_` | `accepts_email_marketing`, `created_at`, `email`, `first_name`, `id`, `last_name`, `phone`, `updated_at` || `customer_addresses_` | `address1`, `address2`, `city`, `company`, `country_code`, `created_at`, `first_name`, `id`, `last_name`, `phone`, `postal_code`, `state_code`, `updated_at` || `customer_bill_address_` | `address1`, `address2`, `city`, `company`, `country_code`, `created_at`, `first_name`, `id`, `last_name`, `phone`, `postal_code`, `state_code`, `updated_at` |@@ -7273,6 +7271,7 @@ paths:outstanding: truecustomer_id: cust_UkLWZg9DAJcreated_by_id: adm_UkLWZg9DAJ+ created_by_type: admin_useroriginator_type:originator_id:meta:@@ -7351,6 +7350,7 @@ paths:outstanding: truecustomer_id: cust_UkLWZg9DAJcreated_by_id: adm_gbHJdmfrXB+ created_by_type: admin_useroriginator_type:originator_id:requestBody:@@ -7429,6 +7429,7 @@ paths:outstanding: truecustomer_id: cust_UkLWZg9DAJcreated_by_id: adm_UkLWZg9DAJ+ created_by_type: admin_useroriginator_type:originator_id:requestBody:@@ -34415,12 +34416,10 @@ paths:<Accordion title="Filters through associations">- Prefix an associated record's attribute with the association, as in `q[created_by_id_eq]`. The same predicates apply.+ Prefix an associated record's attribute with the association, as in `q[customer_id_eq]`. The same predicates apply.| Prefix | Attributes ||---|---|- | `created_by_` | `created_at`, `email`, `first_name`, `id`, `last_name`, `updated_at` |- | `created_by_spree_roles_` | `created_at`, `id`, `name`, `updated_at` || `customer_` | `accepts_email_marketing`, `created_at`, `email`, `first_name`, `id`, `last_name`, `phone`, `updated_at` || `customer_addresses_` | `address1`, `address2`, `city`, `company`, `country_code`, `created_at`, `first_name`, `id`, `last_name`, `phone`, `postal_code`, `state_code`, `updated_at` || `customer_bill_address_` | `address1`, `address2`, `city`, `company`, `country_code`, `created_at`, `first_name`, `id`, `last_name`, `phone`, `postal_code`, `state_code`, `updated_at` |@@ -34464,6 +34463,7 @@ paths:outstanding: truecustomer_id: cust_UkLWZg9DAJcreated_by_id: adm_UkLWZg9DAJ+ created_by_type: admin_useroriginator_type:originator_id:meta:@@ -34572,6 +34572,7 @@ paths:outstanding: truecustomer_id: cust_UkLWZg9DAJcreated_by_id: adm_UkLWZg9DAJ+ created_by_type: admin_useroriginator_type:originator_id:schema:@@ -45450,7 +45451,9 @@ paths:pattern: "^-?\\d+(\\.\\d+)?$"default: {}amount:- type: string+ type:+ - string+ - 'null'format: moneypattern: "^-?\\d+(\\.\\d+)?$"default: '0'@@ -45499,7 +45502,9 @@ paths:pattern: "^-?\\d+(\\.\\d+)?$"default: {}amount:- type: string+ type:+ - string+ - 'null'format: moneypattern: "^-?\\d+(\\.\\d+)?$"default: '0'@@ -45550,7 +45555,9 @@ paths:pattern: "^-?\\d+(\\.\\d+)?$"default: {}amount:- type: string+ type:+ - string+ - 'null'format: moneypattern: "^-?\\d+(\\.\\d+)?$"default: '0'@@ -72195,6 +72202,18 @@ components:created_by_id:type: stringnullable: true+ created_by_type:+ anyOf:+ - type: string+ enum:+ - admin_user+ - api_key+ - type: string+ nullable: true+ description: The values listed are the built-in ones; extensions may add+ more.+ created_by:+ "$ref": "#/components/schemas/Actor"originator_type:type: stringnullable: true@@ -72203,8 +72222,6 @@ components:nullable: truecustomer:"$ref": "#/components/schemas/Customer"- created_by:- "$ref": "#/components/schemas/AdminUser"required:- id- amount@@ -72219,6 +72236,7 @@ components:- outstanding- customer_id- created_by_id+ - created_by_type- originator_type- originator_idx-typelizer: true@@ -75756,6 +75774,7 @@ components:format: moneypattern: "^-?\\d+(\\.\\d+)?$"default: '0'+ nullable: truecurrency:type: stringformat: currency@@ -75788,6 +75807,7 @@ components:format: moneypattern: "^-?\\d+(\\.\\d+)?$"default: '0'+ nullable: truecurrency:type: stringformat: currency@@ -75833,6 +75853,7 @@ components:format: moneypattern: "^-?\\d+(\\.\\d+)?$"default: '0'+ nullable: truecurrency:type: stringformat: currency@@ -85748,7 +85769,6 @@ components:memo: textupdated_at: datetimeassociations:- created_by: AdminUsercustomer: Customerscopes:from_gift_card: booleandiff --git a/docs/api-reference/seller.yaml b/docs/api-reference/seller.yamlindex e77b94cca0..83ae1f6bda 100644--- a/docs/api-reference/seller.yaml+++ b/docs/api-reference/seller.yaml@@ -12805,7 +12805,9 @@ paths:pattern: "^-?\\d+(\\.\\d+)?$"default: {}amount:- type: string+ type:+ - string+ - 'null'format: moneypattern: "^-?\\d+(\\.\\d+)?$"default: '0'@@ -12854,7 +12856,9 @@ paths:pattern: "^-?\\d+(\\.\\d+)?$"default: {}amount:- type: string+ type:+ - string+ - 'null'format: moneypattern: "^-?\\d+(\\.\\d+)?$"default: '0'@@ -12905,7 +12909,9 @@ paths:pattern: "^-?\\d+(\\.\\d+)?$"default: {}amount:- type: string+ type:+ - string+ - 'null'format: moneypattern: "^-?\\d+(\\.\\d+)?$"default: '0'@@ -30493,6 +30499,7 @@ components:format: moneypattern: "^-?\\d+(\\.\\d+)?$"default: '0'+ nullable: truecurrency:type: stringformat: currency@@ -30525,6 +30532,7 @@ components:format: moneypattern: "^-?\\d+(\\.\\d+)?$"default: '0'+ nullable: truecurrency:type: stringformat: currency@@ -30570,6 +30578,7 @@ components:format: moneypattern: "^-?\\d+(\\.\\d+)?$"default: '0'+ nullable: truecurrency:type: stringformat: currencydiff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdxindex 25457685f7..21d6cea3f9 100644--- a/docs/developer/upgrades/5.6-to-6.0.mdx+++ b/docs/developer/upgrades/5.6-to-6.0.mdx@@ -185,11 +185,12 @@ bundle exec rake spree:stock:recount_levelsbundle exec rake spree:upgrade:backfill_actor_types```-Orders, refunds, returns, exchanges, claims and stock receipts remember who-cancelled, approved, created or received them. In 6.0 that can be a member of-staff **or an API key**, so each id column — `canceler_id`, `approver_id`,-`created_by_id`, `refunder_id`, `received_by_id` — gained a type column beside-it (`canceler_type`, and so on) naming which kind of actor the id points at.+Orders, refunds, returns, exchanges, claims, stock receipts and store credits+remember who cancelled, approved, created, received or issued them. In 6.0 that+can be a member of staff **or an API key**, so each id column — `canceler_id`,+`approver_id`, `created_by_id`, `refunder_id`, `received_by_id` — gained a type+column beside it (`canceler_type`, and so on) naming which kind of actor the id+points at.Rows written before the upgrade carry an id and an empty type; this task fillsthe type in. Until it runs they still read as the staff member they always@@ -1087,6 +1088,8 @@ Two enforcement changes on the Admin API:- **JWT staff pass the same per-controller key gate as secret keys.** A request whose principal lacks `<read|write>_<resource>` gets a 403 with `details.required_permission` naming the missing key.- **Staff endpoints moved out of the `settings` scope.** `/admin_users`, `/invitations`, and `/roles` now require the new `read_staff` / `write_staff` scopes; secret keys minted with `settings` before 6.0 lose those endpoints. `/countries` and `/locales` became scope-exempt reference data.+- **The CORS allowlist moved out of the `settings` scope too.** `/allowed_origins` requires `read_api_keys` / `write_api_keys` (6.0 release candidates briefly held it under `staff`): an allowed origin can read any signed-in admin's access token through the cookie-authenticated refresh endpoint, so it is managed like a credential.+- **Paying a customer back needs `write_refunds`.** Refunding a return, resolving a claim with a refund, fulfilling an exchange and cancelling an order with `refund_payments` require it alongside `write_orders`, as the nested refunds endpoint always did. Roles and keys that only hold `write_orders` get a 403 on those calls; the dashboard hides the actions from them.### Rich-text fields read as plain text plus HTMLdiff --git a/packages/admin-sdk/src/types/filters.generated.ts b/packages/admin-sdk/src/types/filters.generated.tsindex 25f0340656..3cb7cbb221 100644--- a/packages/admin-sdk/src/types/filters.generated.ts+++ b/packages/admin-sdk/src/types/filters.generated.ts@@ -2427,7 +2427,6 @@ export interface StoreCreditFilterExtensions {}export interface StoreCreditSortExtensions {}export type StoreCreditFilters = StoreCreditFields- & Filter.Prefixed<'created_by_', AdminUserFields & Filter.Prefixed<'spree_roles_', RoleFields>>& Filter.Prefixed<'customer_', CustomerFields & Filter.Prefixed<'addresses_', AddressFields> & Filter.Prefixed<'bill_address_', AddressFields> & Filter.Prefixed<'customer_groups_', CustomerGroupFields> & Filter.Prefixed<'orders_', OrderFields> & Filter.Prefixed<'ship_address_', AddressFields> & Filter.Prefixed<'spree_roles_', RoleFields> & Filter.Prefixed<'tags_', TagFields>>& {from_gift_card?: booleandiff --git a/packages/admin-sdk/src/types/generated/StoreCredit.ts b/packages/admin-sdk/src/types/generated/StoreCredit.tsindex 2154cc487c..2f53b2c4cf 100644--- a/packages/admin-sdk/src/types/generated/StoreCredit.ts+++ b/packages/admin-sdk/src/types/generated/StoreCredit.ts@@ -1,7 +1,7 @@-// Typelizer digest d23e2b73f8970f8d9d0fe7e8a686d910+// Typelizer digest 1ee5f0adf29982e3fac1be03a2418379//// DO NOT MODIFY: This file was automatically generated by Typelizer.-import type {Customer, AdminUser, CurrencyCode} from '@/types'+import type {Actor, Customer, CurrencyCode, ActorKind} from '@/types'interface StoreCredit {id: string;@@ -17,10 +17,11 @@ interface StoreCredit {outstanding: boolean;customer_id: string | null;created_by_id: string | null;+ created_by_type: ActorKind | null;+ created_by?: Actor;originator_type: string | null;originator_id: string | null;customer?: Customer;- created_by?: AdminUser;}export default StoreCredit;diff --git a/packages/admin-sdk/src/zod/generated/StoreCredit.ts b/packages/admin-sdk/src/zod/generated/StoreCredit.tsindex a9bb559248..0afb6859ab 100644--- a/packages/admin-sdk/src/zod/generated/StoreCredit.ts+++ b/packages/admin-sdk/src/zod/generated/StoreCredit.ts@@ -1,7 +1,7 @@// This file is auto-generated. Do not edit directly.import { z } from 'zod';import type StoreCredit from '../../types/generated/StoreCredit';-import { AdminUserSchema } from './AdminUser';+import { ActorSchema } from './Actor';import { CustomerSchema } from './Customer';export const StoreCreditSchema = z.object({@@ -18,10 +18,11 @@ export const StoreCreditSchema = z.object({outstanding: z.boolean(),customer_id: z.string().nullable(),created_by_id: z.string().nullable(),+ created_by_type: z.string().nullable(),+ created_by: ActorSchema.optional(),originator_type: z.string().nullable(),originator_id: z.string().nullable(),get customer() { return CustomerSchema.optional(); },- created_by: AdminUserSchema.optional(),}) as unknown as z.ZodObject<{id: z.ZodType<StoreCredit['id']>;amount: z.ZodType<StoreCredit['amount']>;@@ -36,10 +37,11 @@ export const StoreCreditSchema = z.object({outstanding: z.ZodType<StoreCredit['outstanding']>;customer_id: z.ZodType<StoreCredit['customer_id']>;created_by_id: z.ZodType<StoreCredit['created_by_id']>;+ created_by_type: z.ZodType<StoreCredit['created_by_type']>;+ created_by: z.ZodOptional<z.ZodType<Exclude<StoreCredit['created_by'], undefined>>>;originator_type: z.ZodType<StoreCredit['originator_type']>;originator_id: z.ZodType<StoreCredit['originator_id']>;customer: z.ZodOptional<z.ZodType<Exclude<StoreCredit['customer'], undefined>>>;- created_by: z.ZodOptional<z.ZodType<Exclude<StoreCredit['created_by'], undefined>>>;}>;export type { StoreCredit };diff --git a/packages/dashboard/e2e/refund-permissions.spec.ts b/packages/dashboard/e2e/refund-permissions.spec.tsnew file mode 100644index 0000000000..3a229e0871--- /dev/null+++ b/packages/dashboard/e2e/refund-permissions.spec.ts@@ -0,0 +1,65 @@+import { expect, request, test } from '@playwright/test'+import { adminRequest, createPlacedOrder, invitationAcceptancePath, login } from './helpers'++// Paying a customer back takes the refunds permission, so a teammate whose+// role handles orders but not refunds must not be offered it.+test.describe('refund permissions', () => {+ test('hides the refund choice from staff without the refunds permission', async ({ page }) => {+ const session = await login(page)+ const order = await createPlacedOrder(page, session.accessToken, { ship: false })+ const stamp = Date.now()+ const password = 'e2e-password-123'+ const email = `e2e-orders-only-${stamp}@example.com`++ const role = await adminRequest<{ id: string }>(page, session, 'post', '/roles', {+ name: `e2e-orders-only-${stamp}`,+ permissions: ['read_orders', 'write_orders', 'read_customers', 'read_products'],+ })+ const invitation = await adminRequest<{ id: string }>(page, session, 'post', '/invitations', {+ email,+ role_id: role.id,+ })+ const acceptance = new URL(+ await invitationAcceptancePath(page, session, `/api/v3/admin/invitations/${invitation.id}`),+ 'http://localhost',+ )+ const invitee = await request.newContext({ baseURL: new URL(page.url()).origin })+ try {+ const accepted = await invitee.post(+ `/api/v3/admin/auth/invitations/${invitation.id}/accept`,+ {+ data: {+ token: acceptance.searchParams.get('token'),+ password,+ password_confirmation: password,+ first_name: 'Robin',+ last_name: 'Teammate',+ },+ },+ )+ expect(accepted.ok(), await accepted.text()).toBeTruthy()+ } finally {+ await invitee.dispose()+ }++ // The admin, who may refund, is offered the choice when cancelling.+ await page.goto(`/${session.store_id}/orders/${order.id}`)+ await page.getByRole('button', { name: /more actions/i }).click()+ await page.getByRole('menuitem', { name: /cancel order/i }).click()+ const dialog = page.getByRole('dialog')+ await expect(dialog.getByRole('checkbox', { name: /refund the customer/i })).toBeVisible({+ timeout: 15_000,+ })+ await page.keyboard.press('Escape')++ // The teammate is not.+ await login(page, { email, password })+ await page.goto(`/${session.store_id}/orders/${order.id}`)+ await page.getByRole('button', { name: /more actions/i }).click()+ await page.getByRole('menuitem', { name: /cancel order/i }).click()+ await expect(page.getByRole('dialog')).toBeVisible({ timeout: 15_000 })+ await expect(+ page.getByRole('dialog').getByRole('checkbox', { name: /refund the customer/i }),+ ).toHaveCount(0)+ })+})diff --git a/packages/dashboard/src/components/spree/order-post-sale-cards.tsx b/packages/dashboard/src/components/spree/order-post-sale-cards.tsxindex c51ea6dbbb..9bf24463a2 100644--- a/packages/dashboard/src/components/spree/order-post-sale-cards.tsx+++ b/packages/dashboard/src/components/spree/order-post-sale-cards.tsx@@ -1,6 +1,6 @@import type { Claim, Exchange, Order } from '@spree/admin-sdk'import { CLAIM_STATUSES, EXCHANGE_STATUSES, subsetOf } from '@spree/core'-import { isPositiveMoney, Money } from '@spree/dashboard-core'+import { isPositiveMoney, Money, usePermissions } from '@spree/dashboard-core'import {Badge,Button,@@ -59,6 +59,10 @@ export function OrderExchangesCard({ order }: { order: Order }) {const confirm = useConfirm()const { data } = useOrderExchanges(orderId)const { create, approve, receive, fulfill, cancel } = useExchangeActions(orderId)+ // Fulfilling settles money on what came back, so the API wants the refunds+ // permission for it; without it the action is not offered.+ const { permissionKeys } = usePermissions()+ const canRefund = permissionKeys.includes('write_refunds')const [creating, setCreating] = useState(false)const exchanges = data?.data ?? []@@ -126,7 +130,7 @@ export function OrderExchangesCard({ order }: { order: Order }) {{t('admin.pages.orders.detail.returns.actions.receive')}</DropdownMenuItem>)}- {exchange.status === 'received' && (+ {exchange.status === 'received' && canRefund && (<DropdownMenuItemonClick={async () => {// A dearer replacement leaves the customer owing@@ -231,6 +235,10 @@ export function OrderClaimsCard({ order }: { order: Order }) {const confirm = useConfirm()const { data } = useOrderClaims(orderId)const { create, approve, resolve, deny, cancel } = useClaimActions(orderId)+ // A resolution may pay the customer back, which takes the refunds+ // permission; resolving is left to staff who hold it.+ const { permissionKeys } = usePermissions()+ const canRefund = permissionKeys.includes('write_refunds')const [creatingClaim, setCreatingClaim] = useState(false)const [resolving, setResolving] = useState<Claim | null>(null)@@ -289,7 +297,7 @@ export function OrderClaimsCard({ order }: { order: Order }) {{t('admin.pages.orders.detail.returns.actions.approve')}</DropdownMenuItem>)}- {claim.status === 'approved' && (+ {claim.status === 'approved' && canRefund && (<DropdownMenuItem onClick={() => setResolving(claim)}><BanknoteIcon className="size-4" />{t('admin.pages.orders.detail.claims.actions.resolve')}diff --git a/packages/dashboard/src/components/spree/order-returns-card.tsx b/packages/dashboard/src/components/spree/order-returns-card.tsxindex 912d55f9ff..e61f98feb5 100644--- a/packages/dashboard/src/components/spree/order-returns-card.tsx+++ b/packages/dashboard/src/components/spree/order-returns-card.tsx@@ -7,6 +7,7 @@ import {returnOwesNothing,returnRefundSummary,useMoneyLocale,+ usePermissions,} from '@spree/dashboard-core'import {Badge,@@ -67,6 +68,10 @@ export function OrderReturnsCard({ order }: { order: Order }) {const { data } = useOrderReturns(orderId)const { create, approve, receive, refund, cancel, buyLabel, refundLabel, deleteLabel } =useReturnActions(orderId)+ // Paying the customer back is the refunds permission's, not the orders+ // one's: the API refuses a refund without it, so the action is not offered.+ const { permissionKeys } = usePermissions()+ const canRefund = permissionKeys.includes('write_refunds')const [creating, setCreating] = useState(false)const [receiving, setReceiving] = useState<Return | null>(null)@@ -135,7 +140,7 @@ export function OrderReturnsCard({ order }: { order: Order }) {{t('admin.pages.orders.detail.returns.actions.receive')}</DropdownMenuItem>)}- {returnRecord.status === 'received' && (+ {returnRecord.status === 'received' && canRefund && (<DropdownMenuItem onClick={() => setRefunding(returnRecord)}>{returnOwesNothing(returnRecord.refundable_total) ? (<>diff --git a/packages/dashboard/src/components/spree/orders/order-cancel-dialog.tsx b/packages/dashboard/src/components/spree/orders/order-cancel-dialog.tsxindex 08373c3f45..a035b64f3a 100644--- a/packages/dashboard/src/components/spree/orders/order-cancel-dialog.tsx+++ b/packages/dashboard/src/components/spree/orders/order-cancel-dialog.tsx@@ -5,6 +5,7 @@ import {type CancelOrderFormValues,cancelOrderFormSchema,mapSpreeErrorsToForm,+ usePermissions,useResourceMutation,} from '@spree/dashboard-core'import { OrderCancelDialog as SharedOrderCancelDialog } from '@spree/dashboard-ui'@@ -19,6 +20,9 @@ import { ReasonField } from '../reason-field'*/export function OrderCancelDialog({ orderId, onClose }: { orderId: string; onClose: () => void }) {const { t } = useTranslation()+ // Handing money back on cancel is the refunds permission's; the choice+ // is only offered to staff who hold it.+ const { permissionKeys } = usePermissions()const cancelMutation = useResourceMutation({mutationFn: (values: CancelOrderFormValues) =>@@ -50,7 +54,7 @@ export function OrderCancelDialog({ orderId, onClose }: { orderId: string; onCloreturn (<SharedOrderCancelDialogform={form}- showRefund+ showRefund={permissionKeys.includes('write_refunds')}reasonField={/* A merchant who has not curated the vocabulary can still cancel, sothe empty choice stays available rather than forcing a reason. */diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsxindex de97e305d5..c9d073485f 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsx@@ -37,9 +37,10 @@ import {import { PencilIcon, PlusIcon, TrashIcon } from '@spree/dashboard-ui/icons'import { useIsFetching } from '@tanstack/react-query'import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'-import { useRef, useState } from 'react'+import { type ReactNode, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { z } from 'zod/v4'+import { ActorLabel } from '../../../../components/spree/actor-label'import { ApiCustomFieldsCard } from '../../../../components/spree/custom-fields/custom-fields-inline'import { EditStoreCreditDialog } from '../../../../components/spree/store-credits/edit-store-credit-dialog'import { IssueStoreCreditDialog } from '../../../../components/spree/store-credits/issue-store-credit-dialog'@@ -369,7 +370,7 @@ function StoreCreditSheet({/><DetailRowlabel={t('admin.store_credits.columns.issued_by')}- value={credit.created_by?.email ?? '—'}+ value={credit.created_by ? <ActorLabel actor={credit.created_by} /> : '—'}/><DetailRowlabel={t('admin.fields.store_credit.memo.label')}@@ -468,7 +469,7 @@ function DetailRow({emphasis = false,}: {label: string- value: string+ value: ReactNodenumeric?: booleanemphasis?: boolean}) {diff --git a/packages/dashboard/src/tables/store-credits.tsx b/packages/dashboard/src/tables/store-credits.tsxindex 0b09d86d68..e05f58ad51 100644--- a/packages/dashboard/src/tables/store-credits.tsx+++ b/packages/dashboard/src/tables/store-credits.tsx@@ -3,6 +3,7 @@ import { defineTable, Money } from '@spree/dashboard-core'import { Badge, RelativeTime, ResourceNameCell } from '@spree/dashboard-ui'import { BanknoteIcon } from '@spree/dashboard-ui/icons'import i18n from 'i18next'+import { ActorLabel } from '../components/spree/actor-label'import { adminUserAutocompleteProps } from '../hooks/use-admin-users'import { customerAutocompleteProps } from '../hooks/use-customers'import { erasedFieldValue } from '../lib/erased-customer'@@ -140,7 +141,7 @@ defineTable<StoreCredit>('store-credits', {expand: 'created_by',sortable: false,default: false,- render: (credit) => credit.created_by?.email ?? '—',+ render: (credit) => (credit.created_by ? <ActorLabel actor={credit.created_by} /> : '—'),},{key: 'created_at',diff --git a/spree/api/app/controllers/spree/api/v3/admin/allowed_origins_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/allowed_origins_controller.rbindex 4d352e1ea5..d7f947a15a 100644--- a/spree/api/app/controllers/spree/api/v3/admin/allowed_origins_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/allowed_origins_controller.rb@@ -3,10 +3,10 @@ module Spreemodule V3module Adminclass AllowedOriginsController < ResourceController- # Staff, not settings: an allowed origin can read every admin's- # session through the cookie-authenticated refresh endpoint, so- # editing the list is staff-level authority (see the catalog).- scoped_resource :staff+ # A credential, not a setting: an allowed origin can read every+ # admin's session through the cookie-authenticated refresh endpoint,+ # so the list is managed under the same scope as API keys.+ scoped_resource :api_keysrequest_params :allowed_origin do |body|body.attribute :origin, :string,diff --git a/spree/api/app/controllers/spree/api/v3/admin/commission_lines_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/commission_lines_controller.rbindex 4938c06290..fb7ff5d496 100644--- a/spree/api/app/controllers/spree/api/v3/admin/commission_lines_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/commission_lines_controller.rb@@ -23,8 +23,8 @@ module Spree# Reached through the store's own orders: the lines carry no store of# their own, and the order is what ties them to one.- def scope- super.where(order_id: current_store.orders.select(:id))+ def store_scope+ model_class.where(order_id: current_store.orders.select(:id))end# Every association the serializer reads, so a page of lines costs adiff --git a/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rbindex 60219120e8..7a86a338e9 100644--- a/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb@@ -66,18 +66,15 @@ module Spree# no-op), so the store boundary for customer parents is enforced by# the `authorize!(:update, @parent)` ability check above.#- # Fails closed: `Spree::Base.for_store` answers the bare class when the- # store has no association for the model, which would search every- # store's records.+ # `Spree::Base.for_store` answers nothing for a model the store has+ # no association for, so an unexpected parent type 404s rather than+ # searching every store's records.def parent_relationklass = parent_lookup.klassreturn klass.where(id: current_store.id) if klass <= Spree::Storereturn klass if klass <= Spree.customer_class- relation = klass.for_store(current_store)- raise ActiveRecord::RecordNotFound, 'Parent resource not found' if relation.equal?(klass)-- relation+ klass.for_store(current_store)end# Product-family parents have no scope pair of their own — theirdiff --git a/spree/api/app/controllers/spree/api/v3/admin/customers/store_credits_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers/store_credits_controller.rbindex 820e3b2811..67b3e7807f 100644--- a/spree/api/app/controllers/spree/api/v3/admin/customers/store_credits_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/customers/store_credits_controller.rb@@ -18,7 +18,7 @@ module Spree# POST /api/v3/admin/customers/:customer_id/store_creditsdef create@resource = @parent.store_credits.new(store_credit_attributes)- @resource.created_by = try_spree_current_user+ @resource.created_by = current_actor@resource.store ||= current_storeauthorize_resource!(@resource, :create)diff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rbindex 4fe7105eab..f4935a18bd 100644--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb@@ -481,13 +481,23 @@ module Spreebase_scope = if @parent.present?@parent.send(parent_association)else- model_class.for_store(current_store)+ store_scopeendbase_scope = base_scope.includes(scope_includes) if scope_includes.any?base_scope = base_scope.preload_associations_lazilymodel_class.include?(Spree::TranslatableResource) ? base_scope.i18n : base_scopeend+ # The store's rows of this model when the resource has no parent. A+ # model the store reaches through another record rather than an+ # association of its own — a commission line through its order —+ # names that path here, since `for_store` answers nothing for it.+ #+ # @return [ActiveRecord::Relation]+ def store_scope+ model_class.for_store(current_store)+ end+# Action names treated as reads. Override in subclasses with custom# read-only member/collection actions (e.g. add `analytics`, `types`)# so they map to the `:show` ability instead of a write.diff --git a/spree/api/app/serializers/spree/api/v3/admin/store_credit_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/store_credit_serializer.rbindex 3aa4a8d747..826004782b 100644--- a/spree/api/app/serializers/spree/api/v3/admin/store_credit_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/store_credit_serializer.rb@@ -7,6 +7,7 @@ module Spreetypelize customer_id: [:string, nullable: true],created_by_id: [:string, nullable: true],+ created_by_type: [:string, nullable: true, enum: Spree::Actor::BUILT_IN_KINDS, enum_type_name: 'ActorKind'],memo: [:string, nullable: true],amount: [:string, nullable: false], amount_used: [:string, nullable: false],amount_remaining: [:string, nullable: false],@@ -27,7 +28,8 @@ module Spree# money_attributes types its fields nullable for gated guests; the# Admin API never gates prices.typelize amount_authorized: [:string, nullable: false]- prefixed_id_attributes :customer, :created_by+ prefixed_id_attributes :customer+ actor_attributes :created_by# Why the credit exists: the return, exchange, claim or gift card# that issued it, or null when an admin issued it by hand. The type@@ -50,10 +52,6 @@ module Spreeone :customer,resource: proc { Spree.api.admin_customer_serializer },if: proc { expand?('customer') }-- one :created_by,- resource: proc { Spree.api.admin_admin_user_serializer },- if: proc { expand?('created_by') }endendenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/allowed_origins_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/allowed_origins_controller_spec.rbindex e7a630172b..6774093644 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/allowed_origins_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/allowed_origins_controller_spec.rb@@ -8,8 +8,8 @@ RSpec.describe Spree::Api::V3::Admin::AllowedOriginsController, type: :controllebefore { request.headers.merge!(api_key_headers) }# An allowed origin may call the cookie-authenticated refresh endpoint from- # a browser and read back any admin's access token, so editing the list is- # staff authority — a settings key must not be enough.+ # a browser and read back any admin's access token, so the list is managed+ # like a credential — a settings key must not be enough.describe 'POST #create' dosubject { post :create, params: { origin: 'https://attacker.example' }, as: :json }@@ -19,12 +19,12 @@ RSpec.describe Spree::Api::V3::Admin::AllowedOriginsController, type: :controlleit 'is denied' doexpect { subject }.not_to change(Spree::AllowedOrigin, :count)expect(response).to have_http_status(:forbidden)- expect(json_response['error']['details']['required_scope']).to eq('write_staff')+ expect(json_response['error']['details']['required_scope']).to eq('write_api_keys')endend- context 'with a staff key' do- let(:secret_api_key) { create(:api_key, :secret, store: store, scopes: %w[write_staff]) }+ context 'with an api keys key' do+ let(:secret_api_key) { create(:api_key, :secret, store: store, scopes: %w[write_api_keys]) }it 'creates the origin' doexpect { subject }.to change(Spree::AllowedOrigin, :count).by(1)diff --git a/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_polymorphic_parent_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_polymorphic_parent_spec.rbindex 31dc5d5d9b..38963fbf3c 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_polymorphic_parent_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_polymorphic_parent_spec.rb@@ -91,13 +91,13 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controllerendend- # `Spree::Base.for_store` answers the bare class when the store has no- # association for a model; the lookup must refuse rather than search every- # store's records.+ # `Spree::Base.for_store` answers nothing for a model the store has no+ # association for; the lookup refuses rather than searching every store's+ # records.describe 'a parent the store cannot scope' dolet!(:promotion) { create(:promotion) }- before { allow(Spree::Promotion).to receive(:for_store).and_return(Spree::Promotion) }+ before { allow(Spree::Promotion).to receive(:for_store).and_return(Spree::Promotion.none) }it 'returns not found' doget :index, params: { promotion_id: promotion.prefixed_id }, as: :jsondiff --git a/spree/api/spec/controllers/spree/api/v3/admin/customers/store_credits_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/customers/store_credits_controller_spec.rbindex 074b61edd2..e19575d1ae 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/customers/store_credits_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/customers/store_credits_controller_spec.rb@@ -121,6 +121,21 @@ RSpec.describe Spree::Api::V3::Admin::Customers::StoreCreditsController, type: :expect(created.amount).to eq(25.00)expect(created.memo).to eq('Goodwill')end++ # A credit issued by an integration names the key it called with, as the+ # order operations do.+ context 'with a secret API key' do+ let(:secret_api_key) { create(:api_key, :secret, store: store, scopes: %w[write_store_credits]) }+ let(:headers) { api_key_headers }++ it 'records the key as the issuer' do+ post :create, params: { customer_id: customer.prefixed_id, amount: '25.00', currency: 'USD' }, as: :json++ expect(response).to have_http_status(:created)+ expect(json_response['created_by_type']).to eq('api_key')+ expect(Spree::StoreCredit.find_by_prefix_id(json_response['id']).created_by).to eq(secret_api_key)+ end+ endenddescribe 'PATCH #update' dodiff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rbindex a1ca49e637..9cb7cfc9fd 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb@@ -266,6 +266,22 @@ RSpec.describe Spree::Api::V3::Admin::Orders::ReturnsController, type: :controllendend+ context 'with a key that may refund' do+ let(:secret_api_key) { create(:api_key, :secret, store: store, scopes: %w[write_orders write_refunds]) }+ let(:headers) { api_key_headers }++ it 'refunds to store credit issued by the key' do+ patch :refund, params: {+ order_id: order.prefixed_id,+ id: return_record.prefixed_id,+ refund_method: 'store_credit'+ }, as: :json++ expect(response).to have_http_status(:ok)+ expect(Spree::StoreCredit.find_by(originator: return_record).created_by).to eq(secret_api_key)+ end+ end+it 'rejects an unknown refund method' dopatch :refund, params: {order_id: order.prefixed_id,diff --git a/spree/api/spec/integration/spree/api/v3/admin/allowed_origins_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/allowed_origins_spec.rbindex e7f8d37b50..cd0ef6a791 100644--- a/spree/api/spec/integration/spree/api/v3/admin/allowed_origins_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/allowed_origins_spec.rb@@ -20,7 +20,7 @@ RSpec.describe 'Admin Allowed Origins API', type: :request, swagger_doc: 'api-rethe admin cookie session (see`docs/plans/5.5-admin-auth-cookie-refresh.md`).DESC- admin_scope :read, :staff+ admin_scope :read, :api_keysadmin_sdk_example 'allowed-origins/list'@@ -67,7 +67,7 @@ RSpec.describe 'Admin Allowed Origins API', type: :request, swagger_doc: 'api-re`scheme://host[:port]` (no path, query, or fragment) and use `http` or`https`.DESC- admin_scope :write, :staff+ admin_scope :write, :api_keysadmin_sdk_example 'allowed-origins/create'@@ -107,7 +107,7 @@ RSpec.describe 'Admin Allowed Origins API', type: :request, swagger_doc: 'api-reproduces 'application/json'security [api_key: [], bearer_auth: []]description 'Returns a single allowed origin by prefixed ID.'- admin_scope :read, :staff+ admin_scope :read, :api_keysadmin_sdk_example 'allowed-origins/get'@@ -145,7 +145,7 @@ RSpec.describe 'Admin Allowed Origins API', type: :request, swagger_doc: 'api-reproduces 'application/json'security [api_key: [], bearer_auth: []]description 'Updates an existing allowed origin.'- admin_scope :write, :staff+ admin_scope :write, :api_keysadmin_sdk_example 'allowed-origins/update'@@ -186,7 +186,7 @@ RSpec.describe 'Admin Allowed Origins API', type: :request, swagger_doc: 'api-readmin SPA running at that origin will no longer be able to call theadmin API from a browser.DESC- admin_scope :write, :staff+ admin_scope :write, :api_keysadmin_sdk_example 'allowed-origins/delete'diff --git a/spree/core/app/models/spree/base.rb b/spree/core/app/models/spree/base.rbindex 0ef053f01f..ee60fb7e3f 100644--- a/spree/core/app/models/spree/base.rb+++ b/spree/core/app/models/spree/base.rb@@ -46,13 +46,21 @@ class Spree::Base < ApplicationRecordselect("#{klass.table_name}.*").select(*(fields || klass::TRANSLATABLE_FIELDS))}+ # The store's own rows of this model, through the association named after+ # it. A model the store has no association for answers nothing: a tenant+ # boundary that quietly widened to every store's rows is how a cross-store+ # read ships unnoticed. Global reference data (countries, roles) and+ # records reached through a parent are fetched as such, never through here.+ #+ # @param store [Spree::Store]+ # @return [ActiveRecord::Relation]def self.for_store(store)plural_model_name = model_name.plural.gsub(/spree_/, '').to_symif store.respond_to?(plural_model_name)store.send(plural_model_name)else- self+ noneendenddiff --git a/spree/core/app/models/spree/store_credit.rb b/spree/core/app/models/spree/store_credit.rbindex 6a4f10a0bc..7a314a8078 100644--- a/spree/core/app/models/spree/store_credit.rb+++ b/spree/core/app/models/spree/store_credit.rb@@ -3,6 +3,7 @@ module Spreehas_prefix_id :creditinclude Spree::SingleStoreResource+ include Spree::ActedByinclude Spree::HasCustomFieldsinclude Spree::Metadatainclude Spree::CanonicalDecimals@@ -25,7 +26,7 @@ module Spree# to attach it to.belongs_to :customer, class_name: "::#{Spree.customer_class}", optional: trueinclude Spree::DeprecatedCustomerAlias- belongs_to :created_by, class_name: Spree.admin_user_class.to_s, foreign_key: 'created_by_id', optional: true+ acted_by :created_bybelongs_to :originator, polymorphic: true, optional: truebelongs_to :refunded_order, class_name: 'Spree::Order', optional: true,inverse_of: :store_credit_refunds@@ -40,8 +41,6 @@ module Spreevalidate :amount_used_less_than_or_equal_to_amountvalidate :amount_authorized_less_than_or_equal_to_amount- delegate :email, to: :created_by, prefix: true, allow_nil: true-# Redemption order: the oldest credit is spent first.scope :oldest_first, -> { order(:created_at, :id) }# @deprecated Removed in Spree 6.1 — store credit types are gone; use {.oldest_first}.@@ -110,7 +109,7 @@ module Spreeself.whitelisted_ransackable_attributes = %w[customer_id created_by_id amount currency memo]search_by :memo- self.whitelisted_ransackable_associations = %w[customer created_by]+ self.whitelisted_ransackable_associations = %w[customer]self.whitelisted_ransackable_scopes = %w[outstanding from_gift_card]self.ransackable_scope_types = %w[outstanding from_gift_card].index_with('boolean')# Staff notes and who issued the credit are back-office data.@@ -283,6 +282,7 @@ module Spreeamount: amount,customer_id: customer_id,created_by_id: created_by_id,+ created_by_type: created_by_type,currency: currency,memo: credit_allocation_memo,store: storediff --git a/spree/core/app/models/spree/webhook_endpoint.rb b/spree/core/app/models/spree/webhook_endpoint.rbindex 6975cbe7b5..fd4d23fc74 100644--- a/spree/core/app/models/spree/webhook_endpoint.rb+++ b/spree/core/app/models/spree/webhook_endpoint.rb@@ -203,12 +203,22 @@ module Spreeuri = URI.parse(url)blacklist = SsrfFilter::IPV4_BLACKLIST + SsrfFilter::IPV6_BLACKLIST- addresses = Resolv.getaddresses(uri.host)+ addresses = host_addresses(uri.host)if addresses.any? { |addr| blacklist.any? { |range| range.include?(IPAddr.new(addr)) } }errors.add(:url, :internal_address_not_allowed)endrescue URI::InvalidURIError, Resolv::ResolvError, IPAddr::InvalidAddressError, ArgumentError# URI format validation handles invalid URLs; DNS failures are not SSRFend++ # A literal address first — including the forms a resolver answers+ # nothing for, such as a bracketed IPv6 address, `127.1`, or a decimal or+ # hex IPv4 — then DNS for a hostname.+ def host_addresses(host)+ literal = host.to_s.delete_prefix('[').delete_suffix(']')+ Socket.getaddrinfo(literal, nil, nil, Socket::SOCK_STREAM, nil, Socket::AI_NUMERICHOST).map { |entry| entry[3] }.uniq+ rescue SocketError+ Resolv.getaddresses(host)+ endendenddiff --git a/spree/core/db/migrate/20261022000001_store_credit_actor_polymorphic.rb b/spree/core/db/migrate/20261022000001_store_credit_actor_polymorphic.rbnew file mode 100644index 0000000000..6fe7acfa8b--- /dev/null+++ b/spree/core/db/migrate/20261022000001_store_credit_actor_polymorphic.rb@@ -0,0 +1,13 @@+# Makes a store credit's issuer polymorphic, so a credit issued with a secret+# API key — a return an integration refunds to store credit — records the key+# rather than failing. See docs/plans/6.0-action-actors.md.+class StoreCreditActorPolymorphic < ActiveRecord::Migration[8.1]+ def change+ # Nullable with no default: the type is data, filled by+ # `rake spree:upgrade:backfill_actor_types`. Until it runs, the+ # transitional reader resolves these rows through the admin user class.+ add_column :spree_store_credits, :created_by_type, :string+ add_index :spree_store_credits, [:created_by_type, :created_by_id],+ name: 'index_spree_store_credits_on_created_by_actor'+ end+enddiff --git a/spree/core/lib/spree/core/permissions/default_catalog.rb b/spree/core/lib/spree/core/permissions/default_catalog.rbindex 4329a09abc..5694feae97 100644--- a/spree/core/lib/spree/core/permissions/default_catalog.rb+++ b/spree/core/lib/spree/core/permissions/default_catalog.rb@@ -201,19 +201,19 @@ module Spree})catalog.register_scope(:integrations, group: :settings, resources: -> { [Spree::Integration] })- catalog.register_scope(:api_keys, group: :access, resources: -> { [Spree::ApiKey] })+ # The CORS allowlist is a credential as much as a key is: an origin on+ # it may call the cookie-authenticated refresh endpoint from a browser+ # and read back any signed-in admin's access token. So it sits with+ # API keys rather than settings, under a scope a delegated OAuth token+ # never holds.+ catalog.register_scope(:api_keys, group: :access, resources: -> { [Spree::ApiKey, Spree::AllowedOrigin] })# Connecting an AI agent hands a third party a standing credential to# the store, so it is its own permission rather than part of settings# — a merchandiser who may edit a delivery zone is not thereby someone# who may connect Claude to the back office.catalog.register_scope(:oauth_applications, group: :access, resources: -> { [Spree::OauthApplication] })- # The CORS allowlist sits with staff rather than settings: an origin on- # it may call the cookie-authenticated refresh endpoint from a browser- # and read back any signed-in admin's access token, so whoever edits it- # can reach every staff session. That is the authority the staff scope- # already guards, and it is one a delegated OAuth token never holds.catalog.register_scope(:staff, group: :access, resources: -> {- [Spree.admin_user_class, Spree::Invitation, Spree::Role, Spree::RoleUser, Spree::AllowedOrigin]+ [Spree.admin_user_class, Spree::Invitation, Spree::Role, Spree::RoleUser]})# The seller panel's own scopes. Their audience is the seller alone,diff --git a/spree/core/spec/lib/tasks/consolidate_metadata_spec.rb b/spree/core/spec/lib/tasks/consolidate_metadata_spec.rbindex c76e76d731..ce3f17552d 100644--- a/spree/core/spec/lib/tasks/consolidate_metadata_spec.rb+++ b/spree/core/spec/lib/tasks/consolidate_metadata_spec.rb@@ -15,6 +15,11 @@ describe 'metadata consolidation' do# merge and the safety-net rake task are exercised against a synthetic table# still carrying the pre-6.0 pair — the state an out-of-band install is in.before do+ # The registry the real migration left behind names tables as they were+ # then — `spree_assets`, since renamed — and reading a column of a table+ # that no longer exists raises on PostgreSQL. Each example starts from no+ # registry, so only the fixture's own consolidation is ever on record.+ connection.drop_table :spree_consolidated_metadata_tables, if_exists: trueconnection.drop_table table_name, if_exists: trueconnection.create_table table_name do |t|if t.respond_to?(:jsonb)diff --git a/spree/core/spec/models/spree/base_spec.rb b/spree/core/spec/models/spree/base_spec.rbindex 7a0354e562..81ff888429 100644--- a/spree/core/spec/models/spree/base_spec.rb+++ b/spree/core/spec/models/spree/base_spec.rb@@ -165,4 +165,19 @@ describe Spree::Base doexpect { loaded.with_lock { nil } }.not_to raise_errorendend++ describe '.for_store' do+ let(:store) { @default_store }++ it 'reads through the association the store has for the model' do+ expect(Spree::Product.for_store(store).to_sql).to eq(store.products.to_sql)+ end++ # A model the store cannot reach answers nothing: widening to every+ # store's rows is how a cross-store read goes unnoticed.+ it 'answers nothing for a model the store has no association for' do+ expect(Spree::Zone.for_store(store)).to be_none+ end+ end+enddiff --git a/spree/core/spec/models/spree/search_provider/database_spec.rb b/spree/core/spec/models/spree/search_provider/database_spec.rbindex 3b891e8a1f..d8cf7c1c78 100644--- a/spree/core/spec/models/spree/search_provider/database_spec.rb+++ b/spree/core/spec/models/spree/search_provider/database_spec.rb@@ -293,17 +293,24 @@ module Spree# be able to read it back through search, a sort or a range filter.context 'with admin-only custom_fields' dolet!(:definition) do- create(:custom_field_definition, :number_field, :admin_only, :searchable, :sortable,+ create(:custom_field_definition, :number_field, :admin_only, :sortable,namespace: 'internal', key: 'margin')end+ # Text, so the search probe cannot collide with a generated SKU the+ # way a short number can.+ let!(:note) do+ create(:custom_field_definition, :short_text_field, :admin_only, :searchable,+ namespace: 'internal', key: 'note')+ endbefore doproduct_1.set_custom_field(definition, '40')product_2.set_custom_field(definition, '12')+ product_1.set_custom_field(note, 'zq-hidden-note')endit 'ignores them for shoppers' do- expect(provider.search_and_filter(scope: scope, query: '40').products).to be_empty+ expect(provider.search_and_filter(scope: scope, query: 'zq-hidden-note').products).to be_emptyexpect(provider.search_and_filter(scope: scope, filters: { 'cf_internal_margin_gteq' => '30' }).products).to match_array([product_1, product_2, product_3])expect(provider.search_and_filter(scope: scope, sort: '-cf_internal_margin').products.to_a).to eq(provider.search_and_filter(scope: scope).products.to_a)diff --git a/spree/core/spec/models/spree/webhook_endpoint_spec.rb b/spree/core/spec/models/spree/webhook_endpoint_spec.rbindex 511ad0480d..0b5c979213 100644--- a/spree/core/spec/models/spree/webhook_endpoint_spec.rb+++ b/spree/core/spec/models/spree/webhook_endpoint_spec.rb@@ -37,6 +37,16 @@ describe Spree::WebhookEndpoint, type: :model doexpect(webhook_endpoint).not_to be_validend+ # A resolver answers nothing for these spellings, so each must be read+ # as the address it is.+ %w[http://[::1]/hook http://2130706433/hook http://0x7f000001/hook http://127.1/hook].each do |literal|+ it "rejects the loopback address written as #{literal}" do+ webhook_endpoint.url = literal+ expect(webhook_endpoint).not_to be_valid+ expect(webhook_endpoint.errors[:url]).to include('must not point to an internal or private network address')+ end+ end+it 'rejects urls resolving to private IPs' doallow(Resolv).to receive(:getaddresses).with('internal.example.com').and_return(['127.0.0.1'])webhook_endpoint.url = 'https://internal.example.com/webhooks'