Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: harden signed GitHub webhook rejection paths
Sebastian B8d1ef0d6965d
diff --git a/apps/docs/content/docs/features/automation.mdx b/apps/docs/content/docs/features/automation.mdxindex a75a1735e3..e5072c5731 100644--- a/apps/docs/content/docs/features/automation.mdx+++ b/apps/docs/content/docs/features/automation.mdx@@ -62,10 +62,12 @@ Use a repository webhook when the catalog does not offer the event you need:1. Ask the bot to create a webhook automation for the work.Include the repository, action, and branch conditions in its instructions.For example: "Review acme/widgets PRs only when action is opened and the base branch is main. Stop for other events."-2. Open the automation under **Automations** and copy its endpoint and secret.- The bot can also retrieve them with `trigger_info` and `include_address`.+2. In your own chat, ask the owning bot for setup details with `trigger_info` and `include_address`.+ Use the private result's `githubUrl` for the signed endpoint.+ Get the secret separately from its `bearer` field; keep it only in GitHub's **Secret** field.+ Do not append `/github` to **Copy address** or the result's `url`; those may contain the secret.3. In the GitHub repository, open **Settings → Webhooks → Add webhook**.-4. Set **Payload URL** to the endpoint followed by `/github`, such as `https://bots.example.com/hooks/wh_example/github`.+4. Set **Payload URL** to `githubUrl`, such as `https://bots.example.com/hooks/wh_example/github`.5. Set **Content type** to `application/json` and **Secret** to the automation's secret.Keep SSL verification enabled.6. Select the events you need, such as **Pull requests**, **Issues**, **Pushes**, **Releases**, or **Workflow runs**.diff --git a/server/webhook-address.test.ts b/server/webhook-address.test.tsindex 863c78191a..495a36df56 100644--- a/server/webhook-address.test.ts+++ b/server/webhook-address.test.ts@@ -32,6 +32,15 @@ describe("who gets a webhook automation's address", () => {});describe("the address", () => {+ it("gives GitHub setup a signed endpoint and a separate secret", () => {+ const address = webhookAddress(kept, "hook-1", "https://acme.example.com/");+ expect(address).toMatchObject({ githubUrl: "https://acme.example.com/hooks/wh_abc/github", bearer: SECRET });+ if (!address || "unavailable" in address) throw new Error("Expected an available address");+ expect(address.note).toContain("githubUrl as Payload URL");+ expect(address.note).toContain("bearer as Secret");+ expect(address.note).toContain("Do not append /github to url or Copy address");+ });+it("is the full address, the endpoint and the bearer secret, with where to paste it and where never to", () => {const address = webhookAddress(kept, "hook-1", "https://acme.example.com/");expect(address).toMatchObject({ url: `https://acme.example.com/hooks/wh_abc/${SECRET}`, endpoint: "https://acme.example.com/hooks/wh_abc", bearer: SECRET });diff --git a/server/webhook-address.ts b/server/webhook-address.tsindex a0c3b83cb7..58851436ec 100644--- a/server/webhook-address.ts+++ b/server/webhook-address.ts@@ -14,7 +14,7 @@ export interface AddressAsk {outsideDriven: boolean;}-export type WebhookAddress = { url: string; endpoint: string; bearer: string; note: string } | { unavailable: string };+export type WebhookAddress = { url: string; endpoint: string; githubUrl: string; bearer: string; note: string } | { unavailable: string };const LOOPBACK = /^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?\//u;@@ -37,8 +37,9 @@ export function webhookAddress(webhooks: Pick<WebhookManager, "currentSecret">,return {url: credential.url,endpoint: credential.endpointUrl,+ githubUrl: `${credential.endpointUrl}/github`,bearer: credential.secret,- note: `Paste url into the setup of the app that sends to this automation, and nowhere else: never repeat it in chat, notes, files or messages to other bots. An app that can't take the full address sends to endpoint with the header "Authorization: Bearer <bearer>". For GitHub, use endpoint + "/github" as Payload URL, application/json as Content type, and bearer as Secret. Select the requested GitHub events; put action and branch conditions in the automation's instructions.${local}`,+ note: `Paste url into the setup of the app that sends to this automation, and nowhere else: never repeat it in chat, notes, files or messages to other bots. An app that can't take the full address sends to endpoint with the header "Authorization: Bearer <bearer>". For GitHub, use githubUrl as Payload URL, application/json as Content type, and bearer as Secret. Do not append /github to url or Copy address; those may contain the secret. Obtain bearer separately from this private tool result. Select the requested GitHub events; put action and branch conditions in the automation's instructions.${local}`,};}diff --git a/server/webhook-github.test.ts b/server/webhook-github.test.tsindex b5eb7d0e60..766166e11c 100644--- a/server/webhook-github.test.ts+++ b/server/webhook-github.test.ts@@ -1,11 +1,12 @@import { createHmac } from "node:crypto";import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { createConnection } from "node:net";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";import { listenWebhookIngress, MAX_WEBHOOK_BODY_BYTES, type WebhookIngress } from "./webhook-ingress.ts";-import { WebhookManager } from "./webhooks.ts";+import { WEBHOOK_KEY_FILE, WebhookManager } from "./webhooks.ts";let dir: string;let manager: WebhookManager;@@ -74,7 +75,7 @@ describe("signed GitHub webhook ingress", () => {it.each(["", "sha1=" + "a".repeat(40), "sha256=bad", "sha256=" + "0".repeat(64)])("rejects signature %j even with a bearer secret", async (value) => {expect((await send(body, { "x-hub-signature-256": value, authorization: `Bearer ${secret}` })).status).toBe(401);expect(queued).toHaveLength(0);- expect(manager.listAttempts()).toMatchObject([{ outcome: "rejected", statusCode: 401 }]);+ expect(manager.listAttempts()).toEqual([]);});it("rejects changed bodies and unknown endpoints before parsing JSON", async () => {@@ -136,4 +137,98 @@ describe("signed GitHub webhook ingress", () => {expect((await send()).status).toBe(401);expect(queued).toHaveLength(0);});++ async function seedAcceptedHistory() {+ expect((await send()).status).toBe(202);+ await new Promise<void>((resolve) => ingress.server.close(() => resolve()));+ const path = join(dir, "webhooks.json");+ const saved = JSON.parse(readFileSync(path, "utf8"));+ for (let i = 0; i < 1999; i++) {+ saved.attempts.push({ id: `seed-${i}`, webhookId: id, receivedAt: Date.now(), outcome: "rejected", statusCode: 429 });+ }+ writeFileSync(path, JSON.stringify(saved));+ manager = loadManager();+ ingress = await listenWebhookIngress(manager, { port: 0 });+ return { path, before: readFileSync(path, "utf8"), attempts: manager.listAttempts() };+ }++ it.each(["", "sha256=bad", "sha256=" + "0".repeat(64)])("does not persist or evict accepted history for oversized bodies with signature %j", async (value) => {+ const { path, before, attempts } = await seedAcceptedHistory();+ for (let i = 0; i < 3; i++) {+ const response = await send("x".repeat(MAX_WEBHOOK_BODY_BYTES + 1), { "x-hub-signature-256": value });+ expect([401, 413]).toContain(response.status);+ await response.arrayBuffer();+ }+ expect(readFileSync(path, "utf8")).toBe(before);+ expect(manager.listAttempts()).toEqual(attempts);+ expect(queued).toHaveLength(1);+ expect(await (await send()).json()).toMatchObject({ duplicate: true, runId: "run-1" });+ });++ it.each(["", "sha256=" + "0".repeat(64)])("does not persist or evict accepted history for truncated bodies with signature %j", async (value) => {+ const { path, before, attempts } = await seedAcceptedHistory();+ await new Promise<void>((resolve, reject) => {+ const socket = createConnection(ingress.port, "127.0.0.1", () => socket.end(+ `POST /hooks/${endpointId}/github HTTP/1.1\r\nHost: localhost\r\nX-GitHub-Event: pull_request\r\nX-GitHub-Delivery: truncated\r\nX-Hub-Signature-256: ${value}\r\nContent-Length: 1000\r\nConnection: close\r\n\r\n{`,+ ));+ socket.on("data", () => {});+ socket.on("error", reject);+ socket.on("close", () => resolve());+ });+ expect(readFileSync(path, "utf8")).toBe(before);+ expect(manager.listAttempts()).toEqual(attempts);+ expect(queued).toHaveLength(1);+ });++ it("does not evict accepted history for unauthenticated malformed JSON", async () => {+ const { path, before, attempts } = await seedAcceptedHistory();+ expect((await send("{", { "x-hub-signature-256": signature(body) })).status).toBe(401);+ expect(readFileSync(path, "utf8")).toBe(before);+ expect(manager.listAttempts()).toEqual(attempts);+ });++ it("uses GitHub delivery metadata for authenticated parse rejections", async () => {+ expect((await send("{", { "idempotency-key": "wrong-generic-id", "x-webhook-id": "wrong-webhook-id", "x-github-delivery": "gh-parse-1" })).status).toBe(400);+ expect(manager.listAttempts()).toMatchObject([{ statusCode: 400, deliveryId: "gh-parse-1", eventName: "pull_request" }]);+ const response = await fetch(`${ingress.baseUrl}/hooks/${endpointId}`, {+ method: "POST",+ headers: { authorization: `Bearer ${secret}`, "content-type": "application/json", "idempotency-key": "generic-parse-1", "x-github-delivery": "gh-parse-2" },+ body: "{",+ });+ expect(response.status).toBe(400);+ expect(manager.listAttempts().at(-1)).toMatchObject({ statusCode: 400, deliveryId: "generic-parse-1" });+ });++ it.each(["legacy", "missing key", "corrupt seal"])("gives the owner a bounded recovery diagnostic for a %s secret", async (failure) => {+ await new Promise<void>((resolve) => ingress.server.close(() => resolve()));+ const path = join(dir, "webhooks.json");+ const saved = JSON.parse(readFileSync(path, "utf8"));+ if (failure === "legacy") delete saved.webhooks[0].sealedSecret;+ else if (failure === "missing key") rmSync(join(dir, WEBHOOK_KEY_FILE));+ else saved.webhooks[0].sealedSecret = "invalid";+ writeFileSync(path, JSON.stringify(saved));+ manager = loadManager();+ ingress = await listenWebhookIngress(manager, { port: 0 });+ const before = readFileSync(path, "utf8");+ for (let i = 0; i < 20; i++) {+ const response = await send();+ expect(response.status).toBe(401);+ expect(await response.text()).toBe('{"error":"Invalid webhook URL or secret"}');+ }+ const attempts = manager.listAttempts();+ expect(attempts).toHaveLength(1);+ expect(attempts[0]?.reason).toMatch(/replace.*address/i);+ expect(attempts[0]?.reason).toMatch(/GitHub.*Secret/);+ expect(attempts[0]?.reason).toContain("20 requests");+ expect(attempts[0]?.reason!.length).toBeLessThan(500);+ expect(JSON.stringify(attempts)).not.toContain(secret);+ expect(JSON.stringify(attempts)).not.toContain(saved.webhooks[0].secretHash);+ expect(readFileSync(path, "utf8")).toBe(before);+ expect(queued).toHaveLength(0);+ expect(manager.authorize(endpointId, secret)).toBe(true);+ const rotated = manager.rotateSecret(id)!;+ secret = rotated.secret;+ expect((await send()).status).toBe(202);+ });+});diff --git a/server/webhook-ingress.ts b/server/webhook-ingress.tsindex 0f01962ca2..69f1a818d8 100644--- a/server/webhook-ingress.ts+++ b/server/webhook-ingress.ts@@ -103,16 +103,26 @@ export function createWebhookIngressHandler(manager: WebhookManager, claimRequesif (!match) return json(res, 404, { error: "Unknown webhook endpoint" });if (req.method !== "POST") return json(res, 405, { error: "Webhooks accept POST requests" });+ const github = match[2] === "github";+ const metadata = {+ contentType: header(req, "content-type"),+ eventName: github ? header(req, "x-github-event")?.trim() : eventName(req),+ deliveryId: github ? header(req, "x-github-delivery")?.trim() : deliveryId(req),+ };+ let authenticated = false;let release: (() => void) | undefined;try {release = claimRequest?.();- const github = match[2] === "github";let secret = "";let raw: Buffer | undefined;+ let secretUnavailable = false;if (github) {- if (header(req, "x-github-delivery")?.trim() && header(req, "x-github-event")?.trim()) {+ const signature = header(req, "x-hub-signature-256");+ if (metadata.deliveryId && metadata.eventName && signature && /^sha256=[a-f0-9]{64}$/.test(signature)) {raw = await readRawBody(req);- secret = manager.githubSecret(match[1], header(req, "x-hub-signature-256"), raw) ?? "";+ const verified = manager.githubSecret(match[1], signature, raw);+ if (verified && "secret" in verified) secret = verified.secret;+ secretUnavailable = Boolean(verified && "unavailable" in verified);}} else {try {@@ -121,34 +131,26 @@ export function createWebhookIngressHandler(manager: WebhookManager, claimReques}}if (!manager.authorize(match[1], secret)) {- manager.recordUnauthorized(match[1], {- contentType: header(req, "content-type"),- eventName: github ? header(req, "x-github-event") : eventName(req),- deliveryId: github ? header(req, "x-github-delivery") : deliveryId(req),- });+ if (!github || secretUnavailable) manager.recordUnauthorized(match[1], metadata, secretUnavailable);return json(res, 401, { error: "Invalid webhook URL or secret" });}+ authenticated = true;raw ??= await readRawBody(req);const contentType = header(req, "content-type")?.split(";")[0]?.trim().toLowerCase() ?? "text/plain";const payload = parsePayload(raw.toString("utf8"), contentType);const result = await manager.receive(match[1], secret, {+ ...metadata,payload,contentType,- eventName: github ? header(req, "x-github-event")?.trim() : eventName(req),userAgent: header(req, "user-agent"),- deliveryId: github ? header(req, "x-github-delivery")?.trim() : deliveryId(req),});return json(res, 202, { accepted: true, ...result });} catch (error) {const parsedError = statusErrorSchema.safeParse(error);const status = parsedError.success ? parsedError.data.status ?? 500 : 500;const message = error instanceof Error ? error.message : String(error);- if (status === 400 || status === 413) {- manager.recordRejected(match[1], status, message, {- contentType: header(req, "content-type"),- eventName: eventName(req),- deliveryId: deliveryId(req),- });+ if (authenticated && (status === 400 || status === 413)) {+ manager.recordRejected(match[1], status, message, metadata);}return json(res, status, { error: message });} finally {diff --git a/server/webhooks.ts b/server/webhooks.tsindex 682260ce84..5347ff2e61 100644--- a/server/webhooks.ts+++ b/server/webhooks.ts@@ -564,13 +564,14 @@ export class WebhookManager {}/** The kept secret leaves this method only after GitHub's signature authenticates the raw request bytes. */- githubSecret(endpointId: string, signature: string | undefined, raw: Buffer): string | null {+ githubSecret(endpointId: string, signature: string | undefined, raw: Buffer): { secret: string } | { unavailable: true } | null {if (!signature || !/^sha256=[a-f0-9]{64}$/.test(signature)) return null;const trigger = this.webhooks.find((candidate) => candidate.endpointId === endpointId);- const secret = trigger && this.unseal(trigger);- if (!secret) return null;+ if (!trigger) return null;+ const secret = this.unseal(trigger);+ if (!secret) return { unavailable: true };const expected = createHmac("sha256", secret).update(raw).digest();- return timingSafeEqual(Buffer.from(signature.slice(7), "hex"), expected) ? secret : null;+ return timingSafeEqual(Buffer.from(signature.slice(7), "hex"), expected) ? { secret } : null;}receive(endpointId: string, secret: string, event: WebhookEvent): WebhookReceiveResult | Promise<WebhookReceiveResult> {@@ -725,10 +726,11 @@ export class WebhookManager {}/** Anyone who reaches the receiver can send a wrong secret: one rolling record per burst, saved with the next real change. */- recordUnauthorized(endpointId: string, event: Partial<WebhookEvent> = {}): WebhookAttempt | null {+ recordUnauthorized(endpointId: string, event: Partial<WebhookEvent> = {}, secretUnavailable = false): WebhookAttempt | null {const trigger = this.webhooks.find((candidate) => candidate.endpointId === endpointId);if (!trigger) return null;- const details = (count: number) => ({ outcome: "rejected" as const, statusCode: 401, reason: count > 1 ? `${UNAUTHORIZED_REASON} (${count} requests)` : UNAUTHORIZED_REASON, deliveryId: event.deliveryId });+ const reason = secretUnavailable ? "Replace this automation's address and update GitHub's Secret; the saved secret cannot be recovered." : UNAUTHORIZED_REASON;+ const details = (count: number) => ({ outcome: "rejected" as const, statusCode: 401, reason: count > 1 ? `${reason} (${count} requests)` : reason, deliveryId: event.deliveryId });const at = this.attempts.findLastIndex((attempt) => attempt.webhookId === trigger.id);const burst = at === -1 ? undefined : this.attempts[at]!;if (!burst || burst.outcome !== "rejected" || burst.statusCode !== 401 || this.now() - burst.receivedAt > UNAUTHORIZED_BURST_MS) {