diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index ff6ce27cc87..fe10f773b46 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -97,6 +97,7 @@ import { companyObservability } from "@paperclipai/db"; import * as runIdentityModule from "../services/run-identity.js"; import * as heartbeatModule from "../services/heartbeat.js"; import { chatGitHubRegistrations, chatGitHubReviews, chatGitHubConfigurations, toolCatalogEntries } from "@paperclipai/db"; +import { secretAccessEvents } from "@paperclipai/db"; import { AsyncLocalStorage } from "node:async_hooks"; import * as cloudRuntimeIdentity from "../services/cloud-runtime-identity.js"; import { @@ -6543,6 +6544,44 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { } } }); + it.each(["current", "invalid_signature"] as const)("resolves only the secrets a %s signed GitHub webhook delivery uses", async (kind) => { + const f = await reviewBotFixture(); + const [endpoint] = await readChatEndpointsById(f.endpoint.id); + const accessesBefore = new Set((await db.select({ id: secretAccessEvents.id }).from(secretAccessEvents) + .where(eq(secretAccessEvents.consumerId, endpoint.connectionId))).map(row => row.id)); + const delivery = randomUUID(); + const response = await f.service.handleWebhook(endpoint.publicId, "github", signedGitHubWebhookRequest({ + event: "issue_comment", delivery, webhookSecret: kind === "invalid_signature" ? "wrong-secret" : f.webhookSecret, + payload: { action: "created", installation: { id: 2468 }, + repository: { id: 97531, full_name: "paperclipai/paperclip", owner: { id: 1357, login: "paperclipai" } }, + issue: { number: 418 }, comment: { id: 41801, body: "Ordinary comment", user: { id: 42, login: "octocat" } }, sender: { id: 42, login: "octocat" } }, + })); + if (kind === "invalid_signature") expect(response.status).toBe(401); + else { + expect(response.status).toBeLessThan(300); + await expect.poll(async () => (await db.select({ status: chatActions.status }).from(chatActions).where(and( + eq(chatActions.endpointId, endpoint.id), eq(chatActions.providerActionId, `github_webhook_ingress:${delivery}`))))[0]?.status, + { timeout: 10_000 }).toBe("processed"); + } + const accesses = (await db.select({ id: secretAccessEvents.id, configPath: secretAccessEvents.configPath }).from(secretAccessEvents) + .where(eq(secretAccessEvents.consumerId, endpoint.connectionId))).filter(row => !accessesBefore.has(row.id)); + const reads: Record = {}; + for (const access of accesses) reads[access.configPath ?? "unknown"] = (reads[access.configPath ?? "unknown"] ?? 0) + 1; + // A delivery must never decrypt the App private key, OAuth client + // secret or other unused keys. Each step reads only what it uses: + // - durable staging verifies the provider signature (webhookSecret); + // once it holds, it rejects foreign installations (installationId) + // and scopes recovery-receipt denial to this App (appId); + // - the durable worker signs the retained body for internal replay + // (webhookSecret); + // - the replayed request re-authenticates under the credential lease + // against the current secret and installation (webhookSecret, + // installationId). + // A bad signature stops after the one webhookSecret read. + expect(reads).toEqual(kind === "invalid_signature" + ? { "credentials.webhookSecret": 1 } + : { "credentials.webhookSecret": 3, "credentials.installationId": 2, "credentials.appId": 1 }); + }); it("stack rejects forged raw gateway deliveries without changing verification or waking an agent", async () => { const f = await reviewBotFixture(); await db diff --git a/server/src/services/chat-channels/github/webhook-authentication.ts b/server/src/services/chat-channels/github/webhook-authentication.ts index d393306d084..ec94f94f416 100644 --- a/server/src/services/chat-channels/github/webhook-authentication.ts +++ b/server/src/services/chat-channels/github/webhook-authentication.ts @@ -117,7 +117,7 @@ export function createGitHubWebhookAuthentication(db: Db, options: Authenticatio ) ) return false; - const credentials = await resolveCredentials(current.endpoint); + const credentials = await resolveCredentials(current.endpoint, undefined, ["webhookSecret"]); const expected = `sha256=${createHmac("sha256", credentials.webhookSecret).update(body).digest("hex")}`; let valid = false; try { @@ -182,7 +182,9 @@ export function createGitHubWebhookAuthentication(db: Db, options: Authenticatio ) { return "ignored"; } - const credentials = await resolveCredentials(current.endpoint); + // Read only the signing secret until the signature holds; the bound + // installation is read below only for events that name one. + const credentials = await resolveCredentials(current.endpoint, undefined, ["webhookSecret"]); const expected = `sha256=${createHmac("sha256", credentials.webhookSecret).update(body).digest("hex")}`; let signatureValid = false; try { @@ -209,9 +211,13 @@ export function createGitHubWebhookAuthentication(db: Db, options: Authenticatio const lifecycleEvent = ["github_app_authorization", "installation", "installation_repositories"].includes(eventType ?? ""); if (payload) { const incomingInstallationId = payload.installation?.id; + const boundInstallationId = + incomingInstallationId !== undefined && eventType !== "installation" + ? (await resolveCredentials(current.endpoint, undefined, ["installationId"])).installationId + : undefined; if ( incomingInstallationId !== undefined && - String(incomingInstallationId) !== credentials.installationId && + String(incomingInstallationId) !== boundInstallationId && eventType !== "installation" ) { // A dedicated endpoint represents exactly one GitHub App @@ -231,7 +237,7 @@ export function createGitHubWebhookAuthentication(db: Db, options: Authenticatio if (!current.endpoint.setup.webhookVerifiedAt && ["active", "verifying", "attention"].includes(current.endpoint.status) && incomingInstallationId !== undefined && - String(incomingInstallationId) === credentials.installationId && + String(incomingInstallationId) === boundInstallationId && !lifecycleEvent) { await recordVerifiedWebhook(current.endpoint, credentialLease, inspection.headers.get("x-github-delivery")); } diff --git a/server/src/services/chat-channels/github/webhook-ingress.ts b/server/src/services/chat-channels/github/webhook-ingress.ts index e186b468a9a..1252528c7c6 100644 --- a/server/src/services/chat-channels/github/webhook-ingress.ts +++ b/server/src/services/chat-channels/github/webhook-ingress.ts @@ -133,6 +133,22 @@ export function githubWebhookIngressPayload( return payload as GitHubWebhookIngressPayload; } +/** + * Every resolved secret is a vault read plus an access-audit row, and a GitHub + * App connection stores seven of them. Webhook steps read only the keys they + * use; the App private key and OAuth client secret stay sealed on this path. + */ +export function githubCredentialRefsFor( + refs: ToolCredentialSecretRef[], + keys: readonly string[], +): ToolCredentialSecretRef[] { + return refs.filter((ref) => + keys.includes(ref.configPath.replace(/^credentials\./, "")), + ); +} + +const GITHUB_APP_TOKEN_KEYS = ["appId", "privateKey", "installationId"] as const; + export function redactedGitHubWebhookIngressPayload( payload: GitHubWebhookIngressPayload, ): RedactedGitHubWebhookIngressPayload { @@ -258,34 +274,31 @@ export function createGitHubWebhookIngress(db: Db, options: GitHubWebhookIngress return { kind: "ignored" }; } const context = runtimeContextForRecord(record); - let credentials: Record; - try { - credentials = await resolveCredentialRefs( - record.endpoint, - record.credentialSecretRefs, - ); - } catch (error) { + const credentialsSuperseded = async () => { const latest = await endpointRecord(endpoint.id); - if ( - latest && + return ( + latest !== null && (runtimeGeneration(latest.endpoint.setup) !== context.generation || credentialFingerprint(latest.credentialSecretRefs) !== context.credentialFingerprint) - ) { - continue; - } + ); + }; + const resolveKeys = (keys: readonly string[]) => + resolveCredentialRefs( + record.endpoint, + githubCredentialRefsFor(record.credentialSecretRefs, keys), + ); + let credentials: Record; + try { + // Unsigned or forged traffic must not decrypt anything beyond the + // signing secret. + credentials = await resolveKeys(["webhookSecret"]); + } catch (error) { + if (await credentialsSuperseded()) continue; throw error; } if (!githubSignatureIsValid(body, signature, credentials.webhookSecret)) { - const latest = await endpointRecord(endpoint.id); - if ( - latest && - (runtimeGeneration(latest.endpoint.setup) !== context.generation || - credentialFingerprint(latest.credentialSecretRefs) !== - context.credentialFingerprint) - ) { - continue; - } + if (await credentialsSuperseded()) continue; return { kind: "invalid_signature" }; } @@ -296,6 +309,21 @@ export function createGitHubWebhookIngress(db: Db, options: GitHubWebhookIngress ? (parsedPayload as { installation?: { id?: unknown } }).installation ?.id : undefined; + try { + // A signed event that names an installation is checked against the + // bound one; the App id scopes the recovery-receipt denial below. + Object.assign( + credentials, + await resolveKeys( + incomingInstallationId !== undefined && eventType !== "installation" + ? ["installationId", "appId"] + : ["appId"], + ), + ); + } catch (error) { + if (await credentialsSuperseded()) continue; + throw error; + } if ( incomingInstallationId !== undefined && String(incomingInstallationId) !== credentials.installationId && @@ -817,9 +845,11 @@ export function createGitHubWebhookIngress(db: Db, options: GitHubWebhookIngress } try { + // Replay re-signs the retained body for internal authentication. Only a + // recovered delivery also needs an App token to recheck its source. const credentials = await resolveCredentialRefs( record.endpoint, - record.credentialSecretRefs, + githubCredentialRefsFor(record.credentialSecretRefs, ["webhookSecret"]), ); const recovery = await db .select({ payload: chatActions.payload, status: chatActions.status }) @@ -840,7 +870,13 @@ export function createGitHubWebhookIngress(db: Db, options: GitHubWebhookIngress (recovery.status === "cancelled" || !(await githubRecoverySourceIsCurrent( (recovery.payload as GitHubRecoveryReceipt).original, - credentials, + await resolveCredentialRefs( + record.endpoint, + githubCredentialRefsFor( + record.credentialSecretRefs, + GITHUB_APP_TOKEN_KEYS, + ), + ), ))) ) { await settleGitHubWebhookIngress(action.id, { @@ -1217,7 +1253,10 @@ export function createGitHubWebhookIngress(db: Db, options: GitHubWebhookIngress } const credentials = await resolveCredentialRefs( record.endpoint, - record.credentialSecretRefs, + githubCredentialRefsFor( + record.credentialSecretRefs, + GITHUB_APP_TOKEN_KEYS, + ), ); if (credentials.appId !== window.appId || !credentials.installationId) return;