From 26cff7ebf41d7d87286f0ff9fda52778ecadc493 Mon Sep 17 00:00:00 2001 From: Luke Abell Date: Sat, 5 Dec 2026 03:03:05 -0500 Subject: [PATCH] fix(plugins): record webhook deliveries whose body holds NUL (#16985) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plugins receive inbound webhooks on `POST /api/plugins/:pluginId/webhooks/:endpointKey` > - The route records each delivery in `plugin_webhook_deliveries` before it calls the worker > - The row keeps the parsed body and the headers in jsonb columns > - PostgreSQL refuses a jsonb value that holds U+0000 or an unpaired UTF-16 surrogate (22P05 "unsupported Unicode escape sequence") > - So a delivery whose body has a NUL fails at the insert. No row is written, the worker is not called, and the sender gets a 500 and retries into the same failure > - This pull request stores a jsonb-safe copy of the body and headers, and gives the worker the request as sent > - The benefit is that such a delivery is recorded and handled ## Linked Issues or Issue Description **What happened?** A plugin webhook delivery whose JSON body held `\^@` failed with `PostgresError: unsupported Unicode escape sequence` (code 22P05) at `insert into "plugin_webhook_deliveries"`. The route answered 500 and did not call the worker. A provider that retries on 5xx sent the same delivery again, and it failed again. **Expected behavior** The route records the delivery, calls the worker with the body as sent, and answers 200. **Steps to reproduce** 1. Install a plugin that has the `webhooks.receive` capability and declares a webhook endpoint. 2. Send `{"text":"a\^@b"}` with `Content-Type: application/json` to `POST /api/plugins//webhooks/`. 3. The answer is 500, and `plugin_webhook_deliveries` has no row for the delivery. **Paperclip version or commit** `master` at efcc8a7d8. `server/src/routes/plugins.ts` is the same on the current `master`. Refs #16918 (the same 22P05 error class on run status writes; this pull request uses its rule: drop NUL, turn an unpaired surrogate into U+FFFD) Refs #16782 (what the delivery row stores) ## What Changed - `server/src/routes/plugins.ts`: add the exported helper `pluginWebhookJsonbValue()`. It reads the `JSON.stringify` text that the driver sends. It drops each real `\^@` escape. It replaces each `\udXXX` escape (the form `JSON.stringify` gives an unpaired surrogate) with `�`. This applies to keys and values. An escaped backslash before a literal `u0000` stays unchanged. A clean value comes back unchanged (the same object). - The delivery insert stores `pluginWebhookJsonbValue(payload)` and `pluginWebhookJsonbValue(rawHeaders)`. The worker call does not change: it still gets `rawBody` and `parsedBody` as sent, so a signature check on the raw body does not change. - `server/src/__tests__/plugin-webhook-unicode.test.ts`: unit tests for the helper, and a route test on embedded Postgres that posts a body with a NUL and an unpaired surrogate. ## Verification - `cd server && npx vitest run src/__tests__/plugin-webhook-unicode.test.ts`: 3 passed (embedded Postgres included). - With the change to `plugins.ts` reverted, the route test fails with `expected 500 to be 200`, which is the reported error. - `tsc --noEmit` in `server/`: no errors in the changed files. ## Risks - Low risk. The stored copy is different only when the body or headers hold a NUL or an unpaired surrogate. PostgreSQL refuses those values today, so no such row exists now. - A reader of `plugin_webhook_deliveries.payload` sees the NUL dropped. The worker and the signature check see the request as sent. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Provider: Anthropic. Model: Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution, in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Luke Abell <3343530+LukeAbell@users.noreply.github.com> --- .../__tests__/plugin-webhook-unicode.test.ts | 94 +++++++++++++++++++ server/src/routes/plugins.ts | 13 ++- 2 files changed, 105 insertions(+), 2 deletions(-) create mode 100644 server/src/__tests__/plugin-webhook-unicode.test.ts diff --git a/server/src/__tests__/plugin-webhook-unicode.test.ts b/server/src/__tests__/plugin-webhook-unicode.test.ts new file mode 100644 index 00000000000..dd80236b8f7 --- /dev/null +++ b/server/src/__tests__/plugin-webhook-unicode.test.ts @@ -0,0 +1,94 @@ +import { randomUUID } from "node:crypto"; +import express from "express"; +import request from "supertest"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { createDb, pluginWebhookDeliveries, plugins } from "@paperclipai/db"; +import { pluginRoutes, pluginWebhookJsonbValue } from "../routes/plugins.js"; +import { + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, +} from "./helpers/embedded-postgres.js"; + +const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); + +describe("pluginWebhookJsonbValue", () => { + it("drops NUL and replaces unpaired surrogates in keys and values, and keeps everything else", () => { + expect(pluginWebhookJsonbValue({ "k\u0000ey": ["a\u0000b", { n: "\ud800x\udc00" }], pair: "\ud83d\ude00", n: 1 })) + .toEqual({ key: ["ab", { n: "\ufffdx\ufffd" }], pair: "\ud83d\ude00", n: 1 }); + }); + + it("keeps an escaped backslash before a literal u0000, and returns a clean value unchanged", () => { + expect(pluginWebhookJsonbValue({ path: "C:\\u0000", both: "\\\u0000" })).toEqual({ path: "C:\\u0000", both: "\\" }); + const clean = { a: "b", c: [1, null] }; + expect(pluginWebhookJsonbValue(clean)).toBe(clean); + }); +}); + +describe.skipIf(!embeddedPostgresSupport.supported)("plugin webhook route: Postgres-invalid Unicode", () => { + let db!: ReturnType; + let tempDb: Awaited> | null = null; + const workerCall = vi.fn(async () => undefined); + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-plugin-webhook-unicode-"); + db = createDb(tempDb.connectionString); + }, 20_000); + + afterEach(async () => { + workerCall.mockReset(); + workerCall.mockImplementation(async () => undefined); + await db.delete(pluginWebhookDeliveries); + await db.delete(plugins); + }); + + afterAll(async () => { + await tempDb?.cleanup(); + }); + + async function seedPlugin() { + const id = randomUUID(); + const key = `paperclip.webhook-unicode-test-${id.slice(0, 8)}`; + await db.insert(plugins).values({ + id, + pluginKey: key, + packageName: `@paperclipai/${key}`, + version: "0.0.1", + apiVersion: 1, + categories: ["connector"], + manifestJson: { + id: key, apiVersion: 1, version: "0.0.1", displayName: "Webhook test", description: "Test plugin", + author: "Paperclip", categories: ["connector"], capabilities: ["webhooks.receive"], + entrypoints: { worker: "./dist/worker.js" }, + webhooks: [{ endpointKey: "hook", displayName: "Hook" }], + }, + status: "ready", + installOrder: 1, + } as never); + return id; + } + + function app() { + const a = express(); + a.use(express.json({ verify: (req, _res, buf) => { (req as unknown as { rawBody: Buffer }).rawBody = buf; } })); + a.use("/api", pluginRoutes(db, {} as never, undefined, { workerManager: { call: workerCall } } as never)); + return a; + } + + it("records a delivery whose body holds NUL and an unpaired surrogate, and passes the body to the worker as sent", async () => { + const id = await seedPlugin(); + const body = '{"text":"a\\u0000b","bad\\u0000key":"\\ud800"}'; + const res = await request(app()) + .post(`/api/plugins/${id}/webhooks/hook`) + .set("Content-Type", "application/json") + .send(body); + expect(res.status).toBe(200); + expect(workerCall).toHaveBeenCalledTimes(1); + expect(workerCall.mock.calls[0]).toEqual([id, "handleWebhook", expect.objectContaining({ + rawBody: body, + parsedBody: { text: "a\u0000b", "bad\u0000key": "\ud800" }, + })]); + const rows = await db.select().from(pluginWebhookDeliveries); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ status: "success", payload: { text: "ab", badkey: "\ufffd" } }); + }); +}); diff --git a/server/src/routes/plugins.ts b/server/src/routes/plugins.ts index 488f4eb1560..6538d737dd1 100644 --- a/server/src/routes/plugins.ts +++ b/server/src/routes/plugins.ts @@ -487,6 +487,15 @@ interface PluginToolExecuteRequest { runContext: Omit & { projectId?: string | null }; } +export function pluginWebhookJsonbValue(value: T): T { + const json = JSON.stringify(value); + if (json === undefined || !/\\u(?:0000|d[89a-f])/i.test(json)) return value; + return JSON.parse(json.replace( + /(? `${backslashes}${code === "0000" ? "" : "\\ufffd"}`, + )) as T; +} + /** * Create Express router for plugin management API. * @@ -2854,8 +2863,8 @@ export function pluginRoutes( pluginId: plugin.id, webhookKey: endpointKey, status: "pending", - payload, - headers: rawHeaders, + payload: pluginWebhookJsonbValue(payload), + headers: pluginWebhookJsonbValue(rawHeaders), startedAt, }) .returning({ id: pluginWebhookDeliveries.id });