Skip to content

Commit 6cc5374

Browse files
fix(plugin-webhooks): gate webhook redelivery on webhook-administration access (#27474)
domain:devx#1 · sunhaolin · session_017xRBcVy4VXmkQjn2MGeaWk Hardening dispatched directly by QA (domain:devx); no tracking issue. Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — no file under skills/** teaches the redeliver door (git grep -i redeliver -- skills: 0 hits at b4a2146); the page that does, content/docs/automation/webhooks.mdx section 8, is updated in this diff Review owed before the queue: this narrows who may call a public door (`POST /api/v1/webhooks/redeliver`). The contract-tier review of 957b968 (FAIL, one must-fix and four should-fixes) is answered at b4a2146; a delta review by that seat is owed on this head. ## 维护者速读 - 改了什么:Webhook 重投递入口(`POST /api/v1/webhooks/redeliver`,两个入口面)在登录校验之后、读取请求体之前,由安全服务判定调用者是否有 Webhook 管理权限(`sys_webhook` 的对象级编辑准入);判定所用的调用者上下文按部署的租户隔离姿态解析,与数据 API 一致:隔离姿态下,会话声称的组织若已无有效成员关系,该声明不被采纳,入口以同一个 403 拒绝;重投递只写入调用者被准入的那个组织。 - 为什么改:原先"任何已登录用户都可重投递"只是早期延后实现;本轮复核指出闸门未带租户姿态,在隔离姿态下与数据 API 的准入不一致(成员关系已结束的会话仍按旧组织解析),现已对齐 2026-09-05 裁决(选项 B)的逐请求成员关系校验。 - 风险与回滚:依赖非管理员点重投递的部署改为 403(迁移:用权限集授予 `sys_webhook` 编辑权);隔离姿态下组织声明失效的会话改为 403(切换到自己所属的组织即可);未注册安全服务的部署改为 503,并在启动时打印一次提示。回滚即 revert 本 PR。待维护者定夺(人工底线,未在本 PR 内决定):重投递权限轴,按现实现为 `sys_webhook` 的 `update`,备选为投递对象上的专用能力(需改 spec)。 - 先看:`packages/plugins/plugin-webhooks/src/redeliver-entitlement.ts`(租户解析器两条腿、被丢弃组织声明的拒绝、失败方向)、`webhook-outbox-plugin.ts` 中 `serveRedeliver` 闸门段与重投递所用租户、`webhook-redeliver-entitlement.test.ts` 新增的隔离姿态用例。 - 两分钟验证:`pnpm --filter @objectstack/plugin-webhooks exec vitest run --maxWorkers=2 src/webhook-redeliver-entitlement.test.ts`,预期 21 个用例全绿(含 isolated/group 下组织声明失效 403 且未重投、成员关系有效时放行且限定本组织、真实 ObjectKernel 上租户服务失败 503)。 - 需要你做的:裁定重投递的权限轴(保持 `sys_webhook` 的 `update`,或改为投递对象上的专用能力)。 ## What changes - **The gate.** `serveRedeliver` (the one body both faces run: the self-hosted raw-app mount and the `webhooks` slot's `handleRedeliver`) asks, right after the auth gate and the `401` and before the request body is read, whether the signed-in caller may administer webhooks (`redeliver-entitlement.ts`): - the caller's `ExecutionContext` comes from `resolveRequestExecutionContext` (the one platform composition), fed the session the door already read (`session: { established }`), so the gate judges exactly the identity the door acts as; - the decision is `ISecurityService.explain({ object: 'sys_webhook', operation: 'update' }, context).allowed` (ADR-0124 D1: server-side); - refused: `403 PERMISSION_DENIED`, one fixed answer, so nothing in it depends on a delivery row; no security service, or a check that throws: `503 SERVICE_UNAVAILABLE` (ADR-0124 D3: an undecided case is never admitted; cause logged at `error`). - **The organization (this round's must-fix).** The composition is now handed the door's own `tenancy` resolver (`redeliverTenancyResolver`), so the session's organization claim is vetted against the posture in force exactly as the data API's doors vet it (the per-request membership check of the 2026-09-05 ruling, option B). The resolver reads the kernel's async accessor (`getServiceAsync('tenancy')`) where the kernel has one, so `classifyAdmissionTenancyPosture` sees the registry's own answer: never registered is no posture, registered and failing is the outage the gate's `catch` answers `503`. On a factory-less `KernelBase` host the sync accessor's only fault is "not registered", absorbed inside the thunk. The admission carries the vetted `tenantId`, and the replay is scoped to it, never to the raw session claim. - **A claim the composition did not keep is refused** with the same `403` body. The replay is scoped by one organization; a dropped claim leaves none, and threading none would be an unscoped write, wider than any write the data API's gate gives that caller (with no active organization the tenant layer denies every row under `isolated` and admits only the caller's own organizations under `group`, a set this door's single-tenant scope cannot express). The principal is not refused: the session stays signed in with no active organization, as option B prescribes; only this door's act, which needs an organization, is declined. - **Absence is loud at boot.** When the door is served on either face and no security service can decide, the plugin says once at `kernel:ready`, at `warn`, that every caller will be answered `503`, naming the remedy (compose `@objectstack/plugin-security`). - **Why `update` on `sys_webhook`, not `read` on `sys_http_delivery`.** Replaying a delivery is a write-shaped act (the row resets and a signed request goes out), the same power as editing or re-activating the subscription; a read-only principal holding a read wildcard must not gain it. The axis is pending the maintainer (see 维护者速读). - **Unchanged for an entitled caller:** the ADR-0069 gate, `401`, the `400` body refusals, active-organization scoping (`404` outside it), the redelivery veto's `409`s, the `200` replay. The door still admits no API key. - **Docs and records.** `content/docs/automation/webhooks.mdx` section 8 states the gate and the organization vetting; checklist `integration-system.webhook-lifecycle` r12 (posture sentence) and r13 (this round: acceptance[4].verify no longer cites a no-capability docblock, steps[6] drives the redeliver as the seeded admin, the walled-posture refusal is named) and `integration-system.notification-org-and-redeliver-eligibility` r4; the two stale "any authenticated user" docblocks in `service-messaging` (`http-outbox.ts` `RedeliverOptions`, `sql-http-outbox.ts` `redeliver`) now state the gate; an ADR-0124 anchor for `redeliver-entitlement.ts`; the dogfood authz matrix row; the engine-double ledger row; the changeset declares the narrowing (`Clause-②: no (narrowing)`, the BREAKING banner, one ADR-0087 disposition `not-required (no-migration-prescription)`), level `patch`. ## Tests At b4a2146 (local, on a shared box): - `@objectstack/plugin-webhooks` `pnpm test`: `Test Files 24 passed (24) · Tests 252 passed (252)`; `typecheck` (tsc, scripts tsconfig, test layer) exit 0, `check:test-typecheck: OK`. - `webhook-redeliver-entitlement.test.ts`: 21 cases (11 before this round). New: on `isolated`, an administrator whose claimed organization no current membership backs is refused with the byte-identical body an unentitled member gets, nothing replayed (both faces); on `group`, a claim on an organization the caller left is refused for that organization's delivery and for the one it still belongs to (both faces); control, a backed claim is admitted, the replay is threaded with that organization and another organization's delivery answers `404` (both faces); the once-at-boot line for a kernel with no security service; on a real `ObjectKernel` registry, the resolver reads never-registered as no posture, a walled posture as the drop, and a `tenancy` factory that throws as `503` with the cause logged and the security service never asked. The security double now records the organization the caller's context was resolved in. - `@objectstack/service-messaging` (comment-only edits): `typecheck` exit 0; `pnpm test` `Test Files 62 passed (62) · Tests 739 passed (739)`. - `@objectstack/http-conformance` `hono-webhooks-redeliver.conformance.test.ts`: 7/7. <details><summary>Ablations (one-time, not kept; tool: scripts/ablation-replace.mjs, subject resolved from source)</summary> - `tenancy: input.tenancy` replaced by `tenancy: undefined` (anchor 1 to 0, blob `ea5e9bd6` to `59923a52`): `6 failed | 15 passed (21)`, the four walled-posture refusals and the two `ObjectKernel` walled/failing cases red; restored, blob equal to HEAD, `git diff HEAD` empty. - the dropped-claim refusal line deleted (blob `ea5e9bd6` to `edbf3939`): `5 failed | 16 passed (21)`, the four walled refusals and the `ObjectKernel` walled case red (the replay went out unscoped); restored, blob equal to HEAD. - the once-at-boot report call deleted from the `kernel:ready` hook (`webhook-outbox-plugin.ts`, blob `c13b3ae5` to `99057719`): `1 failed | 20 passed (21)`, the boot-line case red; restored, blob equal to HEAD, `git diff HEAD` empty. </details> ## Acceptance notes - The review suggested reaching the `tenancy` service "through the same `tryGetService` discipline". The resolver deliberately does not use the plugin's swallowing `tryGetService` on a kernel with `getServiceAsync`: it would read a registered-and-failed service as absent, the permissive-on-failure collapse `classifyAdmissionTenancyPosture` exists to prevent. The sync, swallowing leg is used only on a factory-less `KernelBase` host, the same split `packages/mcp/src/plugin.ts` records. - Threading the vetted `tenantId` rather than the raw claim has no behaviour difference on an admitted call (the gate refuses whenever they differ), so it is pinned structurally (the replay's organization is asserted in the control case) and not ablated separately. - Kept as found, noted: `http-outbox-parked-record.integration.test.ts`'s docblock narrates the pre-#8069 state ("which any authenticated user can reach") as history, not as the current posture. - `tryGetService(['security'])` treats a throwing lookup as absent, so a kernel that never registered `security` answers `503` with a remedy, never a silent admit. - The gate is asked of `sys_webhook` (this plugin's configuration object), not of a host-renamed `subscriptionsObject`. ## Verification The live readings recorded on 957b968 (fresh showcase boot, member 403 / admin 409, 404, 400, 200 with the sink re-hit / anonymous 401) are unchanged in meaning by this round, which changes only the walled-posture organization vetting; the showcase boots on `single`, where the claim stands as made. Not re-driven live this round. <details><summary>Local gates (derived set, b4a2146)</summary> `node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack --ran FILE`: `Run reconciliation — 104 derived, 104 run, 0 NOT-MEASURED, 0 UNRUN` · `✓ dispatch-gates --ran: 104 derived famil(ies) accounted for`, all 104 exit 0 at `b4a2146cb6`. First-pass reds and their resolution: `check:objectql-double-limit` exit 1 (the suite's new `sys_member` double was limit-blind; CI red on `1b07782bdb`) fixed in `b4a2146cb6`, re-run exit 0; `check-plugin-teardown-shape --self-test` exit 3 (shallow clone, pinned positive control unreachable) re-run after fetching that one commit, exit 0; `check:skill-examples`, `check:dual-build-cjs-loads`, `check:i18n` exit 3 (PREREQUISITE NOT MET: unbuilt dist) re-run after a full `pnpm build` (114/114), exit 0 each. CI on `b4a2146cb6`: 50 check-runs, 37 success, 13 skipped, 0 failure; the reds reported on `f1c7919300` were `cancelled` lanes superseded by the next push. </details> <details><summary>Not run locally</summary> `pnpm lint` and the repo-wide farm are CI's; `test:repo` not run (the diff edits no `repo`-project test). Full dogfood battery owed by the `(narrowing)` arm, run once at `b4a2146cb6` after a full `pnpm build`: `pnpm --filter @objectstack/dogfood test` under the verify lock, `VERDICT command-exit 0`, `Test Files 348 passed | 3 skipped (351)`, `Tests 2806 passed | 20 skipped (2826)`. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_017xRBcVy4VXmkQjn2MGeaWk)_ <sub>Body refreshed by the PM seat 2026-10-29T15:22Z from the os-dev rework report.</sub> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent aa874c8 commit 6cc5374

18 files changed

Lines changed: 971 additions & 49 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/plugin-webhooks': patch
3+
---
4+
5+
fix(plugin-webhooks)!: gate webhook redelivery on webhook-administration access
6+
7+
Clause-②: no (narrowing) — `POST /api/v1/webhooks/redeliver` admits only a signed-in caller entitled to administer webhooks, in an organization a current membership backs on a walled posture, where it admitted every signed-in caller. Nothing is widened.
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No metadata moves: no spec key, authorable spelling, object definition, stored row or stored shape is added, removed, renamed or re-shaped, and no exported declaration changes, so there is nothing for `objectstack migrate meta` to rewrite and no tombstone. What narrows is the set of callers one HTTP door admits; the remedy is a permission grant an administrator makes, which no ledger entry can derive. The other categories are closed on facts: the package publishes (not unpublished); no ADR-0087 id covers this change (not registered or already-registered); and nothing exported is removed or narrowed (not runtime-interface-only, type-surface-only or runtime-export-retired). -->
11+
12+
**BREAKING** accept-set narrowing at the webhook redeliver door (`@objectstack/plugin-webhooks`), on both faces: the self-hosted mount and the `webhooks` service's `handleRedeliver`. The caller's entitlement is decided server-side by the security service before the request body is read or any delivery row is looked up.
13+
14+
- **The entitlement.** The security service's object-level `update` admission on `sys_webhook` (`ISecurityService.explain`), for the caller's execution context as the platform's request-context composition resolves it, the same answer the data API's write gate gives that caller. The shipped administrator permission sets carry it; a member baseline does not.
15+
- **The organization.** That context is resolved with the deployment's tenancy posture, as the data API resolves it: on a walled posture (`isolated`, `group`) a session's active-organization claim that no current membership backs is not kept, and the door answers that caller with the same `403`. The replay is scoped to the organization the caller was admitted in.
16+
- **An unentitled caller** is answered `403 PERMISSION_DENIED`, the same answer whatever the request names, so the refusal carries no row-specific detail and nothing is replayed.
17+
- **Fail closed.** A deployment with no security service registered, or a check that cannot be decided (including a tenancy service that is registered and cannot answer), answers `503 SERVICE_UNAVAILABLE` and replays nothing. A kernel that serves the door with no security service says so once at boot, naming the remedy.
18+
- **Unchanged for an entitled caller:** the auth gate, `401` for no session, the `400` body refusals, the active-organization scoping (`404` outside it), the redelivery veto's `409`s and the `200` replay. The door still admits no API key.
19+
20+
Migration: a deployment that relied on non-administrators pressing redeliver grants them `allowEdit` on `sys_webhook` through a permission set; a caller on a walled posture switches to an organization it belongs to.

‎content/docs/automation/webhooks.mdx‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -624,7 +624,17 @@ The plugin mounts exactly **one** custom endpoint:
624624
| POST | `/api/v1/webhooks/redeliver` | `{ deliveryId }` | Re-queue a delivery that was **attempted** and failed. A row that was never attempted cannot be redelivered. |
625625

626626
It delegates to `messaging.redeliverHttp(deliveryId)` and is guarded by the
627-
better-auth session (any authenticated user). Failures answer in the declared
627+
better-auth session **and by webhook-administration access**: the caller must be
628+
allowed to edit `sys_webhook` (the security service's object-level `update`
629+
admission, decided server-side before the request body is read). A signed-in
630+
caller without it is answered `403` `PERMISSION_DENIED` before any detail about
631+
the delivery; a deployment with no security service to decide answers `503`
632+
`SERVICE_UNAVAILABLE`. Grant webhook administration through a permission set
633+
(the shipped administrator sets carry it). The caller's active organization is
634+
vetted the way the data API vets it: on a walled tenancy posture (`isolated`,
635+
`group`) an organization claim that no current membership backs is answered with
636+
the same `403`, and a replay reaches only deliveries of the organization the
637+
caller was admitted in (`404` for any other). Failures answer in the declared
628638
envelope — `{ success: false, error: { code, message } }` — with `401`
629639
`UNAUTHENTICATED`, `400` `INVALID_REQUEST` or `MISSING_REQUIRED_FIELD`, `404`
630640
`RESOURCE_NOT_FOUND`, `409` `DELIVERY_NOT_ELIGIBLE`, or `409`

‎docs/qa/platform-checklist/areas/integration-system.json‎

Lines changed: 26 additions & 8 deletions
Large diffs are not rendered by default.

‎packages/plugins/plugin-webhooks/src/in-process-session-read.pin.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
import { describe, it, expect } from 'vitest';
2323
import { WebhookOutboxPlugin } from './webhook-outbox-plugin.js';
24+
import { webhookAdministrationSecurity } from './redeliver-entitlement.testkit.js';
2425

2526
const SESSION_COOKIE = 'better-auth.session_token=tok_22258.c2lnbmF0dXJl';
2627
const BEARER = 'Bearer tok_22258.c2lnbmF0dXJl';
@@ -46,6 +47,8 @@ async function redeliver(headers: Record<string, string>) {
4647
return { id, status: 'pending' };
4748
},
4849
},
50+
// The entitlement gate: every signed-in caller here administers webhooks.
51+
security: webhookAdministrationSecurity(),
4952
auth: {
5053
api: {
5154
getSession: async (input: any) => {
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* A `security` service double for the redeliver door's entitlement gate
5+
* (`redeliver-entitlement.ts`): it answers `explain` the way the real service
6+
* answers the one question the gate asks — may this caller `update`
7+
* `sys_webhook`? — for the users it is told are webhook administrators, and
8+
* records every question it was asked.
9+
*
10+
* A suite whose subject is NOT entitlement (tenant scope, the veto, the auth
11+
* gate, the session read) registers {@link webhookAdministrationSecurity} with
12+
* no argument, so every signed-in caller in it is an administrator and the
13+
* suite drives the door's admitted path exactly as it did before the gate.
14+
*/
15+
16+
export interface AskedEntitlement {
17+
readonly object: string;
18+
readonly operation: string;
19+
readonly userId: unknown;
20+
/** The organization the caller's context was resolved in when the gate asked. */
21+
readonly tenantId: unknown;
22+
}
23+
24+
export interface WebhookAdministrationSecurityDouble {
25+
readonly asked: AskedEntitlement[];
26+
explain(request: { object: string; operation: string }, context?: { userId?: unknown; tenantId?: unknown }): Promise<any>;
27+
}
28+
29+
/**
30+
* @param isAdministrator which signed-in users may administer webhooks;
31+
* omitted, every one may.
32+
*/
33+
export function webhookAdministrationSecurity(
34+
isAdministrator: (userId: unknown) => boolean = () => true,
35+
): WebhookAdministrationSecurityDouble {
36+
const asked: AskedEntitlement[] = [];
37+
return {
38+
asked,
39+
async explain(request, context) {
40+
asked.push({
41+
object: request.object,
42+
operation: request.operation,
43+
userId: context?.userId,
44+
tenantId: context?.tenantId,
45+
});
46+
const allowed = request.object === 'sys_webhook'
47+
&& request.operation === 'update'
48+
&& isAdministrator(context?.userId);
49+
return { allowed, layers: [] };
50+
},
51+
};
52+
}

0 commit comments

Comments
 (0)