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.

Fix: Validated webhook subscriptions and matched them without regular expressions (#14970)

Damian Legawiecfb8a9ce01e16
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yaml
index a2d7b9e0dc..0ac6843691 100644
--- a/docs/api-reference/admin.yaml
+++ b/docs/api-reference/admin.yaml
@@ -84317,7 +84317,8 @@ components:
type: string
description: Event names this endpoint receives. An empty list or `["*"]`
subscribes to every event; otherwise list exact names (`order.completed`)
- or patterns (`order.*`).
+ or patterns with `*` in place of a segment (`order.*`, `*.created`). At
+ most 200 entries of up to 100 characters.
example:
- order.placed
- order.canceled
@@ -84354,7 +84355,8 @@ components:
type: string
description: Event names this endpoint receives. An empty list or `["*"]`
subscribes to every event; otherwise list exact names (`order.completed`)
- or patterns (`order.*`).
+ or patterns with `*` in place of a segment (`order.*`, `*.created`). At
+ most 200 entries of up to 100 characters.
example:
- order.placed
- order.canceled
diff --git a/docs/developer/core-concepts/webhooks.mdx b/docs/developer/core-concepts/webhooks.mdx
index 0388c2a05d..140982babb 100644
--- a/docs/developer/core-concepts/webhooks.mdx
+++ b/docs/developer/core-concepts/webhooks.mdx
@@ -147,6 +147,8 @@ The `subscriptions` array accepts exact event names and wildcard patterns:
| `['order.*', 'payment.*', 'fulfillment.fulfilled']` | Multiple patterns |
| `[]` or `['*']` | All events |
+A pattern is an event name with `*` standing in for whole segments, so `order.*` and `*.created` are accepted while `order.pl*` is not. An endpoint holds at most 200 entries of up to 100 characters each; anything else is refused with a validation error.
+
An event that carries a credential — `customer.password_reset_requested`, which includes a reset token, and `data_request.confirmation_requested`, which includes the token that confirms a customer's data request — is never matched by a pattern. An endpoint receives it only when it names it, and naming it needs the permission to manage customers. Password reset requests for staff and sellers are never sent to webhooks: Spree emails those itself.
To see every event you can subscribe to, including those your installed extensions add, list them:
diff --git a/packages/admin-sdk/src/types/params/WebhookEndpointCreateParams.ts b/packages/admin-sdk/src/types/params/WebhookEndpointCreateParams.ts
index 40f33fdd65..a7c453892a 100644
--- a/packages/admin-sdk/src/types/params/WebhookEndpointCreateParams.ts
+++ b/packages/admin-sdk/src/types/params/WebhookEndpointCreateParams.ts
@@ -9,7 +9,8 @@ export type WebhookEndpointCreateParams = {
active?: boolean
/**
* Event names this endpoint receives. An empty list or `["*"]` subscribes to every event;
- * otherwise list exact names (`order.completed`) or patterns (`order.*`).
+ * otherwise list exact names (`order.completed`) or patterns with `*` in place of a segment
+ * (`order.*`, `*.created`). At most 200 entries of up to 100 characters.
*/
subscriptions?: string[]
}
diff --git a/packages/admin-sdk/src/types/params/WebhookEndpointUpdateParams.ts b/packages/admin-sdk/src/types/params/WebhookEndpointUpdateParams.ts
index 021ea018f1..8ec3c9c1da 100644
--- a/packages/admin-sdk/src/types/params/WebhookEndpointUpdateParams.ts
+++ b/packages/admin-sdk/src/types/params/WebhookEndpointUpdateParams.ts
@@ -9,7 +9,8 @@ export type WebhookEndpointUpdateParams = {
active?: boolean
/**
* Event names this endpoint receives. An empty list or `["*"]` subscribes to every event;
- * otherwise list exact names (`order.completed`) or patterns (`order.*`).
+ * otherwise list exact names (`order.completed`) or patterns with `*` in place of a segment
+ * (`order.*`, `*.created`). At most 200 entries of up to 100 characters.
*/
subscriptions?: string[]
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 97f54287cb..3466607ee5 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -56,3 +56,10 @@ export {
export { currencyParts, normalizeMoneyInput } from './money-input'
// Units
export { UNIT_SYSTEM_WEIGHT_UNITS } from './unit-systems'
+// Webhooks
+export {
+ isWebhookEventPattern,
+ WEBHOOK_EVENT_PATTERN,
+ WEBHOOK_SUBSCRIPTION_MAX_LENGTH,
+ WEBHOOK_SUBSCRIPTIONS_MAX,
+} from './webhooks'
diff --git a/packages/core/src/webhooks.ts b/packages/core/src/webhooks.ts
new file mode 100644
index 0000000000..b125f44542
--- /dev/null
+++ b/packages/core/src/webhooks.ts
@@ -0,0 +1,22 @@
+/**
+ * The shapes a webhook endpoint subscription may take: `*`, an event name
+ * (`order.placed`), or a name with `*` in place of whole segments (`order.*`,
+ * `*.created`). The server stores nothing else, so a pattern never carries
+ * regexp syntax. Mirrors `Spree::WebhookEndpoint.event_pattern?`.
+ */
+export const WEBHOOK_EVENT_PATTERN = /^(\*|[a-zA-Z0-9_-]+)(\.(\*|[a-zA-Z0-9_-]+))*$/
+
+/** The longest subscription entry an endpoint accepts. */
+export const WEBHOOK_SUBSCRIPTION_MAX_LENGTH = 100
+
+/** The most subscription entries one endpoint accepts. */
+export const WEBHOOK_SUBSCRIPTIONS_MAX = 200
+
+/** Whether a value is an event name or pattern a webhook endpoint accepts. */
+export function isWebhookEventPattern(value: unknown): value is string {
+ return (
+ typeof value === 'string' &&
+ value.length <= WEBHOOK_SUBSCRIPTION_MAX_LENGTH &&
+ WEBHOOK_EVENT_PATTERN.test(value)
+ )
+}
diff --git a/packages/core/tests/webhooks.test.ts b/packages/core/tests/webhooks.test.ts
new file mode 100644
index 0000000000..0cb00bf9a5
--- /dev/null
+++ b/packages/core/tests/webhooks.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest'
+import { isWebhookEventPattern, WEBHOOK_SUBSCRIPTION_MAX_LENGTH } from '../src'
+
+describe('isWebhookEventPattern', () => {
+ it('accepts event names, segment wildcards and the catch-all', () => {
+ for (const value of [
+ '*',
+ 'order.placed',
+ 'order.*',
+ '*.created',
+ 'order.line_item.*',
+ 'my_app.Thing-done',
+ ]) {
+ expect(isWebhookEventPattern(value), value).toBe(true)
+ }
+ })
+
+ it('refuses regexp syntax, partial-segment wildcards, empty segments and non-ASCII letters', () => {
+ for (const value of [
+ 'order.(placed|canceled)',
+ 'order.p*',
+ 'order..placed',
+ '.placed',
+ 'order placed',
+ 'order.placed$',
+ 'order.place\u017f',
+ '',
+ 'a'.repeat(WEBHOOK_SUBSCRIPTION_MAX_LENGTH + 1),
+ 42,
+ null,
+ ]) {
+ expect(isWebhookEventPattern(value), String(value)).toBe(false)
+ }
+ })
+})
diff --git a/packages/dashboard-ui/src/ui/field.tsx b/packages/dashboard-ui/src/ui/field.tsx
index b4a5821c62..02a2d1a506 100644
--- a/packages/dashboard-ui/src/ui/field.tsx
+++ b/packages/dashboard-ui/src/ui/field.tsx
@@ -186,9 +186,20 @@ function FieldError({
return null
}
- const uniqueErrors = [...new Map(errors.map((error) => [error?.message, error])).values()]
+ // `filter` also closes the holes react-hook-form leaves in a per-item
+ // error array (`[ <empty>, { message } ]`), which `map` would keep and
+ // `new Map` would choke on.
+ const uniqueErrors = [
+ ...new Map(
+ errors.filter((error) => error?.message).map((error) => [error?.message, error]),
+ ).values(),
+ ]
+
+ if (!uniqueErrors.length) {
+ return null
+ }
- if (uniqueErrors?.length == 1) {
+ if (uniqueErrors.length == 1) {
return uniqueErrors[0]?.message
}
diff --git a/packages/dashboard/e2e/webhooks.spec.ts b/packages/dashboard/e2e/webhooks.spec.ts
index d0454dd757..c44ee0b7fd 100644
--- a/packages/dashboard/e2e/webhooks.spec.ts
+++ b/packages/dashboard/e2e/webhooks.spec.ts
@@ -158,6 +158,26 @@ test.describe('webhooks', () => {
})
})
+ test('refuses a custom event that is not an event name or pattern', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, WEBHOOKS_PATH(creds.store_id), CTA)
+
+ await page.getByRole('button', { name: CTA }).click()
+ await expect(page.getByRole('heading', { name: /add webhook endpoint/i })).toBeVisible()
+
+ const customInput = page.getByPlaceholder('custom.event_name')
+ await customInput.fill('order.(placed|canceled)')
+ await customInput.press('Enter')
+ await expect(page.getByText(/use event names, or patterns/i)).toBeVisible()
+ await expect(page.getByRole('button', { name: /order\.\(placed\|canceled\)/ })).toHaveCount(0)
+
+ await customInput.fill('order.*')
+ await customInput.press('Enter')
+ // A custom entry renders as a badge whose only control is its remove button.
+ await expect(page.getByRole('button', { name: /order\.\*/ })).toBeVisible()
+ await expect(page.getByText(/use event names, or patterns/i)).toHaveCount(0)
+ })
+
test('deletes an endpoint via the row confirm dialog', async ({ page }) => {
const creds = await login(page)
await gotoIndex(page, WEBHOOKS_PATH(creds.store_id), CTA)
diff --git a/packages/dashboard/src/components/spree/webhook-endpoint-form.tsx b/packages/dashboard/src/components/spree/webhook-endpoint-form.tsx
index ef5d70f53d..bfc690166d 100644
--- a/packages/dashboard/src/components/spree/webhook-endpoint-form.tsx
+++ b/packages/dashboard/src/components/spree/webhook-endpoint-form.tsx
@@ -1,3 +1,4 @@
+import { isWebhookEventPattern } from '@spree/core'
import {
Alert,
AlertAction,
@@ -98,6 +99,11 @@ export function WebhookEndpointFormFields({
control={form.control}
render={({ field }) => <EventPicker value={field.value} onChange={field.onChange} />}
/>
+ <FieldError
+ errors={
+ Array.isArray(errors.subscriptions) ? errors.subscriptions : [errors.subscriptions]
+ }
+ />
</Field>
</>
)
@@ -106,6 +112,7 @@ export function WebhookEndpointFormFields({
function EventPicker({ value, onChange }: { value: string[]; onChange: (next: string[]) => void }) {
const { t } = useTranslation()
const [customEvent, setCustomEvent] = useState('')
+ const [customEventInvalid, setCustomEventInvalid] = useState(false)
const { data: catalog, isPending, isError, refetch } = useWebhookEventCatalog()
const events = catalog?.data ?? []
const subscribed = new Set(value)
@@ -129,8 +136,13 @@ function EventPicker({ value, onChange }: { value: string[]; onChange: (next: st
function addCustom() {
const trimmed = customEvent.trim()
if (!trimmed || value.includes(trimmed)) return
+ if (!isWebhookEventPattern(trimmed)) {
+ setCustomEventInvalid(true)
+ return
+ }
onChange([...value, trimmed])
setCustomEvent('')
+ setCustomEventInvalid(false)
}
return (
@@ -217,22 +229,31 @@ function EventPicker({ value, onChange }: { value: string[]; onChange: (next: st
)}
</div>
- <div className="flex items-center gap-2 border-t border-border p-3">
- <Input
- placeholder={t('admin.pages.settings.webhooks.events_custom_input_placeholder')}
- value={customEvent}
- onChange={(e) => setCustomEvent(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault()
- addCustom()
- }
- }}
- className="font-mono text-xs"
- />
- <Button type="button" variant="outline" size="sm" onClick={addCustom}>
- {t('admin.actions.add')}
- </Button>
+ <div className="flex flex-col gap-2 border-t border-border p-3">
+ <div className="flex items-center gap-2">
+ <Input
+ placeholder={t('admin.pages.settings.webhooks.events_custom_input_placeholder')}
+ value={customEvent}
+ aria-invalid={customEventInvalid || undefined}
+ onChange={(e) => {
+ setCustomEvent(e.target.value)
+ setCustomEventInvalid(false)
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault()
+ addCustom()
+ }
+ }}
+ className="font-mono text-xs"
+ />
+ <Button type="button" variant="outline" size="sm" onClick={addCustom}>
+ {t('admin.actions.add')}
+ </Button>
+ </div>
+ {customEventInvalid && (
+ <FieldError>{t('admin.fields.webhook_endpoint.subscriptions.invalid')}</FieldError>
+ )}
</div>
</div>
)
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index f7651a4f8e..29fb885616 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -2580,7 +2580,9 @@
},
"subscriptions": {
"help": "اختر الأحداث التي تُطلق Webhook. لا تختر شيئًا لاستقبال كل حدث.",
- "label": "Events"
+ "invalid": "استخدم أسماء الأحداث أو أنماطًا تحل فيها * محل جزء من الاسم، مثل order.* أو *.created.",
+ "label": "Events",
+ "too_many": "يمكن اختيار {{count}} حدثًا على الأكثر."
},
"url": {
"label": "Destination URL",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index c51238cfbf..75db248dce 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -2562,7 +2562,9 @@
},
"subscriptions": {
"help": "Wählen Sie aus, welche Ereignisse einen Webhook auslösen sollen. Wählen Sie nichts aus, um jedes Ereignis zu empfangen.",
- "label": "Ereignisse"
+ "invalid": "Verwenden Sie Ereignisnamen oder Muster mit * anstelle eines Segments, z. B. order.* oder *.created.",
+ "label": "Ereignisse",
+ "too_many": "Es sind höchstens {{count}} Ereignisse möglich."
},
"url": {
"label": "Ziel-URL",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 6c52165784..da399a02dc 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -2562,7 +2562,9 @@
},
"subscriptions": {
"help": "Select which events should trigger a webhook. Choose nothing to receive every event.",
- "label": "Events"
+ "invalid": "Use event names, or patterns with * in place of a segment, such as order.* or *.created.",
+ "label": "Events",
+ "too_many": "Can hold at most {{count}} events."
},
"url": {
"label": "Destination URL",
diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.json
index ea2296fefa..b23b4b691a 100644
--- a/packages/dashboard/src/locales/es.json
+++ b/packages/dashboard/src/locales/es.json
@@ -2473,7 +2473,9 @@
},
"subscriptions": {
"help": "Elegí qué eventos deben disparar un webhook. No elijas nada para recibir todos los eventos.",
- "label": "Eventos"
+ "invalid": "Usá nombres de eventos o patrones con * en lugar de un segmento, como order.* o *.created.",
+ "label": "Eventos",
+ "too_many": "Admite como máximo {{count}} eventos."
},
"url": {
"label": "URL de destino",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index e96d0b8df1..5bbcb74e08 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -2562,7 +2562,9 @@
},
"subscriptions": {
"help": "Sélectionnez les événements qui doivent déclencher un webhook. Ne choisissez rien pour recevoir tous les événements.",
- "label": "Événements"
+ "invalid": "Utilisez des noms d'événements ou des motifs avec * à la place d'un segment, comme order.* ou *.created.",
+ "label": "Événements",
+ "too_many": "Au plus {{count}} événements sont acceptés."
},
"url": {
"label": "URL de destination",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 0b5c7e818e..e25a88d9c8 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -2580,7 +2580,9 @@
},
"subscriptions": {
"help": "Wybierz, które zdarzenia mają wyzwalać webhook. Nie wybieraj nic, aby otrzymywać każde zdarzenie.",
- "label": "Zdarzenia"
+ "invalid": "Użyj nazw zdarzeń lub wzorców z * w miejscu segmentu, np. order.* lub *.created.",
+ "label": "Zdarzenia",
+ "too_many": "Można wybrać najwyżej {{count}} zdarzeń."
},
"url": {
"label": "Docelowy adres URL",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index b3d18dbbf1..4de132d3c7 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -2557,7 +2557,9 @@
},
"subscriptions": {
"help": "选择哪些事件应触发 Webhook。不选择任何事件则接收所有事件。",
- "label": "事件"
+ "invalid": "使用事件名称,或以 * 代替某一段的模式,例如 order.* 或 *.created。",
+ "label": "事件",
+ "too_many": "最多可选择 {{count}} 个事件。"
},
"url": {
"label": "目标 URL",
diff --git a/packages/dashboard/src/schemas/webhook-endpoint.ts b/packages/dashboard/src/schemas/webhook-endpoint.ts
index 0715cd7893..528a326d43 100644
--- a/packages/dashboard/src/schemas/webhook-endpoint.ts
+++ b/packages/dashboard/src/schemas/webhook-endpoint.ts
@@ -1,6 +1,14 @@
+import {
+ WEBHOOK_EVENT_PATTERN,
+ WEBHOOK_SUBSCRIPTION_MAX_LENGTH,
+ WEBHOOK_SUBSCRIPTIONS_MAX,
+} from '@spree/core'
+import { i18n } from '@spree/dashboard-core'
import { requiredMessage } from '@spree/dashboard-ui'
import { z } from 'zod/v4'
+const invalidSubscription = () => i18n.t('admin.fields.webhook_endpoint.subscriptions.invalid')
+
export const webhookEndpointFormSchema = z.object({
name: z.string().trim().optional().nullable(),
url: z
@@ -10,7 +18,20 @@ export const webhookEndpointFormSchema = z.object({
active: z.boolean(),
// Empty array == subscribe to every event (the model treats `[]` and `['*']`
// the same). The picker emits an empty array when nothing is selected.
- subscriptions: z.array(z.string().min(1)),
+ subscriptions: z
+ .array(
+ z
+ .string()
+ .min(1, { error: invalidSubscription })
+ .max(WEBHOOK_SUBSCRIPTION_MAX_LENGTH, { error: invalidSubscription })
+ .regex(WEBHOOK_EVENT_PATTERN, { error: invalidSubscription }),
+ )
+ .max(WEBHOOK_SUBSCRIPTIONS_MAX, {
+ error: () =>
+ i18n.t('admin.fields.webhook_endpoint.subscriptions.too_many', {
+ count: WEBHOOK_SUBSCRIPTIONS_MAX,
+ }),
+ }),
})
export type WebhookEndpointFormValues = z.infer<typeof webhookEndpointFormSchema>
diff --git a/spree/api/app/controllers/spree/api/v3/admin/webhook_endpoints_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/webhook_endpoints_controller.rb
index 414199a1e5..54dffb0fc9 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/webhook_endpoints_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/webhook_endpoints_controller.rb
@@ -21,7 +21,7 @@ module Spree
description: 'Defaults to true on create. Prefer the disable and enable endpoints to pause one.'
body.attribute :subscriptions, :array, of: :string,
example: %w[order.placed order.canceled],
- description: 'Event names this endpoint receives. An empty list or `["*"]` subscribes to every event; otherwise list exact names (`order.completed`) or patterns (`order.*`).'
+ description: 'Event names this endpoint receives. An empty list or `["*"]` subscribes to every event; otherwise list exact names (`order.completed`) or patterns with `*` in place of a segment (`order.*`, `*.created`). At most 200 entries of up to 100 characters.'
end
request_params 'WebhookEndpointDisableParams', action: :disable do |body|
@@ -112,8 +112,11 @@ module Spree
)
end
+ # Checked after the model's normalization, so what the gate sees is
+ # exactly what would be stored.
def requested_credential_events
- Spree::Events.catalog.credential_events(Array(permitted_params[:subscriptions]))
+ subscriptions = Spree::WebhookEndpoint.normalize_value_for(:subscriptions, permitted_params[:subscriptions])
+ Spree::Events.catalog.credential_events(subscriptions)
end
def repointed_credential_events
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/webhook_endpoints_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/webhook_endpoints_controller_spec.rb
index a6da56e623..d63f152182 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/webhook_endpoints_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/webhook_endpoints_controller_spec.rb
@@ -87,6 +87,15 @@ RSpec.describe Spree::Api::V3::Admin::WebhookEndpointsController, type: :control
expect { subject }.not_to change(Spree::WebhookEndpoint, :count)
expect(response).to have_http_status(:forbidden)
end
+
+ context 'when the event name is padded with whitespace the model strips' do
+ let(:params) { { url: 'https://example.com/hook', subscriptions: [' customer.password_reset_requested '] } }
+
+ it 'is forbidden' do
+ expect { subject }.not_to change(Spree::WebhookEndpoint, :count)
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
end
context 'with permission to manage customers' do
@@ -108,6 +117,16 @@ RSpec.describe Spree::Api::V3::Admin::WebhookEndpointsController, type: :control
expect(json_response['error']['code']).to eq('validation_error')
end
end
+
+ context 'when a subscription is not an event name or pattern' do
+ let(:params) { { url: 'https://example.com/hook', subscriptions: ['order.(placed|canceled)'] } }
+
+ it 'returns a validation error on subscriptions' do
+ subject
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['details']).to have_key('subscriptions')
+ end
+ end
end
describe 'PATCH #update' do
@@ -147,6 +166,18 @@ RSpec.describe Spree::Api::V3::Admin::WebhookEndpointsController, type: :control
expect(response).to have_http_status(:ok)
end
end
+
+ context 'subscribing to customer password resets with a whitespace-padded name' do
+ let(:caller_key) { create(:api_key, :secret, store: store, scopes: %w[write_webhooks]) }
+ let(:headers) { { 'x-spree-api-key' => caller_key.plaintext_token } }
+
+ it 'is forbidden with only the webhooks permission' do
+ patch :update, params: { id: endpoint.prefixed_id, subscriptions: [' customer.password_reset_requested '] }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ expect(endpoint.reload.subscriptions).not_to include('customer.password_reset_requested')
+ end
+ end
end
describe 'DELETE #destroy' do
diff --git a/spree/core/app/models/spree/event.rb b/spree/core/app/models/spree/event.rb
index 7c787b873d..9cd6a46ac4 100644
--- a/spree/core/app/models/spree/event.rb
+++ b/spree/core/app/models/spree/event.rb
@@ -86,14 +86,29 @@ module Spree
# @return [Boolean]
def self.matches?(event_name, pattern)
return true if pattern == '*'
+ return event_name == pattern unless pattern.include?('*')
- if pattern.include?('*')
- regex = Regexp.new("^#{Regexp.escape(pattern).gsub('\*', '.*')}$")
- event_name.match?(regex)
- else
- event_name == pattern
+ wildcard_match?(event_name, pattern)
+ end
+
+ # `*` stands for any run of characters, as in a shell glob. The comparison
+ # is plain string searching so a pattern taken from a merchant never
+ # reaches the regexp engine, which has had memory bugs in pattern parsing.
+ def self.wildcard_match?(event_name, pattern)
+ head, *middle, tail = pattern.split('*', -1)
+ return false unless event_name.start_with?(head) && event_name.end_with?(tail)
+ return false if event_name.length < head.length + tail.length
+
+ position = head.length
+ limit = event_name.length - tail.length
+ middle.all? do |segment|
+ found = event_name.index(segment, position)
+ next false if found.nil? || found + segment.length > limit
+
+ position = found + segment.length
end
end
+ private_class_method :wildcard_match?
alias_method :to_h, :attributes
diff --git a/spree/core/app/models/spree/webhook_endpoint.rb b/spree/core/app/models/spree/webhook_endpoint.rb
index fd4d23fc74..dc053855bd 100644
--- a/spree/core/app/models/spree/webhook_endpoint.rb
+++ b/spree/core/app/models/spree/webhook_endpoint.rb
@@ -20,6 +20,10 @@ module Spree
validates :url, format: { with: URI::DEFAULT_PARSER.make_regexp(%w[http https]), message: :invalid_url }
validates :active, inclusion: { in: [true, false] }
validate :url_must_not_resolve_to_private_ip, if: -> { !Rails.env.development? && url.present? && url_changed? }
+ validate :subscriptions_must_be_event_patterns, if: :will_save_change_to_subscriptions?
+
+ attribute :subscriptions, default: -> { [] }
+ normalizes :subscriptions, apply_to_nil: true, with: ->(value) { Array(value).map { |entry| entry.to_s.strip }.reject(&:empty?).uniq }
before_create :generate_secret_key
after_create { @reveal_secret_in_response = true }
@@ -83,6 +87,23 @@ module Spree
# Number of consecutive failed deliveries before auto-disabling
AUTO_DISABLE_THRESHOLD = 15
+ MAX_SUBSCRIPTIONS = 200
+ MAX_SUBSCRIPTION_LENGTH = 100
+ SUBSCRIPTION_SEGMENT = /\A[a-zA-Z0-9_-]+\z/
+
+ # Whether +value+ is a shape `subscriptions` accepts: `*`, an event name,
+ # or a name with `*` in place of whole segments (`order.*`, `*.created`).
+ # Anything else — regexp syntax above all — is refused before it is
+ # stored, so the matcher only ever sees names and segment wildcards.
+ #
+ # @param value [Object]
+ # @return [Boolean]
+ def self.event_pattern?(value)
+ return false unless value.is_a?(String) && value.length.between?(1, MAX_SUBSCRIPTION_LENGTH)
+
+ value.split('.', -1).all? { |segment| segment == '*' || segment.match?(SUBSCRIPTION_SEGMENT) }
+ end
+
# Check if this endpoint is subscribed to a specific event.
#
# Events whose payload carries a live credential (a password reset token)
@@ -93,16 +114,9 @@ module Spree
# @return [Boolean]
def subscribed_to?(event_name)
return subscriptions.to_a.include?(event_name) if Spree::Events.catalog.credential?(event_name)
- return true if subscriptions.blank? || subscriptions.include?('*')
-
- subscriptions.any? do |subscription|
- if subscription.include?('*')
- pattern = Regexp.escape(subscription).gsub('\*', '.*')
- event_name.match?(Regexp.new("^#{pattern}$"))
- else
- subscription == event_name
- end
- end
+ return true if subscriptions.blank?
+
+ subscriptions.any? { |subscription| Spree::Event.matches?(event_name, subscription) }
end
# The credential-carrying events this endpoint names.
@@ -191,6 +205,16 @@ module Spree
self.secret_key ||= SecureRandom.hex(32)
end
+ def subscriptions_must_be_event_patterns
+ entries = subscriptions.to_a
+ errors.add(:subscriptions, :too_many, count: MAX_SUBSCRIPTIONS) if entries.size > MAX_SUBSCRIPTIONS
+
+ rejected = entries.reject { |entry| self.class.event_pattern?(entry) }
+ return if rejected.empty?
+
+ errors.add(:subscriptions, :invalid_pattern, entries: rejected.first(5).map { |entry| entry.truncate(40) }.join(', '))
+ end
+
def clear_disabled_state_when_reactivated
return unless will_save_change_to_active? && active
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 811e261499..8e3993f9a3 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -463,6 +463,9 @@ en:
required_for_carton_purchase_unit: is required when the purchase unit is cartons
spree/webhook_endpoint:
attributes:
+ subscriptions:
+ invalid_pattern: 'must hold event names or patterns such as order.* or *.created (rejected: %{entries})'
+ too_many: can hold at most %{count} entries
url:
internal_address_not_allowed: must not point to an internal or private network address
invalid_url: must be a valid http or https URL
diff --git a/spree/core/spec/models/spree/event_spec.rb b/spree/core/spec/models/spree/event_spec.rb
index a48a9e3927..0e82482eb3 100644
--- a/spree/core/spec/models/spree/event_spec.rb
+++ b/spree/core/spec/models/spree/event_spec.rb
@@ -147,6 +147,21 @@ RSpec.describe Spree::Event do
expect(described_class.matches?('order.line_item.update', 'order.line_item.*')).to be true
expect(described_class.matches?('order.line_item.update', 'order.*')).to be true
end
+
+ it 'matches a wildcard anywhere in the pattern' do
+ expect(described_class.matches?('order.created', '*.created')).to be true
+ expect(described_class.matches?('order.line_item.created', '*.created')).to be true
+ expect(described_class.matches?('order.updated', '*.created')).to be false
+ expect(described_class.matches?('order.line_item.created', 'order.*.created')).to be true
+ expect(described_class.matches?('order.created', 'order.*.created')).to be false
+ end
+
+ it 'treats regexp syntax in a pattern as literal text' do
+ expect(described_class.matches?('order.placed', 'order.(placed|canceled)')).to be false
+ expect(described_class.matches?('order.placed', 'order.p.aced')).to be false
+ expect(described_class.matches?('order.placed', '.*')).to be false
+ expect(described_class.matches?('order.placed', 'order.placed$')).to be false
+ end
end
describe '#attributes' do
diff --git a/spree/core/spec/models/spree/webhook_endpoint_spec.rb b/spree/core/spec/models/spree/webhook_endpoint_spec.rb
index 0b5c979213..3c3c8c817e 100644
--- a/spree/core/spec/models/spree/webhook_endpoint_spec.rb
+++ b/spree/core/spec/models/spree/webhook_endpoint_spec.rb
@@ -7,6 +7,57 @@ describe Spree::WebhookEndpoint, type: :model do
let(:webhook_endpoint) { build(:webhook_endpoint, store: store) }
describe 'validations' do
+ describe 'subscriptions' do
+ it 'accepts event names, segment wildcards and the catch-all' do
+ webhook_endpoint.subscriptions = ['*', 'order.placed', 'order.*', '*.created', 'order.line_item.*', 'my_app.Thing-done']
+ expect(webhook_endpoint).to be_valid
+ end
+
+ it 'rejects anything that is not an event name or a segment wildcard' do
+ ['order.(placed|canceled)', 'order.p*', 'order..placed', '.placed', 'order placed', 'order.placed$', "order.\n*"].each do |entry|
+ webhook_endpoint.subscriptions = [entry]
+ expect(webhook_endpoint).not_to be_valid, "expected #{entry.inspect} to be refused"
+ expect(webhook_endpoint.errors.details[:subscriptions]).to include(error: :invalid_pattern, entries: entry.truncate(40))
+ end
+ end
+
+ it 'caps the length of an entry and the number of entries' do
+ webhook_endpoint.subscriptions = ['a' * (described_class::MAX_SUBSCRIPTION_LENGTH + 1)]
+ expect(webhook_endpoint).not_to be_valid
+
+ webhook_endpoint.subscriptions = Array.new(described_class::MAX_SUBSCRIPTIONS + 1) { |index| "event_#{index}.created" } + ['order.pl*']
+ expect(webhook_endpoint).not_to be_valid
+ expect(webhook_endpoint.errors.details[:subscriptions]).to include(
+ { error: :too_many, count: described_class::MAX_SUBSCRIPTIONS },
+ { error: :invalid_pattern, entries: 'order.pl*' },
+ )
+ end
+
+ it 'names every rejected entry, not only the first' do
+ webhook_endpoint.subscriptions = ['order.placed', 'order.pl*', 'order.(a|b)']
+ expect(webhook_endpoint).not_to be_valid
+ expect(webhook_endpoint.errors[:subscriptions].first).to include('order.pl*, order.(a|b)')
+ end
+
+ it 'accepts only ASCII letters, so the dashboard and the matcher agree' do
+ webhook_endpoint.subscriptions = ['order.placeſ']
+ expect(webhook_endpoint).not_to be_valid
+ end
+
+ it 'strips, drops blanks and deduplicates on assignment' do
+ webhook_endpoint.subscriptions = [' order.placed ', '', 'order.placed', nil]
+ expect(webhook_endpoint.subscriptions).to eq(['order.placed'])
+ end
+
+ it 'stores an empty list when none is given' do
+ endpoint = described_class.create!(store: store, url: 'https://example.com/webhooks/unassigned')
+ expect(endpoint.reload.subscriptions).to eq([])
+
+ endpoint.update!(subscriptions: nil)
+ expect(endpoint.reload.subscriptions).to eq([])
+ end
+ end
+
it 'requires a url unique within the store' do
store = create(:store)
create(:webhook_endpoint, url: 'https://example.com/hook', store: store)
@@ -206,6 +257,16 @@ describe Spree::WebhookEndpoint, type: :model do
expect(endpoint.subscribed_to?('shipment.shipped')).to be false
end
end
+
+ context 'with a leading wildcard' do
+ let(:endpoint) { build(:webhook_endpoint, subscriptions: ['*.created']) }
+
+ it 'matches on the trailing segment' do
+ expect(endpoint.subscribed_to?('order.created')).to be true
+ expect(endpoint.subscribed_to?('product.created')).to be true
+ expect(endpoint.subscribed_to?('order.updated')).to be false
+ end
+ end
end
describe '#subscribed_events' do