diff --git a/doc/connections/GITHUB.md b/doc/connections/GITHUB.md index 161b709d368..26160947646 100644 --- a/doc/connections/GITHUB.md +++ b/doc/connections/GITHUB.md @@ -137,7 +137,8 @@ and [workflow dispatch permissions](https://docs.github.com/en/rest/actions/work ## Webhooks -Paperclip Cloud verifies `X-Hub-Signature-256` against the exact bounded request +For the shared GitHub account connector, Paperclip Cloud verifies +`X-Hub-Signature-256` against the exact bounded request body before parsing, deduplicates by `X-GitHub-Delivery`, and persists a minimal normalized event before returning `202`. Raw webhook payloads are discarded. When registering an active binding, Paperclip sends the current user token only @@ -158,6 +159,35 @@ remove obsolete Cloud bindings. Activity records contain event identifiers and outcomes but no webhook content. GitHub webhook content is never first-party telemetry. +## Dedicated agent Apps + +The bot wizard uses Cloud gateway protocol version 2. The stack builds the +private manifest for a personal account or organization. GitHub still asks the +user to confirm creation and repository installation. The stack exchanges the +returned manifest code directly with GitHub and stores every App secret in its +vault, including the private key, client secret, and webhook verifier. + +Cloud stores only opaque, instance-bound callback routes and encrypted callback +claims. It does not exchange codes, track App or installation identity, store +GitHub secrets, or interpret bot events. It forwards original webhook bytes, +provider headers, and signature in an envelope sealed to the stack before +writing the inbox. The stack decrypts and authenticates those bytes through its +existing durable ingress. Only that local check can verify a connection or +admit work. Shared-App account connectors keep the behavior described above. + +Unverified gateway traffic has request, byte, pending-queue, retention and wake +limits. Its transport deduplication includes the body and signature, so a forged +request cannot occupy a real delivery's identifier. A ping received before its +verifier reaches the vault remains queued for retry. Malformed and forged +traffic is discarded after local verification. Installation returns only request +a state refresh; the stack queries GitHub to establish installation authority. + +OAuth state, PKCE, consent, repository discovery, recovery and lifecycle changes +also stay in the stack. Interrupted single-use manifest exchanges require +recovery of the existing App instead of a second creation. Direct webhook and +manual existing-App recovery remain available. Connecting does not prove that +an agent runtime can execute a review. + ## Run projection The resolved token is leased at run start as an audited class-3 secret and is diff --git a/doc/plans/2026-10-06-github-app-wizard.md b/doc/plans/2026-10-06-github-app-wizard.md index 54774d24ee1..aaec161787f 100644 --- a/doc/plans/2026-10-06-github-app-wizard.md +++ b/doc/plans/2026-10-06-github-app-wizard.md @@ -62,25 +62,34 @@ new App's OAuth flow, separate from its installation callback, with bound state, PKCE, one explicit identity confirmation, and transient user tokens. All bot execution continues through installation credentials. -Re-enter the existing durable webhook admission/review path from an -independently bounded, authenticated Cloud event. Preserve resource access, +Decrypt original provider webhook bytes from the bounded Cloud gateway queue. +Authenticate their original signature in the stack before entering the existing +durable webhook admission/review path. Preserve resource access, trust boundaries, revocation handling, and duplicate protection. ### Paperclip Cloud -Extend the existing connector broker, durable registry, enrollment, signed -requests, sealed claims, secret store, webhook inbox, event leases and acks, -and coalesced Cloud stack wakes. No per-user tunnel or separate relay service. +Use the existing connector broker, durable registry, enrollment, signed +requests, sealed claims, webhook inbox, event leases and acknowledgments, and +coalesced stack wakes as a transport gateway. No per-user tunnel is needed. -Add dedicated App registrations with compare-and-swap progress, per-App -webhook secrets, fixed provider URLs, distinct public manifest/install/OAuth -callbacks, and normalized bot events. Store only the webhook verification -secret in Cloud's secret store; seal private keys and OAuth client credentials -to the enrolled instance. Installation query parameters are hints, never proof. +The stack builds manifests, exchanges manifest codes directly with GitHub, +vaults every App secret, and owns OAuth state, PKCE, installation verification, +repository access, event interpretation and recovery. Cloud stores opaque routes +and hashes of callback state. It seals callback codes and original webhook bytes +to the enrolled stack before durable storage. It keeps no GitHub private key, +client secret or webhook verifier for dedicated Apps. -The additive capability is controlled by `CLOUD_HARNESS_GITHUB_APPS_ENABLED=1`. -Production requires the durable provider secret store. Deploy the additive -Cloud migration/capability before enabling the synchronized instance wizard. +Cloud provides separate public manifest/install/OAuth callback URLs. Installation +parameters never prove ownership. The stack authenticates the original webhook +signature. Cloud applies bounded ingress, queue and wake limits to unverified +traffic. Deduplication includes the original body and signature to prevent forged +delivery identifiers from suppressing valid events. + +The additive capability is controlled by `CLOUD_HARNESS_GITHUB_APPS_ENABLED=1` +and advertises version 2. Deploy the additive Cloud migration and gateway before +the synchronized instance wizard. Existing shared-App account connections keep +their provider-specific broker behavior and secret-store requirements. ## Qualification @@ -127,12 +136,22 @@ imports resume those defaults while explicit restrictions stay preserved. A real vault-write interruption stays in recovery without completing an empty import; retrying the credentials discovers and imports the actual repositories. -Cloud's final standard `npm test` passes: 2,561 tests and 73 environment-dependent -skips. Dedicated-App regressions cover normalized concurrent starts, stale -installation redeliveries, atomic inbox/state transitions, current enrolled -callback destinations after old hosts stop resolving, PKCE consent and denial, expired claims, and webhook -secret retirement with nonblocking cleanup, including overlapping repairs. The Postgres concurrency case requires a disposable -database and was not run here. +The earlier Cloud qualification tested a Cloud-owned App lifecycle. The +2026-10-07 architecture revision replaces that lifecycle with the gateway +boundary described above. Its standard `npm test` passes: 2,552 tests and 73 +conditional skips. Gateway regressions verify sealed callback and webhook +storage, route/tenant binding, removed instances, renamed origins, forged +identifier suppression, lease/acknowledgment and queue limits. Cloud typecheck +and routing/sleep/wake smoke checks pass. + +The revised stack passes workspace typecheck and build. Focused tests cover +local manifest exchange, interrupted vault storage without repeated exchange, +secret rotation without disclosing it to Cloud, original-signature verification, +and nested-envelope binding. A subsequent database run is blocked by the host's +exhausted shared-memory identifiers (`shmget`: No space left on device), including +the disposable Cloud Postgres concurrency qualification. These skipped or blocked +runs do not establish database qualification. The new PR heads require fresh CI +and review. No real provider calls or deployments were used for this revision. Before rollout, apply the additive Cloud migration, enable the dedicated-App capability, then deploy the synchronized instance migration and wizard through diff --git a/packages/db/src/schema/chat_github.ts b/packages/db/src/schema/chat_github.ts index 2faa2b715ad..1ca66d33942 100644 --- a/packages/db/src/schema/chat_github.ts +++ b/packages/db/src/schema/chat_github.ts @@ -71,6 +71,7 @@ export const chatGitHubRegistrations = pgTable( redemptionId: string; returnState: string; webhookSecretHash?: string; + manifestClaimId?: string; identityLeaseId?: string; identityLeaseExpiresAt?: string; identityStateHash?: string; diff --git a/packages/shared/src/types/github-app-setup.ts b/packages/shared/src/types/github-app-setup.ts index e202086f6d7..2fa15557cf1 100644 --- a/packages/shared/src/types/github-app-setup.ts +++ b/packages/shared/src/types/github-app-setup.ts @@ -3,22 +3,13 @@ export type GitHubAppOwner = { ownerLogin?: string; }; export type GitHubAppRegistrationInput = GitHubAppOwner & { name: string }; -export type GitHubAppCloudState = GitHubAppOwner & { +/** Redacted transport route; GitHub setup state belongs to the instance. */ +export type GitHubAppCloudState = { id: string; - returnOrigin?: string; - status: "pending" | "exchanging" | "credentials" | "installed" | "failed"; + returnOrigin: string; expiresAt: string; - appId?: string; - slug?: string; - claimId?: string; - claimExpired?: boolean; - registrationUrl?: string; - manifest?: Record; - webhookUrl?: string; - installationUrl?: string; - installationId?: string; - signedDeliveryAt?: string; - authorizationUrl?: string; + webhookUrl: string; + callbackUrls: { manifest: string; install: string; oauth: string }; }; export type GitHubAppWizardState = { endpointId: string; diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index f4d91de479e..a3711ea5b57 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -2212,13 +2212,14 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { } return { id: binding.id, - status: "pending", + returnOrigin: "http://127.0.0.1:3104", expiresAt: new Date(Date.now() + 60_000).toISOString(), - registrationUrl: - ownerType === "personal" - ? "https://github.com/settings/apps/new" - : "https://github.com/organizations/acme/settings/apps/new", - manifest: { public: false }, + webhookUrl: "https://gateway.example.test/webhook", + callbackUrls: { + manifest: "https://gateway.example.test/manifest", + install: "https://gateway.example.test/install", + oauth: "https://gateway.example.test/oauth", + }, }; }, ); @@ -2255,11 +2256,19 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { expect(sessions).toHaveLength(1); expect(sessions[0].ownerType).toBe(ownerType); expect(cloudRecord).toMatchObject({ - endpointId: bot.id, - connectionId: bot.connectionId, - agentId: bot.assignedAgentId, returnUri: "http://127.0.0.1:3104/api/chat-github/cloud/callback", }); + expect(cloudRecord).not.toHaveProperty("ownerType"); + expect(cloudRecord).not.toHaveProperty("agentId"); + expect(resumed.registration?.manifest).toMatchObject({ + name: "My Reviewer", + public: false, + }); + expect(resumed.registration?.registrationUrl).toContain( + ownerType === "organization" + ? "/organizations/acme/settings/apps/new" + : "/settings/apps/new", + ); await expect( wizard.saveDraft(bot.id, "owner-user", { ...input, @@ -2274,90 +2283,9 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { expect(current.assignedAgentId).toBe(f.assignedAgentId); }, ); - it("wizard resumes the same sealed claim after App identity was saved but vault storage was interrupted", async () => { - const f = await seedCompany(); - const { service } = createService(); - const bot = await service.create( - f.companyId, - { provider: "github", assignedAgentId: f.assignedAgentId }, - "owner-user", - ); - await db.insert(chatGitHubRegistrations).values({ - companyId: f.companyId, - endpointId: bot.id, - userId: "owner-user", - stateHash: randomUUID(), - trustedOrigin: "http://127.0.0.1:3104", - ownerType: "personal", - status: "exchanging", - expiresAt: new Date(Date.now() + 60_000), - handoff: { - cloudId: "claim-recovery", - returnState: "bound", - redemptionId: "same-receipt", - }, - }); - const claimGitHubApp = vi.fn(async () => ({ - kind: "github_app", - registrationId: "claim-recovery", - endpointId: bot.id, - connectionId: bot.connectionId, - agentId: bot.assignedAgentId, - appId: "1234", - privateKey: "test-key", - webhookSecret: "test-webhook-secret", - clientId: "test-client", - clientSecret: "test-client-secret", - })); - const storeApp = vi.fn(async () => { - await db - .update(chatEndpoints) - .set({ botExternalId: "1234" }) - .where(eq(chatEndpoints.id, bot.id)); - throw new Error("Vault storage interrupted"); - }); - const createWizard = () => - githubChatWizardService(db, { - origin: () => "http://127.0.0.1:3104", - connector: () => - ({ - githubApp: async () => ({ - id: "claim-recovery", - appId: "1234", - claimId: "same-claim", - status: "credentials", - expiresAt: new Date(Date.now() + 60_000).toISOString(), - }), - claimGitHubApp, - }) as unknown as PaperclipCloudConnector, - startDirect: service.startGitHubRegistration, - storeApp, - storeCredentials: async () => {}, - refreshRepositories: service.refreshGitHubRepositories, - resources: service.listResources, - replaceResources: service.replaceResources, - configure: async () => {}, - finish: async () => {}, - }); - await expect(createWizard().advance(bot.id, "owner-user")).rejects.toThrow( - "Vault storage interrupted", - ); - await expect(createWizard().advance(bot.id, "owner-user")).rejects.toThrow( - "Vault storage interrupted", - ); - expect(storeApp).toHaveBeenCalledTimes(2); - expect(claimGitHubApp).toHaveBeenCalledTimes(2); - expect(claimGitHubApp.mock.calls[0]).toEqual(claimGitHubApp.mock.calls[1]); - expect( - await db - .select() - .from(chatGitHubRegistrations) - .where(eq(chatGitHubRegistrations.endpointId, bot.id)), - ).toHaveLength(1); - }); - it("wizard recovers a renamed enrolled origin only after checking bound state and Cloud authority", async () => { - const f = await seedCompany(); - const { service } = createService(); + it("stack exchanges a callback code only once when vault storage is interrupted", async () => { + const f = await seedCompany(), + { service } = createService(); const bot = await service.create( f.companyId, { provider: "github", assignedAgentId: f.assignedAgentId }, @@ -2369,28 +2297,123 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { companyId: f.companyId, endpointId: bot.id, userId: "owner-user", - stateHash: createHash("sha256").update("bound-state").digest("hex"), - trustedOrigin: "https://old.example.test", + stateHash: createHash("sha256").update("bound").digest("hex"), + trustedOrigin: "http://127.0.0.1:3104", + ownerType: "personal", status: "pending", - expiresAt: new Date(Date.now() + 60_000), + expiresAt: new Date(Date.now() + 60000), handoff: { - cloudId: "origin-recovery", - returnState: "bound-state", + cloudId: "claim-recovery", + returnState: "bound", redemptionId: "same-receipt", + manifestClaimId: "same-claim", }, }); + const claimGitHubApp = vi.fn(async () => ({ + kind: "gateway_callback", + callbackKind: "manifest", + state: "bound", + code: "code", + registrationId: "claim-recovery", + })); + const exchange = vi.fn(async (url: string | URL | Request) => { + expect(String(url)).toBe( + "https://api.github.com/app-manifests/code/conversions", + ); + return Response.json({ + id: 1234, + pem: "test-key", + webhook_secret: "test-webhook-secret", + client_id: "test-client", + client_secret: "test-client-secret", + slug: "my-agent", + owner: { type: "User", login: "octocat" }, + }); + }); + const storeApp = vi.fn(async () => { + await db + .update(chatEndpoints) + .set({ botExternalId: "1234" }) + .where(eq(chatEndpoints.id, bot.id)); + throw new Error("Vault storage interrupted"); + }); + const createWizard = () => + githubChatWizardService(db, { + origin: () => "http://127.0.0.1:3104", + fetch: exchange as typeof fetch, + connector: () => + ({ + githubApp: async () => ({ id: "claim-recovery" }), + claimGitHubApp, + }) as unknown as PaperclipCloudConnector, + startDirect: service.startGitHubRegistration, + storeApp, + storeCredentials: async () => {}, + refreshRepositories: service.refreshGitHubRepositories, + resources: service.listResources, + replaceResources: service.replaceResources, + configure: async () => {}, + finish: async () => {}, + }); + await expect( + createWizard().advance(bot.id, "owner-user"), + ).rejects.toThrow("Vault storage interrupted"); + expect(await createWizard().advance(bot.id, "owner-user")).toMatchObject({ + state: "recovery", + }); + expect(exchange).toHaveBeenCalledTimes(1); + expect(storeApp).toHaveBeenCalledTimes(1); + expect(claimGitHubApp).toHaveBeenCalledTimes(1); + const [session] = await db + .select() + .from(chatGitHubRegistrations) + .where(eq(chatGitHubRegistrations.endpointId, bot.id)); + expect(session.status).toBe("failed"); + }); + it("wizard recovers a renamed enrolled origin only after checking bound state and Cloud authority", async () => { + const f = await seedCompany(); + const { service } = createService(); + const bot = await service.create( + f.companyId, + { provider: "github", assignedAgentId: f.assignedAgentId }, + "owner-user", + ); + await db.insert(chatGitHubRegistrations).values({ + companyId: f.companyId, + endpointId: bot.id, + userId: "owner-user", + stateHash: createHash("sha256").update("bound-state").digest("hex"), + trustedOrigin: "https://old.example.test", + status: "pending", + expiresAt: new Date(Date.now() + 60_000), + handoff: { + cloudId: "origin-recovery", + returnState: "bound-state", + redemptionId: "same-receipt", + }, + }); let enrolledOrigin = "https://wrong.example.test"; const githubApp = vi.fn(async () => ({ id: "origin-recovery", - status: "pending", returnOrigin: enrolledOrigin, - registrationUrl: "https://github.com/settings/apps/new", - manifest: { public: false }, - expiresAt: new Date(Date.now() + 60_000).toISOString(), + expiresAt: new Date(Date.now() + 60000).toISOString(), + webhookUrl: "https://gateway.example.test/webhook", + callbackUrls: { + manifest: "https://gateway.example.test/manifest", + install: "https://gateway.example.test/install", + oauth: "https://gateway.example.test/oauth", + }, + })); + const claimGitHubApp = vi.fn(async () => ({ + kind: "gateway_callback", + registrationId: "origin-recovery", + callbackKind: "manifest", + state: "bound-state", })); const wizard = githubChatWizardService(db, { origin: () => "https://new.example.test", - connector: () => ({ githubApp }) as unknown as PaperclipCloudConnector, + connector: () => + ({ githubApp, claimGitHubApp }) as unknown as PaperclipCloudConnector, startDirect: service.startGitHubRegistration, storeApp: service.storeGitHubApp, storeCredentials: async () => {}, @@ -2401,15 +2424,21 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { finish: async () => {}, }); await expect( - wizard.cloudCallback("unbound-state", "origin-recovery"), + wizard.cloudCallback("unbound-state", "origin-recovery", "claim"), ).rejects.toThrow("did not match"); expect(githubApp).not.toHaveBeenCalled(); await expect( - wizard.cloudCallback("bound-state", "origin-recovery"), + wizard.cloudCallback("bound-state", "origin-recovery", "claim"), ).rejects.toThrow("did not match"); enrolledOrigin = "https://new.example.test"; + claimGitHubApp.mockImplementation(async () => ({ + kind: "gateway_callback", + registrationId: "origin-recovery", + callbackKind: "install", + state: "bound-state", + })); expect( - await wizard.cloudCallback("bound-state", "origin-recovery"), + await wizard.cloudCallback("bound-state", "origin-recovery", "claim"), ).toContain("https://new.example.test/"); const [session] = await db .select() @@ -2528,9 +2557,9 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { configure: async () => {}, finish: async () => {}, }); - await expect(wizard.repairCloud(bot.id, "unrelated-user")).rejects.toThrow( - "active company manager", - ); + await expect( + wizard.repairCloud(bot.id, "unrelated-user"), + ).rejects.toThrow("active company manager"); const before = await context.service.listResources(bot.id); await wizard.repairCloud(bot.id, "owner-user"); const current = await context.service.get(bot.id); @@ -2547,12 +2576,19 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { expect(session.handoff?.webhookSecretHash).toMatch(/^[a-f0-9]{64}$/); await context.service.generateSetupSecret(bot.id, "owner-user"); await wizard.repairCloud(bot.id, "owner-user"); - const repairCalls = githubApp.mock.calls.filter( - ([input]) => input.binding.action === "repair", + expect(githubApp).toHaveBeenCalledTimes(2); + for (const [request] of githubApp.mock.calls) { + expect(request.binding).not.toHaveProperty("webhookSecret"); + expect(request.binding).not.toHaveProperty("appToken"); + } + const repairs = providerFetch.mock.calls.filter( + ([url, init]) => + String(url) === "https://api.github.com/app/hook/config" && + init?.method === "PATCH", ); - expect(repairCalls).toHaveLength(2); - expect(repairCalls[0][0].binding.webhookSecret).not.toBe( - repairCalls[1][0].binding.webhookSecret, + expect(repairs).toHaveLength(2); + expect(JSON.parse(String(repairs[0][1]?.body)).secret).not.toBe( + JSON.parse(String(repairs[1][1]?.body)).secret, ); expect((await context.service.get(bot.id)).status).toBe("attention"); }); @@ -2999,42 +3035,55 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { expect((await context.service.listResources(context.endpoint.id)).every(resource => !resource.enabled)).toBe(true); expect(await management.configuration(context.endpoint.id, "owner-user")).toMatchObject({ revision: 1, configuration: { toolsEnabled: false } }); }); - it("Cloud bot delivery cannot enter another company's endpoint or a different agent binding", async () => { + it("stack rejects forged raw gateway deliveries without changing verification or waking an agent", async () => { const f = await reviewBotFixture(); - const event = { - id: "event-a", - provider: "github" as const, - event: "issue_comment", - action: "created", - installationId: "2468", - repositoryId: "97531", - createdAt: new Date().toISOString(), - bindingIds: ["github-app:registration-a"], - payload: { - githubApp: { - endpointId: f.endpoint.id, - companyId: f.companyId, - registrationId: "registration-a", - connectionId: f.endpoint.connectionId, - agentId: "different-agent", - appId: f.endpoint.botExternalId, - deliveryId: "delivery-123", - body: {}, - }, - }, - }; await db .update(chatEndpoints) .set({ setup: { ...f.endpoint.setup, + webhookVerifiedAt: null, github: { cloudRegistrationId: "registration-a" }, }, }) .where(eq(chatEndpoints.id, f.endpoint.id)); - await expect(dispatchGitHubBotCloudEvent(db, event)).rejects.toThrow( - "does not belong", - ); + const body = JSON.stringify({ zen: "forged-ping" }); + const event = { + id: "transport-event", + provider: "github" as const, + event: "gateway_delivery", + action: null, + installationId: null, + repositoryId: null, + createdAt: new Date().toISOString(), + bindingIds: ["github-app:registration-a"], + payload: { + githubApp: { + registrationId: "registration-a", + rawBody: Buffer.from(body).toString("base64"), + headers: { + "x-github-event": "ping", + "x-github-delivery": "provider-delivery", + "x-hub-signature-256": `sha256=${createHmac("sha256", "wrong-secret").update(body).digest("hex")}`, + }, + }, + }, + }; + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, f.endpoint.connectionId)); + await db.update(toolConnections).set({credentialSecretRefs: connection.credentialSecretRefs.filter(ref => ref.configPath !== "credentials.webhookSecret")}).where(eq(toolConnections.id, connection.id)); + await expect(dispatchGitHubBotCloudEvent(db, event)).rejects.toThrow("credentials are not ready"); + await db.update(toolConnections).set({credentialSecretRefs: connection.credentialSecretRefs}).where(eq(toolConnections.id, connection.id)); + expect(await dispatchGitHubBotCloudEvent(db, event)).toBe(true); + expect( + (await f.service.get(f.endpoint.id)).setup.webhookVerifiedAt, + ).toBeNull(); + expect(f.wakeup).not.toHaveBeenCalled(); + event.payload.githubApp.headers["x-hub-signature-256"] = + `sha256=${createHmac("sha256", f.webhookSecret).update(body).digest("hex")}`; + expect(await dispatchGitHubBotCloudEvent(db, event)).toBe(true); + expect( + (await f.service.get(f.endpoint.id)).setup.webhookVerifiedAt, + ).toBeTruthy(); expect(f.wakeup).not.toHaveBeenCalled(); }); it("legacy name-only registration preserves an explicit empty repository selection", async () => { diff --git a/server/src/services/chat-channels.ts b/server/src/services/chat-channels.ts index 824be5ceb50..84623dd1be5 100644 --- a/server/src/services/chat-channels.ts +++ b/server/src/services/chat-channels.ts @@ -38312,20 +38312,35 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { }, finish: (id, userId) => test(id, { optionalSlackTestForUser: userId }), }); - const unregisterGitHubCloudIngress = registerGitHubBotCloudIngress(db, async (endpoint, event, body) => { - const record = await endpointRecord(endpoint.id); - if (!record || record.endpoint.companyId !== endpoint.companyId || record.endpoint.connectionId !== endpoint.connectionId - || record.endpoint.assignedAgentId !== endpoint.assignedAgentId || record.endpoint.setup.github?.cloudRegistrationId !== endpoint.setup.github?.cloudRegistrationId) throw forbidden("GitHub Cloud event binding changed"); - const credentials = await resolveCredentials(record.endpoint); - // Cloud authenticated the provider's original bytes. Re-enter the canonical - // durable ingress with a local authenticator over the bounded normalized payload. - const normalized = JSON.stringify(body); - const response = await handleWebhook(record.endpoint.publicId, "github", new Request("https://paperclip.invalid/github-cloud-ingress", { - method: "POST", headers: { "content-type": "application/json", "x-github-event": event.event, - "x-github-delivery": event.deliveryId, "x-hub-signature-256": `sha256=${createHmac("sha256", credentials.webhookSecret).update(normalized).digest("hex")}` }, body: normalized, - })); - if (!response.ok) throw conflict("GitHub Cloud ingress could not be durably accepted"); - }); + const unregisterGitHubCloudIngress = registerGitHubBotCloudIngress( + db, + async (endpoint, request) => { + const record = await endpointRecord(endpoint.id); + if ( + !record || + record.endpoint.companyId !== endpoint.companyId || + record.endpoint.connectionId !== endpoint.connectionId || + record.endpoint.assignedAgentId !== endpoint.assignedAgentId || + record.endpoint.setup.github?.cloudRegistrationId !== + endpoint.setup.github?.cloudRegistrationId + ) + throw forbidden("GitHub Cloud event binding changed"); + // A manifest ping may arrive before its webhook verifier reaches the vault. + // Keep the sealed delivery queued until the stack can authenticate it. + if (!record.credentialSecretRefs.some((ref) => ref.configPath === "credentials.webhookSecret")) + throw conflict("GitHub webhook credentials are not ready"); + // Preserve the exact provider payload and signature. Authentication, lifecycle + // checks and durable admission all run in the stack's canonical ingress. + const response = await handleWebhook( + record.endpoint.publicId, + "github", + request, + ); + if ([400, 401, 403, 404, 413, 422].includes(response.status)) return; // Discard hostile transport without retrying it indefinitely. + if (!response.ok) + throw conflict("GitHub Cloud ingress could not be durably accepted"); + }, + ); const unregisterSlackTaskAuthority = registerSlackTaskAuthority(db, async (binding) => { if (!(await instanceSettingsService(db).getExperimental()).enableChatConnectors) diff --git a/server/src/services/chat-github-cloud-ingress.ts b/server/src/services/chat-github-cloud-ingress.ts index b386f5ccb11..b1493d64779 100644 --- a/server/src/services/chat-github-cloud-ingress.ts +++ b/server/src/services/chat-github-cloud-ingress.ts @@ -1,17 +1,11 @@ -import { normalizeGitHubBotCloudPayload } from "./chat-github-cloud-payload.js"; import type { Db, chatEndpoints } from "@paperclipai/db"; import { chatEndpoints as endpoints } from "@paperclipai/db"; -import { and, eq } from "drizzle-orm"; -import { forbidden } from "../errors.js"; +import { and, eq, sql } from "drizzle-orm"; import type { SealedConnectorEvents } from "./paperclip-cloud-connector.js"; type Event = SealedConnectorEvents["events"][number]; type Endpoint = typeof chatEndpoints.$inferSelect; -type Handler = ( - endpoint: Endpoint, - event: { event: string; deliveryId: string }, - body: Record, -) => Promise; +type Handler = (endpoint: Endpoint, request: Request) => Promise; const handlers = new WeakMap(); export function registerGitHubBotCloudIngress(db: Db, handler: Handler) { handlers.set(db, handler); @@ -19,7 +13,7 @@ export function registerGitHubBotCloudIngress(db: Db, handler: Handler) { if (handlers.get(db) === handler) handlers.delete(db); }; } -/** Called only for an authenticated, decrypted broker lease, never from a board request body. */ +/** Cloud proves transport ownership only. The canonical stack ingress authenticates GitHub's original bytes. */ export async function dispatchGitHubBotCloudEvent( db: Db, event: Event, @@ -28,54 +22,55 @@ export async function dispatchGitHubBotCloudEvent( if (!value || typeof value !== "object" || Array.isArray(value)) return false; const packet = value as Record; if ( - typeof packet.endpointId !== "string" || - typeof packet.companyId !== "string" || typeof packet.registrationId !== "string" || - typeof packet.deliveryId !== "string" || - !/^[A-Za-z0-9_-]{8,200}$/.test(packet.deliveryId) || !event.bindingIds.includes(`github-app:${packet.registrationId}`) || - !packet.body || - typeof packet.body !== "object" || - Array.isArray(packet.body) || - JSON.stringify(packet.body).length > 1_048_576 + typeof packet.rawBody !== "string" || + packet.rawBody.length > 1_398_104 || + !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test( + packet.rawBody, + ) || + !packet.headers || + typeof packet.headers !== "object" || + Array.isArray(packet.headers) ) - throw forbidden("Invalid GitHub Cloud event"); + return true; + const headers = packet.headers as Record; + if ( + !["x-github-event", "x-github-delivery", "x-hub-signature-256"].every( + (key) => typeof headers[key] === "string" && headers[key].length <= 200, + ) + ) + return true; const [endpoint] = await db .select() .from(endpoints) .where( and( - eq(endpoints.companyId, packet.companyId), - eq(endpoints.id, packet.endpointId), eq(endpoints.provider, "github"), + sql`${endpoints.setup}->'github'->>'cloudRegistrationId' = ${packet.registrationId}`, ), - ); - if (!endpoint || endpoint.status === "archived") return true; + ) + .limit(1); if ( - endpoint.connectionId !== packet.connectionId || - endpoint.assignedAgentId !== packet.agentId || - endpoint.botExternalId !== packet.appId || - endpoint.setup.github?.cloudRegistrationId !== packet.registrationId + !endpoint || + ["archived", "paused"].includes(endpoint.status) || + (endpoint.status === "revoked" && headers["x-github-event"] !== "installation") ) - throw forbidden("GitHub Cloud event does not belong to this bot"); - if ( - ![ - "ping", - "issue_comment", - "pull_request_review_comment", - "pull_request", - "installation", - "installation_repositories", - "github_app_authorization", - ].includes(event.event) - ) - throw forbidden("Unsupported GitHub Cloud event"); + return true; const handler = handlers.get(db); if (!handler) throw new Error("GitHub bot Cloud ingress is not ready"); await handler( endpoint, - { event: event.event, deliveryId: packet.deliveryId }, - normalizeGitHubBotCloudPayload(packet.body as Record), + new Request("https://paperclip.invalid/github-cloud-ingress", { + method: "POST", + headers: { + "content-type": "application/json", + "x-github-event": headers["x-github-event"] as string, + "x-github-delivery": headers["x-github-delivery"] as string, + "x-hub-signature-256": headers["x-hub-signature-256"] as string, + }, + body: new Uint8Array(Buffer.from(packet.rawBody, "base64")), + }), ); return true; } diff --git a/server/src/services/chat-github-cloud-payload.ts b/server/src/services/chat-github-cloud-payload.ts deleted file mode 100644 index 65abd7db540..00000000000 --- a/server/src/services/chat-github-cloud-payload.ts +++ /dev/null @@ -1,100 +0,0 @@ -const record = (value: unknown): Record => - value && typeof value === "object" && !Array.isArray(value) - ? (value as Record) - : {}; - -/** Explicit, bounded provider fields; never persist the original webhook body. */ -export function normalizeGitHubBotCloudPayload( - body: Record, -): Record { - const schemas: Record = { - action: 100, - before: 64, - zen: 300, - sender: { id: true, login: 100, type: 40 }, - repository: { - id: true, - full_name: 300, - name: 100, - owner: { id: true, login: 100, type: 40 }, - }, - installation: { - id: true, - app_id: true, - account: { id: true, login: 100, type: 40 }, - repository_selection: 40, - }, - issue: { - id: true, - number: true, - title: 1_000, - body: 24_000, - html_url: 2_000, - user: { id: true, login: 100, type: 40 }, - pull_request: { url: 2_000, html_url: 2_000 }, - }, - comment: { - id: true, - body: 24_000, - html_url: 2_000, - created_at: 100, - updated_at: 100, - user: { id: true, login: 100, type: 40 }, - in_reply_to_id: true, - path: 1_000, - line: true, - original_line: true, - diff_hunk: 8_000, - }, - pull_request: { - id: true, - number: true, - title: 1_000, - body: 24_000, - html_url: 2_000, - state: 40, - draft: true, - merged: true, - merged_at: 100, - updated_at: 100, - user: { id: true, login: 100, type: 40 }, - head: { sha: 64, ref: 300 }, - base: { sha: 64, ref: 300 }, - labels: [{ name: 100 }], - }, - repositories_added: [{ id: true, full_name: 300, name: 100 }], - repositories_removed: [{ id: true, full_name: 300, name: 100 }], - repositories: [{ id: true, full_name: 300, name: 100 }], - }; - function select(value: unknown, shape: unknown): unknown { - if (shape === true) - return typeof value === "boolean" || - (typeof value === "number" && Number.isSafeInteger(value)) || - (typeof value === "string" && /^[1-9][0-9]{0,30}$/.test(value)) - ? value - : undefined; - if (typeof shape === "number") - return value === null - ? null - : typeof value === "string" - ? value.slice(0, shape) - : undefined; - if (Array.isArray(shape)) - return Array.isArray(value) - ? value - .slice(0, 1_000) - .map((item) => select(item, shape[0])) - .filter((item) => item !== undefined) - : undefined; - if (!value || typeof value !== "object" || Array.isArray(value)) - return undefined; - const source = record(value); - const output: Record = {}; - for (const [key, child] of Object.entries(record(shape))) { - const result = select(source[key], child); - if (result !== undefined) output[key] = result; - } - return output; - } - return record(select(body, schemas)); -} diff --git a/server/src/services/chat-github-wizard.ts b/server/src/services/chat-github-wizard.ts index a3f5147acbe..d9d43defb34 100644 --- a/server/src/services/chat-github-wizard.ts +++ b/server/src/services/chat-github-wizard.ts @@ -13,6 +13,7 @@ import { import type { GitHubAppRegistrationInput, GitHubAppWizardState, + GitHubAppCloudState, } from "@paperclipai/shared"; import { badRequest, conflict, forbidden, notFound } from "../errors.js"; import { logActivity } from "./activity-log.js"; @@ -303,39 +304,167 @@ export function githubChatWizardService( const state = await cloud.githubApp({ subject: userId, companyId: bot.companyId, - binding: cloudStart(bot, session), + binding: cloudStart(session), }); - if (!state.registrationUrl || !state.manifest) - throw conflict( - "GitHub App registration could not be prepared. Resume the existing draft.", - ); return { endpointId: id, state: "create", - registration: { - registrationUrl: state.registrationUrl, - manifest: state.manifest, - expiresAt: state.expiresAt, - }, + registration: cloudManifest(session, state), } satisfies GitHubAppWizardState; } function cloudStart( - bot: Endpoint, session: typeof chatGitHubRegistrations.$inferSelect, ) { return { action: "start", id: session.handoff!.cloudId, - endpointId: bot.id, - connectionId: bot.connectionId, - agentId: bot.assignedAgentId, - name: session.appName!, - ownerType: session.ownerType, - ...(session.ownerLogin ? { ownerLogin: session.ownerLogin } : {}), returnUri: `${session.trustedOrigin}/api/chat-github/cloud/callback`, returnState: session.handoff!.returnState, }; } + function cloudManifest( + session: typeof chatGitHubRegistrations.$inferSelect, + route: GitHubAppCloudState, + ) { + if ( + !route.callbackUrls?.manifest || + !route.callbackUrls.install || + !route.callbackUrls.oauth || + !route.webhookUrl + ) + throw conflict( + "This Cloud connector needs the gateway update before setup can continue.", + ); + const url = new URL( + session.ownerType === "organization" + ? `https://github.com/organizations/${encodeURIComponent(session.ownerLogin!)}/settings/apps/new` + : "https://github.com/settings/apps/new", + ); + url.searchParams.set("state", session.handoff!.returnState); + return { + registrationUrl: url.toString(), + expiresAt: session.expiresAt.toISOString(), + manifest: { + name: session.appName, + url: session.trustedOrigin.startsWith("https:") + ? session.trustedOrigin + : new URL(route.webhookUrl).origin, + public: false, + hook_attributes: { url: route.webhookUrl, active: true }, + redirect_url: route.callbackUrls.manifest, + setup_url: route.callbackUrls.install, + setup_on_update: true, + callback_urls: [route.callbackUrls.oauth], + default_permissions: { + contents: "read", + issues: "write", + metadata: "read", + pull_requests: "write", + checks: "write", + }, + default_events: [ + "issue_comment", + "pull_request_review_comment", + "pull_request", + ], + }, + }; + } + async function exchangeCloudManifest( + session: typeof chatGitHubRegistrations.$inferSelect, + claimId: string, + ) { + const cloud = connector(); + if (!cloud || !session.handoff) + throw conflict("Restore Paperclip Cloud enrollment"); + const material = await cloud.claimGitHubApp({ + subject: session.userId, + companyId: session.companyId, + claimId, + redemptionId: session.handoff.redemptionId, + }); + if ( + material.kind !== "gateway_callback" || + material.registrationId !== session.handoff.cloudId || + material.callbackKind !== "manifest" || + typeof material.state !== "string" || + hash(material.state) !== session.stateHash || + typeof material.code !== "string" || + !/^[A-Za-z0-9_-]{1,256}$/.test(material.code) + ) + throw forbidden("GitHub manifest return did not match this draft"); + // Claim the single-use operation in the stack database before calling GitHub. + const [claimed] = await db + .update(chatGitHubRegistrations) + .set({ status: "exchanging", consumedAt: new Date() }) + .where( + and( + eq(chatGitHubRegistrations.id, session.id), + eq(chatGitHubRegistrations.status, "pending"), + sql`${chatGitHubRegistrations.expiresAt} > now()`, + ), + ) + .returning(); + if (!claimed) return; + try { + await endpoint(session.endpointId, session.userId); + const app = await githubBotRequest<{ + id: number; + pem: string; + webhook_secret: string; + client_id: string; + client_secret: string; + slug: string; + owner: { type: string; login: string }; + }>( + fetchImpl, + null, + `/app-manifests/${encodeURIComponent(material.code)}/conversions`, + { method: "POST" }, + ); + if ( + !Number.isSafeInteger(app.id) || + app.id <= 0 || + !app.pem || + !app.webhook_secret || + !app.client_id || + !app.client_secret || + !/^[a-z0-9-]+$/.test(app.slug ?? "") + ) + throw conflict( + "GitHub returned incomplete App credentials. Recover the App already created.", + ); + if ( + app.owner?.type !== + (session.ownerType === "organization" ? "Organization" : "User") || + (session.ownerLogin && + app.owner.login?.toLowerCase() !== session.ownerLogin.toLowerCase()) + ) + throw forbidden("GitHub returned an App owned by a different account"); + await options.storeApp(session.endpointId, session.userId, { + appId: String(app.id), + privateKey: app.pem, + webhookSecret: app.webhook_secret, + clientId: app.client_id, + clientSecret: app.client_secret, + slug: app.slug, + }); + await db + .update(chatGitHubRegistrations) + .set({ + status: "completed", + handoff: sql`${chatGitHubRegistrations.handoff} - 'manifestClaimId'`, + }) + .where(eq(chatGitHubRegistrations.id, session.id)); + } catch (error) { + await db + .update(chatGitHubRegistrations) + .set({ status: "failed" }) + .where(eq(chatGitHubRegistrations.id, session.id)); + throw error; + } + } + async function saveDraft( id: string, userId: string, @@ -390,7 +519,7 @@ export function githubChatWizardService( const binding = { subject: userId, companyId: bot.companyId }; const state = await cloud.githubApp({ ...binding, - binding: cloudStart(bot, session), + binding: cloudStart(session), }); const { credentials, appJwt } = await githubBotCredentials( db, @@ -399,12 +528,8 @@ export function githubChatWizardService( ); if (!credentials.webhookSecret) throw conflict("Recover this App's webhook secret before continuing"); - if (state.appId && state.appId !== credentials.appId) - throw conflict("Recovery must use the original GitHub App"); if (!state.webhookUrl) - throw conflict( - "Paperclip Cloud does not support recovering this App yet", - ); + throw conflict("Restore this App's Cloud gateway before continuing"); await logActivity(db, { companyId: bot.companyId, actorType: "user", @@ -414,23 +539,13 @@ export function githubChatWizardService( entityId: bot.connectionId, details: { endpointId: id, appId: credentials.appId }, }); + // The App JWT and webhook secret remain entirely in the instance. await resyncGitHubAppWebhook({ fetch: fetchImpl, appToken: appJwt, webhookUrl: state.webhookUrl, webhookSecret: credentials.webhookSecret, }); - const repaired = await cloud.githubApp({ - ...binding, - binding: { - action: "repair", - id: session.handoff.cloudId, - appToken: appJwt, - webhookSecret: credentials.webhookSecret, - }, - }); - if (repaired.appId !== credentials.appId) - throw conflict("GitHub App recovery binding did not match"); await db .update(chatGitHubRegistrations) .set({ @@ -525,20 +640,7 @@ export function githubChatWizardService( eq(toolConnections.companyId, bot.companyId), ), ); - const vaulted = - !!bot.botExternalId && - [ - "appId", - "privateKey", - "webhookSecret", - "clientId", - "clientSecret", - ].every((key) => - connection?.refs.some( - (ref) => ref.configPath === `credentials.${key}`, - ), - ); - const hasAppCredentials = + let hasAppCredentials = !!bot.botExternalId && ["appId", "privateKey", "webhookSecret"].every((key) => connection?.refs.some( @@ -546,138 +648,91 @@ export function githubChatWizardService( ), ); const binding = { subject: userId, companyId: bot.companyId }; - let state = await cloud.githubApp({ + const route = await cloud.githubApp({ ...binding, - binding: cloudStart(bot, session), + binding: cloudStart(session), }); - if (hasAppCredentials) { - const { credentials } = await githubBotCredentials( - db, - bot.companyId, - id, + let exchangedThisTurn = false; + if ( + session.status === "pending" && + session.handoff.manifestClaimId && + !hasAppCredentials + ) { + await exchangeCloudManifest(session, session.handoff.manifestClaimId); + bot = await endpoint(id, userId); + const [savedConnection] = await db + .select({ refs: toolConnections.credentialSecretRefs }) + .from(toolConnections) + .where( + and( + eq(toolConnections.id, bot.connectionId), + eq(toolConnections.companyId, bot.companyId), + ), + ); + hasAppCredentials = ["appId", "privateKey", "webhookSecret"].every( + (key) => + savedConnection?.refs.some( + (ref) => ref.configPath === `credentials.${key}`, + ), ); - if ( - ["pending", "exchanging", "failed"].includes(state.status) || - (session.handoff.webhookSecretHash && - session.handoff.webhookSecretHash !== - hash(credentials.webhookSecret ?? "")) - ) { - await repairCloud(id, userId); - state = await cloud.githubApp({ - ...binding, - binding: { action: "status", id: session.handoff.cloudId }, - }); - bot = await endpoint(id, userId); - } + exchangedThisTurn = true; } - if (state.status === "failed" || state.status === "exchanging") - return { - endpointId: id, - state: "recovery", - message: - state.status === "exchanging" - ? "GitHub registration is still being processed. If it was interrupted, recover the App already created on GitHub." - : "Recover the App already created on GitHub. Registration was interrupted and cannot safely be repeated.", - }; - if (state.status === "pending") { - if (Date.parse(state.expiresAt) <= Date.now()) + if (!bot.botExternalId) { + const current = await registration(bot); + if (current?.status !== "pending" || session.expiresAt <= new Date()) return { endpointId: id, state: "recovery", message: - "Registration expired. Check GitHub for the App before using existing-App recovery.", + "Recover the App already created on GitHub. An interrupted exchange cannot safely be repeated.", }; return { endpointId: id, state: "create", - registration: - state.registrationUrl && state.manifest - ? { - registrationUrl: state.registrationUrl, - manifest: state.manifest, - expiresAt: state.expiresAt, - } - : undefined, + registration: cloudManifest(session, route), }; } - if (state.claimExpired && !vaulted) + if (!hasAppCredentials) return { endpointId: id, state: "recovery", - message: - "Credential delivery expired. Recover the App already created on GitHub; do not create another App.", + message: "Recover this App's saved credentials before continuing.", }; - if (state.claimId && !vaulted) { - const material = await cloud.claimGitHubApp({ - ...binding, - claimId: state.claimId, - redemptionId: session.handoff.redemptionId, - }); - if ( - material.kind !== "github_app" || - material.registrationId !== session.handoff.cloudId || - material.endpointId !== bot.id || - material.connectionId !== bot.connectionId || - material.agentId !== bot.assignedAgentId - ) - throw forbidden( - "GitHub App credential binding did not match this draft", - ); - const credentials: Record = {}; - for (const key of [ - "appId", - "privateKey", - "webhookSecret", - "clientId", - "clientSecret", - ]) { - if (typeof material[key] !== "string" || !material[key]) - throw conflict("GitHub returned incomplete App credentials"); - credentials[key] = material[key] as string; - } - await options.storeApp(id, userId, credentials); - } - bot = await endpoint(id, userId); - if (!bot.botExternalId || bot.botExternalId !== state.appId) - throw conflict("Recover this App's credentials before continuing."); - await cloud.githubApp({ - ...binding, - binding: { action: "stored", id: session.handoff.cloudId }, - }); - const { credentials: storedCredentials } = await githubBotCredentials( + const { credentials: stored } = await githubBotCredentials( db, bot.companyId, id, ); - if (!session.handoff.webhookSecretHash) - await db - .update(chatGitHubRegistrations) - .set({ - handoff: sql`jsonb_set(${chatGitHubRegistrations.handoff}, '{webhookSecretHash}', ${JSON.stringify(hash(storedCredentials.webhookSecret))}::jsonb)`, - }) - .where(eq(chatGitHubRegistrations.id, session.id)); + if ( + (!exchangedThisTurn && session.status !== "completed") || + (session.handoff.webhookSecretHash && + session.handoff.webhookSecretHash !== + hash(stored.webhookSecret ?? "")) + ) { + await repairCloud(id, userId); + bot = await endpoint(id, userId); + } if (session.status !== "completed") await db .update(chatGitHubRegistrations) .set({ status: "completed" }) .where(eq(chatGitHubRegistrations.id, session.id)); + if (!session.handoff.webhookSecretHash) + await db + .update(chatGitHubRegistrations) + .set({ + handoff: sql`jsonb_set(${chatGitHubRegistrations.handoff}, '{webhookSecretHash}', ${JSON.stringify(hash(stored.webhookSecret ?? ""))}::jsonb)`, + }) + .where(eq(chatGitHubRegistrations.id, session.id)); await setup(bot, { cloudRegistrationId: session.handoff.cloudId, ownerType: session.ownerType, - ownerLogin: state.ownerLogin ?? session.ownerLogin ?? undefined, + ownerLogin: session.ownerLogin ?? undefined, appName: session.appName ?? undefined, registrationStatus: "completed", }); - if (state.signedDeliveryAt && !bot.setup.webhookVerifiedAt) { - await db - .update(chatEndpoints) - .set({ - setup: sql`jsonb_set(${chatEndpoints.setup}, '{webhookVerifiedAt}', ${JSON.stringify(state.signedDeliveryAt)}::jsonb)`, - updatedAt: new Date(), - }) - .where(eq(chatEndpoints.id, id)); - } } + bot = await endpoint(id, userId); if (!bot.botExternalId) { if (session && !session.handoff?.cloudId) { @@ -710,11 +765,16 @@ export function githubChatWizardService( return { endpointId: id, state: "recovery", - message: "This App's credentials were not completely saved. Recover its existing credentials before continuing.", + message: + "This App's credentials were not completely saved. Recover its existing credentials before continuing.", }; } } - if (!bot.providerAccountId || bot.setup.github?.stage === "install" || bot.setup.github?.initialSetupPending) { + if ( + !bot.providerAccountId || + bot.setup.github?.stage === "install" || + bot.setup.github?.initialSetupPending + ) { try { await options.refreshRepositories(id, userId); } catch (error) { @@ -735,7 +795,8 @@ export function githubChatWizardService( const resources = await options.resources(id); // Fresh manifest and manual Apps import GitHub's initial choices. Saved // selections and configuration still belong to the user on recovery. - const initializeApp = !!session || bot.setup.github?.initialSetupPending === true; + const initializeApp = + !!session || bot.setup.github?.initialSetupPending === true; if ( initializeApp && bot.status !== "active" && @@ -770,7 +831,10 @@ export function githubChatWizardService( }, userId, ); - await setup(bot, { initialRepositoriesImported: true, initialSetupPending: false }); + await setup(bot, { + initialRepositoriesImported: true, + initialSetupPending: false, + }); } if (bot.status !== "active" && bot.status !== "verifying") await options.configure(id, userId); @@ -976,15 +1040,20 @@ export function githubChatWizardService( subject: userId, companyId: bot.companyId, binding: { - action: "identity", + action: "callback", id: session.handoff.cloudId, - codeChallenge: challenge, - returnState: state, + stateHash: hash(state), }, }); - if (!result.authorizationUrl) + if (!result.callbackUrls?.oauth) throw conflict("GitHub account authorization is unavailable"); - return { authorizationUrl: result.authorizationUrl }; + const url = new URL("https://github.com/login/oauth/authorize"); + url.searchParams.set("client_id", credentials.credentials.clientId); + url.searchParams.set("redirect_uri", result.callbackUrls.oauth); + url.searchParams.set("state", state); + url.searchParams.set("code_challenge", challenge); + url.searchParams.set("code_challenge_method", "S256"); + return { authorizationUrl: url.toString() }; } const url = new URL("https://github.com/login/oauth/authorize"); url.searchParams.set("client_id", credentials.credentials.clientId); @@ -1162,12 +1231,34 @@ export function githubChatWizardService( sql`${chatGitHubRegistrations.handoff}->>'cloudId' = ${registrationId}`, ) .limit(1); - if ( - !session?.handoff || - (session.stateHash !== hash(state) && - session.handoff.identityStateHash !== hash(state)) - ) + if (!session?.handoff || !claimId) throw forbidden("GitHub return did not match this instance"); + const cloud = connector(); + if (!cloud) throw conflict("Restore Paperclip Cloud enrollment"); + const opened = await cloud.claimGitHubApp({ + subject: session.userId, + companyId: session.companyId, + claimId, + redemptionId: + session.handoff.identityStateHash && + hash(state) === session.handoff.identityStateHash + ? session.handoff.identityRedemptionId! + : session.handoff.redemptionId, + }); + if ( + opened.kind !== "gateway_callback" || + opened.registrationId !== registrationId || + (opened.callbackKind !== "install" && opened.state !== state) + ) + throw forbidden("GitHub return did not match this draft"); + const manifestReturn = + opened.callbackKind === "manifest" && + session.stateHash === hash(String(opened.state ?? "")); + const identityReturn = + opened.callbackKind === "oauth" && + session.handoff.identityStateHash === hash(String(opened.state ?? "")); + if (!manifestReturn && !identityReturn && opened.callbackKind !== "install") + throw forbidden("GitHub return state did not match"); const bot = await endpoint(session.endpointId, session.userId); if (session.trustedOrigin !== origin()) { const cloud = connector(); @@ -1200,8 +1291,8 @@ export function githubChatWizardService( details: { registrationId: session.id }, }); } - if (session.handoff.identityStateHash === hash(state)) { - if (!claimId) { + if (identityReturn) { + if (typeof opened.code !== "string" || opened.error) { await db .update(chatGitHubRegistrations) .set({ @@ -1215,28 +1306,28 @@ export function githubChatWizardService( ); return resume(bot); } - const cloud = connector(); - if (!cloud) throw conflict("Restore Paperclip Cloud enrollment"); - const opened = await cloud.claimGitHubApp({ + const route = await cloud.githubApp({ subject: session.userId, companyId: session.companyId, - claimId, - redemptionId: session.handoff.identityRedemptionId!, + binding: { action: "status", id: registrationId }, }); - if ( - opened.kind !== "github_app_identity" || - opened.registrationId !== registrationId || - opened.endpointId !== bot.id || - opened.connectionId !== bot.connectionId || - opened.agentId !== bot.assignedAgentId || - typeof opened.code !== "string" || - typeof opened.redirectUri !== "string" - ) - throw forbidden("GitHub identity return did not match this draft"); - return completeIdentity(session, opened.code, opened.redirectUri); + if (opened.redirectUri !== route.callbackUrls.oauth) + throw forbidden("GitHub identity callback did not match"); + return completeIdentity(session, opened.code, route.callbackUrls.oauth); + } + if (manifestReturn && session.status === "pending") { + await db + .update(chatGitHubRegistrations) + .set({ + handoff: sql`jsonb_set(${chatGitHubRegistrations.handoff}, '{manifestClaimId}', ${JSON.stringify(claimId)}::jsonb)`, + }) + .where( + and( + eq(chatGitHubRegistrations.id, session.id), + eq(chatGitHubRegistrations.status, "pending"), + ), + ); } - if (hash(state) !== session.stateHash) - throw forbidden("GitHub return state did not match"); const progress = await advance(session.endpointId, session.userId); return progress.state === "install" && progress.installationUrl ? progress.installationUrl diff --git a/server/src/services/paperclip-cloud-connector.test.ts b/server/src/services/paperclip-cloud-connector.test.ts index 307c9262b51..42e8a3cd4bb 100644 --- a/server/src/services/paperclip-cloud-connector.test.ts +++ b/server/src/services/paperclip-cloud-connector.test.ts @@ -610,10 +610,12 @@ describe("Paperclip Cloud connector", () => { function seal( payload: unknown, recipientPublicKey: KeyObject, - purpose: "initial" | "access", + purpose: "initial" | "access" | "events", configValue: PaperclipCloudConnectorConfig, - profile: keyof typeof GOOGLE_WORKSPACE_CONNECTOR_PROFILES, + profile: keyof typeof GOOGLE_WORKSPACE_CONNECTOR_PROFILES | "github.bot" | "github.code", ) { + const provider = profile.startsWith("github.") ? "github" : "google"; + const scopes = provider === "github" ? [] : GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile as keyof typeof GOOGLE_WORKSPACE_CONNECTOR_PROFILES].scopes; const ephemeral = generateKeyPairSync("x25519"); const ephemeralJwk = ephemeral.publicKey.export({ format: "jwk" }) as { x: string }; const recipientJwk = recipientPublicKey.export({ format: "jwk" }) as { x: string }; @@ -625,9 +627,9 @@ function seal( purpose, configValue.instanceId, configValue.environment, - "google", + provider, profile, - [...GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes].sort().join(" "), + [...scopes].sort().join(" "), ].join("\n")); const key = Buffer.from(hkdfSync( "sha256", @@ -644,10 +646,34 @@ function seal( v: 1, alg: "X25519-HKDF-SHA256-A256GCM", purpose, - provider: "google", + provider, profile, epk: ephemeralJwk.x, iv: iv.toString("base64url"), ct: ciphertext.toString("base64url"), }; } + +describe("dedicated App gateway delivery", () => { + it.each([1, 2])("requires the stack-owned setup protocol version (%s)", async version => { + const connector = createPaperclipCloudConnector({ config: config().config, request: vi.fn(async () => Response.json({active:true,githubApps:{version}})) as typeof fetch }); + expect(await connector.githubAppsAvailable()).toBe(version === 2); + }); + it("decrypts opaque webhook bytes sealed before Cloud storage", async () => { + const keys = config(); + const rawBody = Buffer.from('{ "comment": { "body": "private comment" } }').toString("base64"); + const packet = { v:1,instanceId,environment:"staging",registrationId:"route-a",rawBody,headers:{"x-github-event":"issue_comment","x-github-delivery":"delivery-a","x-hub-signature-256":"signature"} }; + const inner = seal(packet,keys.sealPublicKey,"events",keys.config,"github.bot"); + const outer = seal({v:1,instanceId,environment:"staging",leaseId:"lease-a",events:[{id:"transport-a",provider:"github",event:"gateway_delivery",payload:{githubApp:{registrationId:"route-a",sealed:inner}},bindingIds:["github-app:route-a"]}]},keys.sealPublicKey,"events",keys.config,"github.code"); + const connector = createPaperclipCloudConnector({config:keys.config,request:vi.fn(async()=>Response.json({leaseId:"lease-a",sealed:outer})) as typeof fetch}); + expect((await connector.leaseEvents({subject,companyId}))?.events[0].payload.githubApp).toEqual(packet); + expect(JSON.stringify(inner)).not.toContain("private comment"); + }); + it("rejects an inner envelope swapped from another opaque route", async () => { + const keys = config(); + const inner = seal({v:1,instanceId,environment:"staging",registrationId:"route-b"},keys.sealPublicKey,"events",keys.config,"github.bot"); + const outer = seal({v:1,instanceId,environment:"staging",leaseId:"lease-a",events:[{id:"transport-a",provider:"github",event:"gateway_delivery",payload:{githubApp:{registrationId:"route-a",sealed:inner}},bindingIds:["github-app:route-a"]}]},keys.sealPublicKey,"events",keys.config,"github.code"); + const connector=createPaperclipCloudConnector({config:keys.config,request:vi.fn(async()=>Response.json({leaseId:"lease-a",sealed:outer})) as typeof fetch}); + await expect(connector.leaseEvents({subject,companyId})).rejects.toBeInstanceOf(PaperclipCloudConnectorError); + }); +}); diff --git a/server/src/services/paperclip-cloud-connector.ts b/server/src/services/paperclip-cloud-connector.ts index 49806ba6f94..7785deeb596 100644 --- a/server/src/services/paperclip-cloud-connector.ts +++ b/server/src/services/paperclip-cloud-connector.ts @@ -368,7 +368,7 @@ export function createPaperclipCloudConnector(input: { return { async githubAppsAvailable() { const response = await call("status", { subject: "instance-capabilities", companyId: "instance-capabilities" }); - return response.active === true && response.githubApps?.version === 1; + return response.active === true && response.githubApps?.version === 2; }, async githubApp(values: { subject: string; companyId: string; binding: Record }) { return await call("github-app", values, { field: "binding", value: JSON.stringify(values.binding) }) as unknown as import("@paperclipai/shared").GitHubAppCloudState; @@ -516,6 +516,15 @@ export function createPaperclipCloudConnector(input: { if (opened.leaseId !== response.leaseId) { throw new PaperclipCloudConnectorError("Paperclip Cloud connector event lease did not match", "CONNECTOR_BINDING_MISMATCH"); } + for (const event of opened.events) { + const packet = event.payload.githubApp; + if (!isRecord(packet) || packet.sealed === undefined) continue; + const sealed = parseEnvelope(packet.sealed, "events", "github", "github.bot"); + const delivery = decryptEnvelope(sealed, sealKey, config.instanceId, config.environment, "github", "github.bot", []) as Record; + if (delivery.v !== 1 || delivery.instanceId !== config.instanceId || delivery.environment !== config.environment + || delivery.registrationId !== packet.registrationId) throw badEnvelope(); + event.payload = { githubApp: delivery }; + } return { leaseId: opened.leaseId, events: opened.events }; }, async acknowledgeEvents(values: { subject: string; companyId: string; leaseId: string; deliveryIds: string[] }): Promise {