diff --git a/.changeset/33263-webhook-remedies-exact-address.md b/.changeset/33263-webhook-remedies-exact-address.md new file mode 100644 index 00000000000..1d8d0255881 --- /dev/null +++ b/.changeset/33263-webhook-remedies-exact-address.md @@ -0,0 +1,29 @@ +--- +'@objectstack/plugin-webhooks': patch +'@objectstack/runtime': patch +'@objectstack/plugin-security': patch +--- + +fix(plugin-webhooks, runtime): declared-webhook remedies name each holder's exact address, and a name refused whole is refused at every address naming both holders + +Clause-②: no +Metadata-protocol: none + +Remedy text and refusals for declared webhooks (ADR-0150 D2/D3/D5/D8): + +| Where | FROM | TO | +|:---|:---|:---| +| Name guard (`sys_webhook` create or rename onto a declared name) | names `POST /api/v1/security/_activation/webhook/NS/NAME` per holder, which answers `409` for two co-owners of one namespace and does not exist for a package that declares no namespace | names `POST /api/v1/security/_activation/webhook/NAME?package=PACKAGE` per holder, which switches exactly that holder | +| Redelivery veto, switched-off declared webhook | `switch it on (POST .../webhook/NS/NAME ...)` | `switch it on (POST .../webhook/NAME?package=PACKAGE ...)` | +| Dispatcher warning, a declared webhook withheld by a `sys_webhook` row | namespace address per holder | `?package=PACKAGE` address per holder | +| Dispatcher warning, a row naming no package under two holders | `.../webhook//NAME` | `.../webhook/NAME?package=PACKAGE`, as the departed-package warning already said | +| Metadata service lists the environment's declaration beside a package's (no registry item): bare refusal sentence | "Nothing picks one of them: address it by its package." | says neither declaration is dispatched and no address switches one, names both holders, and says to remove or rename declarations | +| Same state, `POST .../webhook/NAME?package=PACKAGE` and `POST .../webhook/NS/NAME` | `404` "no enabled package declares the name" | `409 RESOURCE_CONFLICT`, the refusal above, `candidates` naming the environment and the package; nothing written | +| Same state, name guard | names a `` placeholder address | says no declaration of the name is dispatched and quotes the refusal | +| Same state, redelivery of a `declared:PACKAGE/NAME` delivery | "the package is disabled ... Enable the package" | refused with the refusal, naming both holders | +| `?package=` or namespace address when the reader serves no slot and the bare read fails | `404` | `503 SERVICE_UNAVAILABLE`, nothing written | +| Upgrade impact report, withheld-webhook line and `packageDisabled` doc | a disabled package's address "answers 409" | refuses the switch: `404` while the package is the name's only holder, `409` naming the other holders while another package declares it | + +A name that one package, or two packages each once, declare through the metadata service is unchanged: each served holder is switched at its own `?package=` address. A disabled sole holder still answers `404` at its address. + +No action is needed. Operators who scripted the namespace address keep it working where it worked; the `?package=PACKAGE` address the messages now name works for every package holder. diff --git a/content/docs/automation/webhooks.mdx b/content/docs/automation/webhooks.mdx index 19cc23dbf21..b94bd58b5c3 100644 --- a/content/docs/automation/webhooks.mdx +++ b/content/docs/automation/webhooks.mdx @@ -97,7 +97,10 @@ A webhook reaches the dispatcher one of two ways: cannot tell apart (two packages sharing one namespace, or a package that declares no namespace beside another holder) are each switched by the exact qualifier, `POST /api/v1/security/_activation/webhook/:name?package=`. - It writes that holder's + An activation row naming a package that no longer declares the name switches + no remaining holder (ADR-0150 D8), so to keep the webhook off, switch each + holder off at `POST /api/v1/security/_activation/webhook/:name?package=`. + Each switch writes that holder's own `sys_metadata_activation` row of type `webhook` and overrides the declared `isActive` in either direction (ADR-0131 D6, regime C — the door, its authority tiers and its refusals are diff --git a/packages/plugins/plugin-security/src/upgrade-impact-report.test.ts b/packages/plugins/plugin-security/src/upgrade-impact-report.test.ts index 7a498d05b49..12358e57b93 100644 --- a/packages/plugins/plugin-security/src/upgrade-impact-report.test.ts +++ b/packages/plugins/plugin-security/src/upgrade-impact-report.test.ts @@ -437,12 +437,17 @@ describe('webhook: a sys_webhook row holding a declared name', () => { }); const r = await boot(d, 'walled'); expect(r.report.withheldWebhooks.map((w) => w.packageId).sort()).toEqual([OTHER_VENDOR, VENDOR].sort()); - // [#33016 S2] The disabled holder's address answers 409 until it is - // enabled again: its finding says so, and the line says to enable first. + // [#33016 S2] The disabled holder's address refuses the switch until it + // is enabled again: its finding says so, and the line says to enable + // first. [#33263, record nit N5] The refusal is 404 for a sole holder + // and 409 beside another (the door's own pins in runtime's + // `catalog-activation-door.test.ts`); the line said 409 for both. expect(r.report.withheldWebhooks.map((w) => [w.packageId, w.packageDisabled ?? false]).sort()) .toEqual([[order[0], false], [order[1], true]].sort()); const line = errorLines(r).find((m) => m.includes('sys_webhook row(s) hold the name of a webhook')) ?? ''; expect(line).toContain('A finding marked packageDisabled names a disabled package'); + expect(line).toContain("(404 while the package is the name's only holder, 409 naming the other holders while another package declares it too)"); + expect(line).not.toContain('answers 409 until'); expect(line).toContain('enable the package first, then switch it there'); }); } diff --git a/packages/plugins/plugin-security/src/upgrade-impact-report.ts b/packages/plugins/plugin-security/src/upgrade-impact-report.ts index f4120029dbc..aab77590926 100644 --- a/packages/plugins/plugin-security/src/upgrade-impact-report.ts +++ b/packages/plugins/plugin-security/src/upgrade-impact-report.ts @@ -281,7 +281,10 @@ export interface WithheldDeclaredWebhook { organizationId: string | null; /** * [#33016] Set when that package is disabled: it holds nothing for the - * activation door until it is enabled again, so its address answers `409`. + * activation door until it is enabled again, so its address refuses the + * switch — `404` while it is the name's only holder, `409` naming the + * holders the door serves while another package declares the name too + * (#33263, record nit N5: this said `409` for both). */ packageDisabled?: true; } @@ -866,7 +869,9 @@ const CATEGORY_LINES: Record string> = { 'delete the row to let the declaration answer; to keep the row as well, rename it, and switch the declared ' + `one off if it must not fire (${WEBHOOK_SWITCH_DOOR}, with { "enabled": false }; the package is the one the ` + 'finding names). A finding marked packageDisabled names a disabled package: it does not fire now, and that ' + - 'address answers 409 until the package is enabled again, so enable the package first, then switch it there.', + 'address refuses the switch until the package is enabled again (404 while the package is the name\'s only ' + + 'holder, 409 naming the other holders while another package declares it too), so enable the package first, ' + + 'then switch it there.', overlayOrphans: (n) => `[security] upgrade impact: ${n} customization(s) of a view, dashboard, report, translation or email template ` + 'are bound to a package that no longer ships the item, so each is served as an item of its own beside ' + diff --git a/packages/plugins/plugin-webhooks/src/auto-enqueuer.ts b/packages/plugins/plugin-webhooks/src/auto-enqueuer.ts index 42da3364088..24910c7f431 100644 --- a/packages/plugins/plugin-webhooks/src/auto-enqueuer.ts +++ b/packages/plugins/plugin-webhooks/src/auto-enqueuer.ts @@ -593,7 +593,7 @@ export class AutoEnqueuer { if (heldByRow.has(name)) { this.reportDeclarationWithheld( name, - declared.filter((s) => s.webhook.name === name).map((s) => declaredWebhookActivationPath(name, s.namespace)), + declared.filter((s) => s.webhook.name === name).map((s) => declaredWebhookActivationPath(name, s.packageId)), ); continue; } diff --git a/packages/plugins/plugin-webhooks/src/declared-webhooks.test.ts b/packages/plugins/plugin-webhooks/src/declared-webhooks.test.ts index 296d810fb07..4ac72790f84 100644 --- a/packages/plugins/plugin-webhooks/src/declared-webhooks.test.ts +++ b/packages/plugins/plugin-webhooks/src/declared-webhooks.test.ts @@ -33,6 +33,7 @@ import { WEBHOOK_ACTIVATION_TYPE, bindDeclaredWebhookNameGuard, declaredWebhookRefId, + wholeNameRefusal, } from './declared-webhooks.js'; import { SchemaRegistry } from '@objectstack/objectql'; import { createWebhookRedeliverGuard } from './redeliver-guard.js'; @@ -772,6 +773,9 @@ describe('declared webhooks — one declaration per (package, name) slot (ADR-01 expect(said).toHaveLength(1); expect(said[0][0]).toContain(`"${A}"`); expect(said[0][0]).toContain(`"${B}"`); + // [#33263] Each holder's exact address, as the departed-row line says it. + expect(said[0][0]).toContain('POST /api/v1/security/_activation/webhook/task_changed?package=PACKAGE.'); + expect(said[0][0]).not.toContain('namespace>'); const shippedOff = engineOver( registryShipping([[A, ALPHA], [B, declaredWebhook({ url: 'https://hooks.example/beta', isActive: false })]]), @@ -1042,25 +1046,54 @@ describe('declared webhooks — one declaration per (package, name) slot (ADR-01 new DeclaredWebhookSource(engineOver(registry), undefined)); const err = await hooks.beforeInsert({ input: { data: { name: T } }, session: {} }).then(() => undefined, (e: unknown) => e); expect(err).toBeInstanceOf(DeclaredWebhookNameConflictError); - expect((err as Error).message).toContain(`POST /api/v1/security/_activation/webhook/alpha/${T} with`); - expect((err as Error).message).not.toContain('/beta/'); + expect((err as Error).message).toContain(`POST /api/v1/security/_activation/webhook/${T}?package=${A} with`); + expect((err as Error).message).not.toContain(B); }); }); - // [#31699 round 2, R2-D] A remedy names the slot's namespace address. - it('the remedies name the namespace address: the name guard each holder\'s, the redelivery veto the slot\'s', async () => { + // [#31699 round 2, R2-D; #33263] A remedy names the slot's exact address, + // `?package=PKG`: it named the namespace address, which refuses two + // co-owners of one namespace (the pin below). + it('[FROM namespace address TO ?package=] the remedies name each holder\'s exact address: the name guard each holder\'s, the redelivery veto the slot\'s', async () => { const hooks: Record Promise> = {}; bindDeclaredWebhookNameGuard({ registerHook: (event, handler) => { hooks[event] = handler; } }, new DeclaredWebhookSource(twoHolders(), undefined)); const conflict = await hooks.beforeInsert({ input: { data: { name: 'task_changed' } }, session: {} }) .then(() => undefined, (e: unknown) => (e as Error).message); - expect(conflict).toContain('switch the declared ones off (POST /api/v1/security/_activation/webhook/alpha/task_changed, ' - + 'POST /api/v1/security/_activation/webhook/beta/task_changed, each with { "enabled": false })'); + expect(conflict).toContain(`switch the declared ones off (POST /api/v1/security/_activation/webhook/task_changed?package=${A}, ` + + `POST /api/v1/security/_activation/webhook/task_changed?package=${B}, each with { "enabled": false })`); const engine = twoHolders({ [LEDGER]: [slotRow(A, false)] }); const guard = createWebhookRedeliverGuard(engine as any, 'sys_webhook', new DeclaredWebhookSource(engine, undefined)); expect(await guard({ source: 'webhook', refId: declaredWebhookRefId('task_changed', A) })) - .toContain('(POST /api/v1/security/_activation/webhook/alpha/task_changed with { "enabled": true })'); + .toContain(`(POST /api/v1/security/_activation/webhook/task_changed?package=${A} with { "enabled": true })`); + }); + + // [#33263] Two co-owners of one namespace: the namespace address refuses + // both (`catalog-activation-door.test.ts`), so each remedy names the + // holder's own exact address, never the shared namespace's. + it('two co-owners of one namespace: the name guard names each holder\'s exact address, the redelivery veto its slot\'s', async () => { + const registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + for (const id of [A, B]) { + registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: 'shared' } as never, 'code', + undefined, { packageIds: [A, B] }); + registry.registerItem('webhook', { ...(id === A ? ALPHA : BETA) }, 'name' as never, id); + } + const hooks: Record Promise> = {}; + bindDeclaredWebhookNameGuard({ registerHook: (event, handler) => { hooks[event] = handler; } }, + new DeclaredWebhookSource(engineOver(registry), undefined)); + const conflict = await hooks.beforeInsert({ input: { data: { name: 'task_changed' } }, session: {} }) + .then(() => undefined, (e: unknown) => (e as Error).message); + expect(conflict).toContain(`POST /api/v1/security/_activation/webhook/task_changed?package=${A}, ` + + `POST /api/v1/security/_activation/webhook/task_changed?package=${B}, each with`); + expect(conflict).not.toContain('/shared/'); + + const engine = engineOver(registry, { rows: { [LEDGER]: [slotRow(B, false)] } }); + const verdict = await createWebhookRedeliverGuard(engine as any, 'sys_webhook', new DeclaredWebhookSource(engine, undefined))( + { source: 'webhook', refId: declaredWebhookRefId('task_changed', B) }); + expect(verdict).toContain(`(POST /api/v1/security/_activation/webhook/task_changed?package=${B} with { "enabled": true })`); + expect(verdict).not.toContain('/shared/'); }); it('CONTROL — the environment\'s own declaration keeps the bare address in both remedies', async () => { @@ -1077,3 +1110,87 @@ describe('declared webhooks — one declaration per (package, name) slot (ADR-01 .toContain('switch the declared one off (POST /api/v1/security/_activation/webhook/task_changed with { "enabled": false })'); }); }); + +// --------------------------------------------------------------------------- +// 5. A name the metadata service lists for the environment beside a package — +// refused WHOLE, said so at every reader (ADR-0150 D3, #33263) +// --------------------------------------------------------------------------- + +/** + * On a host whose registry holds no webhook, the metadata service lists the + * environment's own declaration beside a package's of the same name. Nothing + * says whether the environment's is that package's customization or a webhook + * of its own, so the name is refused whole: neither is dispatched, and no + * address switches either. BASE: the bare refusal said "address it by its + * package", the door's `?package=` then answered 404 "no enabled package + * declares the name", the name guard named a namespace placeholder and the + * redelivery veto said the package was disabled. Each now says the one true + * thing and names both holders. + */ +describe('declared webhooks — a name the metadata service lists for the environment beside a package (ADR-0150 D3, #33263)', () => { + const PKG = 'com.acme.alpha'; + const T = 'task_changed'; + const listing = (...items: any[]) => ({ list: (type: string) => (type === 'webhook' ? items : []) }); + const envBesidePackage = () => new DeclaredWebhookSource( + newEngine(), + listing(declaredWebhook({ url: 'https://hooks.example/env' }), { ...declaredWebhook({ url: 'https://hooks.example/pkg' }), _packageId: PKG }), + ); + const refusalOf = async (source: DeclaredWebhookSource) => + (await source.declaredWebhookNamed(T).then(() => undefined, (e: unknown) => e) as DeclaredWebhookAmbiguousError).refusal; + + it('[FROM "address it by its package" TO "no address switches one"] the bare refusal names both holders and says neither is dispatched', async () => { + const source = envBesidePackage(); + expect(await source.list()).toEqual([]); + const refusal = await refusalOf(source); + expect(refusal.candidates).toEqual([{ kind: 'environment' }, { kind: 'package', packageId: PKG }]); + expect(refusal.message).toContain('the environment (an item authored in this environment, bound to no package)'); + expect(refusal.message).toContain(`package "${PKG}"`); + expect(refusal.message).toContain('No declaration of it is dispatched, and no address switches one'); + expect(refusal.message).not.toContain('address it by its package'); + expect(await wholeNameRefusal(source, T)).toEqual(refusal); + }); + + it('CONTROL — two packages the metadata service lists once each are served: the bare refusal sends the caller to each package, and no whole refusal stands', async () => { + const source = new DeclaredWebhookSource(newEngine(), listing( + { ...declaredWebhook(), _packageId: PKG }, { ...declaredWebhook(), _packageId: 'com.acme.beta' }, + )); + expect((await source.list()).map((d) => d.packageId)).toEqual([PKG, 'com.acme.beta']); + expect((await refusalOf(source)).message).toContain('address it by its package'); + expect(await wholeNameRefusal(source, T)).toBeUndefined(); + expect(await wholeNameRefusal(source, 'not_declared')).toBeUndefined(); + }); + + it('CONTROL — one holder listing the name twice is refused whole, saying so', async () => { + const source = new DeclaredWebhookSource(newEngine(), listing({ ...declaredWebhook(), _packageId: PKG }, { ...declaredWebhook(), _packageId: PKG })); + const refusal = await refusalOf(source); + expect(refusal.message).toContain('A holder that lists the name twice holds two declarations for one slot'); + expect(refusal.message).not.toContain("the environment's own declaration"); + }); + + it('[FROM namespace placeholder TO the refusal] the name guard refuses the name, saying none is dispatched and naming both holders', async () => { + const hooks: Record Promise> = {}; + bindDeclaredWebhookNameGuard({ registerHook: (event, handler) => { hooks[event] = handler; } }, envBesidePackage()); + const err = await hooks.beforeInsert({ input: { data: { name: T } }, session: {} }).then(() => undefined, (e: unknown) => e); + expect(err).toBeInstanceOf(DeclaredWebhookNameConflictError); + expect(err).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 }); + const message = (err as Error).message; + expect(message).toContain(`No declaration of '${T}' is dispatched, so none needs switching off`); + expect(message).toContain(`package "${PKG}"`); + expect(message).not.toContain('switch the declared'); + expect(message).not.toContain('namespace>'); + }); + + it('[FROM "the package is disabled" TO the refusal] a delivery naming the package is refused with the refusal, never as a disable', async () => { + const engine = newEngine(); + const source = new DeclaredWebhookSource(engine, listing(declaredWebhook(), { ...declaredWebhook(), _packageId: PKG })); + const guard = createWebhookRedeliverGuard(engine as any, 'sys_webhook', source); + const verdict = await guard({ source: 'webhook', refId: declaredWebhookRefId(T, PKG) }); + expect(verdict).toContain(`declared webhook '${T}' is not served, so this delivery is refused`); + expect(verdict).toContain('No declaration of it is dispatched'); + expect(verdict).not.toMatch(/disabled/); + // The environment's own reference names no package: the ambiguity, naming both. + const bare = await guard({ source: 'webhook', refId: declaredWebhookRefId(T) }); + expect(bare).toMatch(/names no package/); + expect(bare).toContain(`package "${PKG}"`); + }); +}); diff --git a/packages/plugins/plugin-webhooks/src/declared-webhooks.ts b/packages/plugins/plugin-webhooks/src/declared-webhooks.ts index bb6b9538045..37cc738d543 100644 --- a/packages/plugins/plugin-webhooks/src/declared-webhooks.ts +++ b/packages/plugins/plugin-webhooks/src/declared-webhooks.ts @@ -58,14 +58,19 @@ * a host whose registry holds no webhook) are slotted by their `_packageId`: * each package's item of a name is its slot, and a name listed twice for one * holder, or for the environment beside a package, is refused the same way, - * never first-picked. + * never first-picked — refused WHOLE (#33263): none of its declarations is + * served, so no address switches one, and the refusal says so and names every + * holder ({@link wholeNameRefusal}); the activation door answers it `409` at + * the bare address and at each holder's own. * * ## The switch: regime C (ADR-0131 D6) * * A declared webhook is read-only. It is switched on or off for the deployment * by one `sys_metadata_activation` row of type {@link WEBHOOK_ACTIVATION_TYPE}, * written through the activation door (`POST /api/v1/security/_activation/ - * webhook/:name`, or `webhook/:ns/:name` for one namespace's), and changed by + * webhook/:name`, `webhook/:name?package=PKG` for exactly one package's — the + * address every remedy here names — or `webhook/:ns/:name` for one + * namespace's), and changed by * a clone under a new name — an organization's own `sys_webhook` row. A * ledger row overrides the declared `isActive` in both directions, so a * webhook shipped inactive is activated by a row with `active: true`. No row @@ -119,6 +124,7 @@ import { WebhookSchema, type WebhookParsed } from '@objectstack/spec/automation'; import { METADATA_ACTIVATION_TABLE } from '@objectstack/core'; import { + describePackageScopedHolder, packageScopedRefusalMessage, resolvePackageScopedName, type PackageScopedHolder, @@ -174,13 +180,16 @@ export function declaredWebhookAddressOfRefId(refId: string): { packageId?: stri } /** - * [ADR-0150 D5, #31699] The activation door's address of one declared - * webhook slot, as a remedy names it: `webhook/NS/NAME` for a package's - * declaration whose namespace is known, which answers whatever else declares - * the name, and the bare `webhook/NAME` for the environment's own. + * [ADR-0150 D2/D5] The activation door's address of one declared webhook + * slot, as a remedy names it: `webhook/NAME?package=PKG` for package + * `packageId`'s declaration — the exact qualifier, which answers that one + * holder whatever else declares the name, two co-owners of one namespace and a + * package that declares no namespace included, where the namespace address + * `webhook/NS/NAME` refuses both — and the bare `webhook/NAME` for the + * environment's own. */ -export function declaredWebhookActivationPath(name: string, namespace?: string): string { - return `/api/v1/security/_activation/${WEBHOOK_ACTIVATION_TYPE}/${namespace ? `${namespace}/` : ''}${name}`; +export function declaredWebhookActivationPath(name: string, packageId?: string): string { + return `/api/v1/security/_activation/${WEBHOOK_ACTIVATION_TYPE}/${name}${packageId ? `?package=${packageId}` : ''}`; } interface Logger { @@ -335,8 +344,18 @@ function listedHolderOf(item: unknown): string | null { return typeof pkg === 'string' && pkg !== '' && pkg !== 'sys_metadata' ? pkg : null; } -/** The refusal of a name no single listed declaration answers, naming every holder. */ -function listedRefusal(name: string, holders: ReadonlyArray): PackageScopedRefusal { +/** + * The refusal of a name no single listed declaration answers, naming every + * holder. `whole` is a name refused WHOLE ({@link slotsOf}): no + * declaration of it is served, so no address switches one, and the sentence + * says so instead of the resolver's "address it by its package", which + * would send the caller to a `?package=` that answers this same refusal. + */ +function listedRefusal( + name: string, + holders: ReadonlyArray, + whole?: { readonly environmentBesidePackage: boolean; readonly listedTwice: boolean }, +): PackageScopedRefusal { const refusal = { status: 'refused' as const, reason: 'ambiguous-in-environment' as const, @@ -345,7 +364,24 @@ function listedRefusal(name: string, holders: ReadonlyArray): Pac callerPackageId: null, candidates: holders.map((h): PackageScopedHolder => (h === null ? { kind: 'environment' } : { kind: 'package', packageId: h })), }; - return { ...refusal, message: packageScopedRefusalMessage(refusal) }; + if (!whole) return { ...refusal, message: packageScopedRefusalMessage(refusal) }; + const why = [ + ...(whole.environmentBesidePackage + ? ["the environment's own declaration beside a package's may be that package's customization or a webhook " + + 'of its own, and nothing on this host says which'] + : []), + ...(whole.listedTwice ? ['a holder that lists the name twice holds two declarations for one slot'] : []), + ].join('; and '); + return { + ...refusal, + message: `The webhook "${name}" is declared, as the metadata service lists it, by ` + + `${holders.length === 1 ? 'one holder' : `${holders.length} holders`}, and no single declaration answers it: ` + + `${refusal.candidates.map(describePackageScopedHolder).join('; ')}. ` + + `${why.charAt(0).toUpperCase()}${why.slice(1)} (ADR-0150 D3). No declaration of it is dispatched, and no ` + + 'address switches one: the bare address and each holder\'s own (?package=PACKAGE) answer this refusal. ' + + 'Remove or rename declarations until each holder lists the name once, and the environment only where no ' + + 'package does.', + }; } /** @@ -389,8 +425,10 @@ function slotsOf( byHolder.set(holder, [...(byHolder.get(holder) ?? []), item]); } const holders = [...byHolder.keys()]; - if ([...byHolder.values()].some((items) => items.length > 1) || (byHolder.has(null) && holders.length > 1)) { - return { slots: [], holders, bare: { refusal: listedRefusal(name, holders) } }; + const listedTwice = [...byHolder.values()].some((items) => items.length > 1); + const environmentBesidePackage = byHolder.has(null) && holders.length > 1; + if (listedTwice || environmentBesidePackage) { + return { slots: [], holders, bare: { refusal: listedRefusal(name, holders, { environmentBesidePackage, listedTwice }) } }; } const slots = [...byHolder].map(([packageId, [raw]]) => ({ raw, packageId })); return { slots, holders, bare: slots.length === 1 ? { packageId: slots[0].packageId } : { refusal: listedRefusal(name, holders) } }; @@ -436,6 +474,30 @@ export function departedWebhookRows( return [...rows.keys()].filter((packageId): packageId is string => packageId !== null && !slots.includes(packageId)).sort(); } +/** + * [ADR-0150 D3, #33263] The refusal of a declared name that is refused WHOLE: + * no declaration of it is served, yet the read for a caller with no package + * refuses it naming its holders — the metadata service listing the + * environment's declaration beside a package's, or one holder's twice + * ({@link slotsOf}). `undefined` when any slot of the name is served (each is + * then switched at its own address) or nothing refuses it (nothing declares + * it, or its only holder is disabled). A read that fails for any other reason + * throws: "we could not check" never reads as an answer. + */ +export async function wholeNameRefusal( + reader: Pick, + name: string, +): Promise { + if ((await reader.list()).some((d) => d.webhook.name === name)) return undefined; + try { + await reader.declaredWebhookNamed(name); + return undefined; + } catch (err) { + if (err instanceof DeclaredWebhookAmbiguousError) return err.refusal; + throw err; + } +} + /** * The raw declared `webhook` items, registry first, metadata service second. * Never throws: a reader that cannot answer yields nothing from that reader. @@ -571,7 +633,7 @@ export class DeclaredWebhookSource implements DeclaredWebhookReader { `${slots.length} holders declare it (${holders}). Such a row switched the name's one holder; under two ` + 'nothing says which, so a row switched off keeps every holder with no row of its own off, and one ' + 'switched on turns none on (ADR-0150 D4). Switch each holder through its own address: POST ' + - `/api/v1/security/_activation/webhook//${name}.`, + `/api/v1/security/_activation/webhook/${name}?package=PACKAGE.`, { name, holders: slots, rows: unowned }, ); } @@ -714,18 +776,31 @@ export class DeclaredWebhookNameConflictError extends Error { readonly webhook: string; /** * @param switches - The activation door's address of each declaration of - * the name ({@link declaredWebhookActivationPath}): a package's names its - * namespace (#31699), so a name two packages declare gets one per holder. + * the name ({@link declaredWebhookActivationPath}): a package's names that + * package exactly (`?package=PKG`), so a name two packages declare gets + * one per holder, two co-owners of one namespace included. + * @param refusal - [#33263] The name is refused WHOLE + * ({@link wholeNameRefusal}): no declaration of it is dispatched, so there + * is nothing to switch off, and the sentence says why instead of naming an + * address that would answer the same refusal. `switches` is then unread. */ - constructor(name: string, write: 'create' | 'rename', switches: readonly string[] = [declaredWebhookActivationPath(name)]) { + constructor( + name: string, + write: 'create' | 'rename', + switches: readonly string[] = [declaredWebhookActivationPath(name)], + refusal?: PackageScopedRefusal, + ) { super( `webhook '${name}' is declared by the application, so ` + (write === 'create' ? 'a new webhook cannot take its name' : 'no webhook can be renamed to it') + `. Declared webhooks are read-only: to customise '${name}', create your own webhook under another ` - + (switches.length > 1 - ? `name and switch the declared ones off (${switches.map((path) => `POST ${path}`).join(', ')}, each ` - : `name and switch the declared one off (POST ${switches[0] ?? declaredWebhookActivationPath(name)} `) - + 'with { "enabled": false }).', + + (refusal + ? `name. No declaration of '${name}' is dispatched, so none needs switching off: ${refusal.message}` + : switches.length > 1 + ? `name and switch the declared ones off (${switches.map((path) => `POST ${path}`).join(', ')}, each ` + + 'with { "enabled": false }).' + : `name and switch the declared one off (POST ${switches[0] ?? declaredWebhookActivationPath(name)} ` + + 'with { "enabled": false }).'), ); this.name = 'DeclaredWebhookNameConflictError'; this.webhook = name; @@ -767,18 +842,28 @@ export function bindDeclaredWebhookNameGuard( } // [ADR-0150 D3, #31699] A name two packages declare is declared: the // by-name read refuses to pick one of them, and the write is refused - // for the name, as for one holder's, naming each holder's address. - const switches = await declared.declaredWebhookNamed(data.name).then( - (d) => (d ? [declaredWebhookActivationPath(d.webhook.name, d.namespace)] : undefined), + // for the name, as for one holder's, naming each holder's address — + // its package's exact address (#33263), which two co-owners of one + // namespace each have. A name refused WHOLE has no served slot and no + // address to name: the refusal says why instead. + const conflict: { switches: readonly string[]; refusal?: PackageScopedRefusal } | undefined = await declared.declaredWebhookNamed(data.name).then( + (d) => (d ? { switches: [declaredWebhookActivationPath(d.webhook.name, d.packageId)] } : undefined), async (err: unknown) => { if (!(err instanceof DeclaredWebhookAmbiguousError)) throw err; - const slots = (await declared.list?.())?.filter((d) => d.webhook.name === data.name) ?? []; + const listed = await declared.list?.(); + // A reader with no list cannot say which holders are served: each candidate's address. + if (!listed) { + return { switches: err.candidates.map((c) => declaredWebhookActivationPath(data.name, c.kind === 'package' ? c.packageId : undefined)) }; + } + const slots = listed.filter((d) => d.webhook.name === data.name); return slots.length > 0 - ? slots.map((d) => declaredWebhookActivationPath(d.webhook.name, d.namespace)) - : [declaredWebhookActivationPath(data.name, '')]; + ? { switches: slots.map((d) => declaredWebhookActivationPath(d.webhook.name, d.packageId)) } + : { switches: [], refusal: err.refusal }; }, ); - if (switches) throw new DeclaredWebhookNameConflictError(data.name, insert ? 'create' : 'rename', switches); + if (conflict) { + throw new DeclaredWebhookNameConflictError(data.name, insert ? 'create' : 'rename', conflict.switches, conflict.refusal); + } }; const opts = { object, packageId: DECLARED_WEBHOOK_NAME_GUARD_PACKAGE, priority: 100 }; engine.registerHook('beforeInsert', guard(true), opts); diff --git a/packages/plugins/plugin-webhooks/src/redeliver-guard.ts b/packages/plugins/plugin-webhooks/src/redeliver-guard.ts index 6667bdaf5b2..c507d76621d 100644 --- a/packages/plugins/plugin-webhooks/src/redeliver-guard.ts +++ b/packages/plugins/plugin-webhooks/src/redeliver-guard.ts @@ -72,7 +72,10 @@ * environment's, or a delivery written before the package coordinate, the * 18.x ceremony's re-source among them — is judged by the declaration a * caller with no package resolves (D3): with one holder exactly as before; - * with two it is refused naming both, and sent to neither. + * with two it is refused naming both, and sent to neither. A name refused + * WHOLE (#33263: the metadata service lists the environment's declaration + * beside a package's, so no declaration of it is served) is refused with that + * refusal, naming every holder — never as a disabled package. * Not declared any more is case 1, switched off (the activation ledger, or a * declared `isActive: false` no ledger row overrides) is case 2. Case 3 cannot * arise: the signing key is code, held with the declaration. A delivery whose @@ -87,6 +90,7 @@ import { DeclaredWebhookAmbiguousError, declaredWebhookActivationPath, declaredWebhookAddressOfRefId, + wholeNameRefusal, type DeclaredWebhookReader, } from './declared-webhooks.js'; import { @@ -239,6 +243,16 @@ async function judgeDeclared( ); } if (!declaration) { + // [ADR-0150 D3, #33263] The name is refused WHOLE: its holders all + // still declare it, none is served, and nothing is disabled — the + // metadata service lists the environment's declaration beside a + // package's. Said as that, naming every holder, never as a disable. + const whole = declared ? await wholeNameRefusal(declared, name) : undefined; + if (whole) { + return ( + `declared webhook '${name}' is not served, so this delivery is refused: ${whole.message}` + ); + } // [#31699 round 2] The slot's package (or, for a reference naming no // package, the name's one holder) still declares it but is disabled: // a disabled package's webhooks are not served, so neither dispatched @@ -262,7 +276,7 @@ async function judgeDeclared( return ( `declared webhook '${name}' is switched off, and a switched-off webhook is skipped by the dispatcher, ` + 'so this delivery is refused rather than sent to an endpoint that was switched off. Fix: switch it on ' - + `(POST ${declaredWebhookActivationPath(name, declaration.namespace)} with { "enabled": true }), then redeliver.` + + `(POST ${declaredWebhookActivationPath(name, declaration.packageId)} with { "enabled": true }), then redeliver.` ); } return undefined; diff --git a/packages/runtime/src/domains/catalog-activation-door.test.ts b/packages/runtime/src/domains/catalog-activation-door.test.ts index b1cda4bd218..80c8fbef874 100644 --- a/packages/runtime/src/domains/catalog-activation-door.test.ts +++ b/packages/runtime/src/domains/catalog-activation-door.test.ts @@ -1000,6 +1000,60 @@ describe('the catalog activation door — a declared webhook two packages declar expect(ledger(h)).toEqual([[null, false], [A, true]]); }); + // [ADR-0150 D3, #33263] A name the reader refuses WHOLE: it serves no slot + // of the name, yet refuses the bare read naming its holders (plugin-webhooks' + // `wholeNameRefusal`: the metadata service lists the environment's + // declaration beside a package's; that reader's own pins are in + // `declared-webhooks.test.ts`). The double answers as it does. BASE: the + // bare address was 409 naming both, but the exact and the namespace address + // answered 404 "no enabled package declares the name" for a package that + // does. Every address now answers the refusal, naming both. + it('[FROM 404 TO 409] a name refused whole: the bare, the exact and the namespace address all answer 409 naming both holders, nothing written', async () => { + const whole = { + status: 'refused', reason: 'ambiguous-in-environment', type: 'webhook', name: HOOK, callerPackageId: null, + candidates: [{ kind: 'environment' }, { kind: 'package', packageId: A }], + message: `The webhook "${HOOK}" is refused whole.`, + }; + const h = boot('single', {}, { + declaredWebhooks: { + async holdersOf(name: string) { return name === HOOK ? [null, A] : []; }, + async list() { return []; }, + async declaredWebhookNamed(name: string) { + if (name !== HOOK) return null; + throw Object.assign(new Error(whole.message), { code: 'RESOURCE_CONFLICT', status: 409, refusal: whole }); + }, + }, + }); + h.engine.registry.getNamespaceOwners = (ns: string) => OWNERS[ns] ?? []; + for (const [path, query] of [ + [`/_activation/webhook/${HOOK}`, {}], + [`/_activation/webhook/${HOOK}`, { package: A }], + [`/_activation/webhook/alpha/${HOOK}`, {}], + ] as const) { + const res = await h.dispatcher.handleSecurity(path, 'POST', { enabled: false }, query, TENANT_ADMIN()); + const candidates = (res?.response?.body?.error?.details?.candidates ?? res?.response?.body?.error?.candidates ?? []); + expect([statusOf(res), codeOf(res), candidates], `${path} ${JSON.stringify(query)}`) + .toEqual([409, 'RESOURCE_CONFLICT', whole.candidates]); + expect(messageOf(res), path).toBe(whole.message); + } + // A name nothing declares is still the miss, at either qualified address. + expect(statusOf(await h.dispatcher.handleSecurity('/_activation/webhook/our_own_hook', 'POST', { enabled: false }, { package: A }, TENANT_ADMIN()))).toBe(404); + expect(statusOf(await flip(h, TENANT_ADMIN(), '/_activation/webhook/alpha/our_own_hook'))).toBe(404); + expect(h.writes).toEqual([]); + }); + + it('a read that fails while the exact address looks for a whole refusal is 503, never a 404 or a write', async () => { + const h = boot('single', {}, { + declaredWebhooks: { + async list() { return []; }, + async declaredWebhookNamed() { throw new Error('registry down'); }, + }, + }); + const res = await h.dispatcher.handleSecurity(`/_activation/webhook/${HOOK}`, 'POST', { enabled: false }, { package: A }, TENANT_ADMIN()); + expect([statusOf(res), codeOf(res)]).toEqual([503, 'SERVICE_UNAVAILABLE']); + expect(h.writes).toEqual([]); + }); + it('the namespace address is the webhook\'s alone: any other type with four segments is the shape 400', async () => { const h = bootWith([A]); expect(statusOf(await flip(h, TENANT_ADMIN(), `/_activation/sharing_rule/alpha/${HOOK}`))).toBe(400); diff --git a/packages/runtime/src/domains/catalog-activation.ts b/packages/runtime/src/domains/catalog-activation.ts index a105cea6a67..099bf3274d8 100644 --- a/packages/runtime/src/domains/catalog-activation.ts +++ b/packages/runtime/src/domains/catalog-activation.ts @@ -113,6 +113,11 @@ * A row naming no package becomes the holder's own when the name has that one * holder (`adoptPackageless`, ADR-0150 D8), as the name-addressed store wrote * it before; under two holders it is neither's and is never written for one. + * A name the reader refuses WHOLE — no declaration of it served, the + * environment's listed beside a package's on a host whose registry holds no + * webhook — has no switch at any address: the bare, the exact and the + * namespace address all answer `409` naming every holder, nothing written + * ({@link wholeWebhookNameRefusal}, #33263). */ import { AUDIENCE_ANCHOR_POSITIONS, GUEST_POSITION } from '@objectstack/spec/identity'; @@ -281,7 +286,10 @@ async function resolveQualifiedWebhook( const slots = (await reader.list!()).filter((d) => d.webhook.name === name); const holding = slots.flatMap((d) => (d.packageId !== undefined && owners.includes(d.packageId) ? [d.packageId] : [])); if (holding.length === 1) return { entry: { name, packageId: holding[0] }, holders: slots.length }; - if (holding.length === 0 && slots.length === 0) return { missing: `nothing declares it in namespace '${namespace}'` }; + if (holding.length === 0 && slots.length === 0) { + const refusal = await wholeWebhookNameRefusal(reader, name); + return refusal ? { refusal } : { missing: `nothing declares it in namespace '${namespace}'` }; + } const candidates: PackageScopedHolder[] = (holding.length > 1 ? holding : slots.map((d) => d.packageId)) .map((packageId) => (packageId === undefined ? { kind: 'environment' as const } : { kind: 'package' as const, packageId })); const base = { @@ -302,9 +310,10 @@ async function resolveQualifiedWebhook( * that switches one holder wherever the namespace address cannot: two * co-owners of one namespace, or a package that declares no namespace beside * another holder. A PKG that does not hold the name is refused naming the - * holders (`not-held-by-qualifier`); `404` when nothing serves the name. As - * in {@link resolveQualifiedWebhook}, a DISABLED package's declaration is no - * slot, so a disabled PKG holds nothing here. + * holders (`not-held-by-qualifier`); `404` when nothing serves the name, unless + * the reader refuses the name WHOLE ({@link wholeWebhookNameRefusal}): `409` + * naming every holder. As in {@link resolveQualifiedWebhook}, a DISABLED + * package's declaration is no slot, so a disabled PKG holds nothing here. */ async function resolveExactWebhook( reader: DeclaredWebhookReader, @@ -317,7 +326,10 @@ async function resolveExactWebhook( > { const slots = (await reader.list!()).filter((d) => d.webhook.name === name); if (slots.some((d) => d.packageId === packageId)) return { entry: { name, packageId }, holders: slots.length }; - if (slots.length === 0) return { missing: 'no enabled package declares the name' }; + if (slots.length === 0) { + const refusal = await wholeWebhookNameRefusal(reader, name); + return refusal ? { refusal } : { missing: 'no enabled package declares the name' }; + } const candidates: PackageScopedHolder[] = slots.map((d) => (d.packageId === undefined ? { kind: 'environment' as const } : { kind: 'package' as const, packageId: d.packageId })); @@ -332,6 +344,29 @@ async function resolveExactWebhook( return { refusal: { ...base, message: packageScopedRefusalMessage(base) } }; } +/** + * [ADR-0150 D3, #33263] The refusal of a declared webhook name the reader + * serves no slot of and yet refuses for a caller with no package: a name + * refused WHOLE (plugin-webhooks' `wholeNameRefusal` — the metadata service + * listing the environment's declaration beside a package's). Every address + * then answers that refusal, `409` naming every holder: the exact and the + * namespace address used to answer `404` "no enabled package declares the + * name" for a package that does declare it. `undefined` when the bare read + * answers (nothing declares the name, or its only holder is disabled: the + * `404` stays). Called only once the served slots are known to be none; a read + * that fails any other way throws, and the caller answers `503`. + */ +async function wholeWebhookNameRefusal(reader: DeclaredWebhookReader, name: string): Promise { + try { + await reader.declaredWebhookNamed(name); + return undefined; + } catch (err) { + const refusal = packageScopedRefusalOf(err); + if (refusal) return refusal; + throw err; + } +} + function declaredWebhookReaderOf(service: unknown): DeclaredWebhookReader | undefined { const candidate = service as Partial | null | undefined; return typeof candidate?.declaredWebhookNamed === 'function' ? (candidate as DeclaredWebhookReader) : undefined;