From 49041e0d8bb781048860d80e471d5a369b5e96f5 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 6 Oct 2026 21:42:21 -0500 Subject: [PATCH] fix: preserve Slack recovery choices and registration secrets Persist existing-app selection, validate setup-method changes before cleanup, and verify the OAuth continuation in a real browser. Co-Authored-By: Paperclip --- doc/connections/SLACK-AUTOMATIC-SETUP.md | 3 +- packages/shared/src/types/chat-channels.ts | 4 +- .../shared/src/validators/chat-channels.ts | 2 +- .../chat-channels.integration.test.ts | 2 + server/src/routes/openapi.ts | 2 +- server/src/services/chat-channels.ts | 5 ++- tests/e2e/chat-adapters-ui-providers.spec.ts | 37 +++++++++++++++---- tests/e2e/chat-adapters-ui.shared.ts | 4 +- ui/src/api/chatEndpoints.ts | 2 +- ui/src/pages/apps/chat/ChatEndpointSetup.tsx | 4 +- 10 files changed, 45 insertions(+), 20 deletions(-) diff --git a/doc/connections/SLACK-AUTOMATIC-SETUP.md b/doc/connections/SLACK-AUTOMATIC-SETUP.md index bbaaf6ad736..88a2aa3f00a 100644 --- a/doc/connections/SLACK-AUTOMATIC-SETUP.md +++ b/doc/connections/SLACK-AUTOMATIC-SETUP.md @@ -34,7 +34,8 @@ the draft and all saved non-secret progress. **Create manually** uses the same generated manifest. **Use an existing app** keeps the existing credential-entry workflow. Both options remain available for -recovery on the same draft. The setup prompt describes browser assistance and +recovery on the same draft. The selected automatic, manual, or existing-app method +is saved, so an existing-app draft reopens at credential entry. The setup prompt describes browser assistance and requires the user to enter the temporary token and handle login/admin approval. ## Deployment diff --git a/packages/shared/src/types/chat-channels.ts b/packages/shared/src/types/chat-channels.ts index c78005c4e30..873a4722623 100644 --- a/packages/shared/src/types/chat-channels.ts +++ b/packages/shared/src/types/chat-channels.ts @@ -188,7 +188,7 @@ export interface SlackAppConfiguration { } export interface ChatEndpointSetupState { - slackSetupMethod?: "automatic" | "manual"; + slackSetupMethod?: "automatic" | "manual" | "existing"; slackRegistration?: import("../slack-app-manifest.js").SlackRegistrationState; slackOAuthCallbackUri?: string | null; github?: { @@ -485,7 +485,7 @@ export interface CreateChatEndpointInput { } export interface UpdateChatEndpointInput { - slackSetupMethod?: "automatic" | "manual"; + slackSetupMethod?: "automatic" | "manual" | "existing"; slackApp?: SlackAppConfiguration; communicationInstructions?: string; allowDirectMessages?: boolean; diff --git a/packages/shared/src/validators/chat-channels.ts b/packages/shared/src/validators/chat-channels.ts index 3d84caebb6a..515403b0f5c 100644 --- a/packages/shared/src/validators/chat-channels.ts +++ b/packages/shared/src/validators/chat-channels.ts @@ -86,7 +86,7 @@ export const updateChatEndpointSchema = z .object({ communicationInstructions: multilineTextSchema.pipe(z.string().trim().max(4000)).optional(), slackApp: slackAppConfigurationSchema.optional(), - slackSetupMethod: z.enum(["automatic", "manual"]).optional(), + slackSetupMethod: z.enum(["automatic", "manual", "existing"]).optional(), allowDirectMessages: z.boolean().optional(), allowGroupChats: z.boolean().optional(), allowUnlinkedPeople: z.boolean().optional(), diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index 440e459ef72..7549a645377 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -4062,6 +4062,8 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { expect(await f.service.listPrincipals(f.endpoint.id)).toEqual([]); const [row] = await db.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, f.endpoint.id)); expect(Object.keys(row.secretIds)).toEqual(["clientSecret"]); + await request(f.app).patch(`/api/chat-endpoints/${f.endpoint.id}`).send({ slackSetupMethod: "manual" }).expect(409); + expect((await f.service.slackRegistration.registration(f.endpoint.id))?.secretIds).toEqual(row.secretIds); const body = JSON.stringify({ type: "url_verification", challenge: "auto-challenge" }); await f.service.handleWebhook(saved.publicId, "slack", signedSlackWebhookRequest({ url: saved.setup.webhookUrl!, body, contentType: "application/json", signingSecret })); expect((await f.service.get(f.endpoint.id)).setup.webhookVerifiedAt).toBeTruthy(); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 5ad164d6d41..bb5853a1188 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -789,7 +789,7 @@ const chatAdapterCapabilitiesResponseSchema = z const chatEndpointSetupResponseSchema = z .object({ step: z.enum(["choose_agent", "provider_setup", "test", "complete"]), - slackSetupMethod: z.enum(["automatic", "manual"]).optional(), + slackSetupMethod: z.enum(["automatic", "manual", "existing"]).optional(), slackRegistration: slackRegistrationStateSchema.optional(), slackOAuthCallbackUri: z.string().nullable().optional(), slackApp: slackAppConfigurationSchema.optional(), diff --git a/server/src/services/chat-channels.ts b/server/src/services/chat-channels.ts index 73efb53bddb..c1448ce9bba 100644 --- a/server/src/services/chat-channels.ts +++ b/server/src/services/chat-channels.ts @@ -6076,6 +6076,9 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { } values.communicationInstructions = input.communicationInstructions; } + if (input.slackSetupMethod && (existing.endpoint.provider !== "slack" || existing.endpoint.botExternalId || existing.endpoint.status !== "draft")) { + throw conflict("Setup method can only change before connecting the app"); + } if (input.slackApp || input.slackSetupMethod) { const [registration] = await db.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, endpointId)); if (registration && registration.status !== "failed") { @@ -6085,8 +6088,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { } } if (input.slackSetupMethod) { - if (existing.endpoint.provider !== "slack" || existing.endpoint.botExternalId || existing.endpoint.status !== "draft") - throw conflict("Setup method can only change before connecting the app"); values.setup = { ...existing.endpoint.setup, slackSetupMethod: input.slackSetupMethod }; } if (input.slackApp) { diff --git a/tests/e2e/chat-adapters-ui-providers.spec.ts b/tests/e2e/chat-adapters-ui-providers.spec.ts index bb4d6d3e43f..f6c41e627f4 100644 --- a/tests/e2e/chat-adapters-ui-providers.spec.ts +++ b/tests/e2e/chat-adapters-ui-providers.spec.ts @@ -1,4 +1,5 @@ import { oauthCallbackInterstitialHtml } from "../../server/src/lib/oauth-browser-return"; +import { createServer } from "node:http"; import { readFile } from "node:fs/promises"; import { expect, test, type Page } from "@playwright/test"; @@ -114,6 +115,28 @@ async function exerciseGitHubReviewSetup(page: Page, mock: ChatMock, seed: Seed, * chat-control-plane mock live in ./chat-adapters-ui.shared.ts; the * messaging-flow describes run in chat-adapters-ui-messaging.spec.ts. */ +test("Slack OAuth continuation reloads once from the callback origin without echoing the code", async ({ page }) => { + const sites: Array = []; + const server = createServer((req, res) => { + sites.push(req.headers["sec-fetch-site"] as string | undefined); + res.setHeader("Content-Type", "text/html"); + res.setHeader("Cache-Control", "no-store"); + if (sites.length === 1) res.end(oauthCallbackInterstitialHtml()); + else res.end("

Callback completed

"); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + try { + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Missing callback fixture listener"); + const callback = `http://127.0.0.1:${address.port}/callback?code=fixture-code`; + await page.route("https://slack.test/consent", route => route.fulfill({ contentType: "text/html", body: `Approve installation` })); + await page.goto("https://slack.test/consent"); + await page.getByRole("link", { name: "Approve installation" }).click(); + await expect(page.getByRole("heading", { name: "Callback completed" })).toBeVisible(); + expect(sites.slice(0, 2)).toEqual(["cross-site", "same-origin"]); + } finally { await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); } +}); + test.describe.serial("native chat adapter UI", () => { test.setTimeout(180_000); @@ -128,11 +151,10 @@ test.describe.serial("native chat adapter UI", () => { const mock = await installChatControlPlaneMock(page, slack, seed, { enableChatConnectors: true, automaticSlack: true }); const rootUrl = new URL(`/${seed.prefix}/apps/chat/connect?provider=slack&purpose=chat&resume=endpoint-slack`, test.info().project.use.baseURL).href; const callbackUrl = new URL("/api/chat-slack/oauth/callback?state=fixture-state&code=fixture-code", rootUrl).href; - const callbackSites: string[] = []; + let callbackRequests = 0; await page.route("**/api/chat-slack/oauth/callback?**", async route => { - const site = route.request().headers()["sec-fetch-site"]; - callbackSites.push(site); - if (site === "cross-site") { + callbackRequests += 1; + if (callbackRequests === 1) { const body = oauthCallbackInterstitialHtml(); expect(body).not.toContain("fixture-code"); await route.fulfill({ contentType: "text/html", body }); @@ -142,9 +164,7 @@ test.describe.serial("native chat adapter UI", () => { } }); await page.route("https://slack.test/**", async route => { - if (route.request().url().endsWith("/approve")) { - await route.fulfill({ status: 302, headers: { location: callbackUrl } }); - } else await route.fulfill({ contentType: "text/html", body: '

Fixture Slack consent

Approve installation' }); + await route.fulfill({ contentType: "text/html", body: `

Fixture Slack consent

Approve installation` }); }); await page.goto(`/${seed.prefix}/apps/chat/connect?provider=slack&purpose=chat&agentId=${seed.agentId}`); await page.getByRole("button", { name: "Continue", exact: true }).click(); @@ -172,7 +192,7 @@ test.describe.serial("native chat adapter UI", () => { await page.getByRole("button", { name: "Continue to message test", exact: true }).click(); await expect(page.getByRole("heading", { name: "Try Maya in Slack", exact: true })).toBeVisible(); expect(mock.slackCreations).toBe(1); expect(mock.slackInstallations).toBe(1); - expect(callbackSites).toEqual(["cross-site", "same-origin"]); + expect(callbackRequests).toBe(2); await page.screenshot({ path: test.info().outputPath("automatic-slack-identity-linked.png"), fullPage: true }); await page.getByRole("button", { name: "Skip test and finish", exact: true }).click(); await expect(page).toHaveURL(/\/apps\/chat\/endpoint-slack\/settings$/); @@ -196,6 +216,7 @@ test.describe.serial("native chat adapter UI", () => { await expect(page.getByRole("heading", { name: "Add Slack credentials", exact: true })).toBeVisible(); await page.reload(); await expect(page.getByRole("heading", { name: "Add Slack credentials", exact: true })).toBeVisible(); + await expect(page.getByRole("heading", { name: "Add Slack credentials", exact: true })).toBeVisible(); expect(mock.slackCreations).toBe(0); }); diff --git a/tests/e2e/chat-adapters-ui.shared.ts b/tests/e2e/chat-adapters-ui.shared.ts index db99bd385d5..14e6011a0f9 100644 --- a/tests/e2e/chat-adapters-ui.shared.ts +++ b/tests/e2e/chat-adapters-ui.shared.ts @@ -281,7 +281,7 @@ export function endpointFixture(provider: ProviderCase, seed: Seed) { proactiveDirectMessages: false, }, setup: { - slackSetupMethod: undefined as "automatic" | "manual" | undefined, + slackSetupMethod: undefined as "automatic" | "manual" | "existing" | undefined, slackRegistration: undefined as SlackRegistrationState | undefined, slackApp: undefined as SlackAppConfiguration | undefined, slackOAuthCallbackUri: "https://paperclip.example.test/api/chat-slack/oauth/callback", @@ -509,7 +509,7 @@ export async function installChatControlPlaneMock( if (method === "PATCH") { const body = bodyOf(route); if (body.slackApp) endpoint.setup.slackApp = body.slackApp as SlackAppConfiguration; - if (body.slackSetupMethod) endpoint.setup.slackSetupMethod = body.slackSetupMethod as "automatic" | "manual"; + if (body.slackSetupMethod) endpoint.setup.slackSetupMethod = body.slackSetupMethod as "automatic" | "manual" | "existing"; if (typeof body.allowDirectMessages === "boolean") state.allowDirectMessages = body.allowDirectMessages; if (typeof body.allowGroupChats === "boolean") diff --git a/ui/src/api/chatEndpoints.ts b/ui/src/api/chatEndpoints.ts index 3b440413543..509df78b5da 100644 --- a/ui/src/api/chatEndpoints.ts +++ b/ui/src/api/chatEndpoints.ts @@ -136,7 +136,7 @@ export interface ChatEndpoint { messagingEndpoint?: string | null; command?: string | null; slackApp?: SlackAppConfiguration; - slackSetupMethod?: "automatic" | "manual"; + slackSetupMethod?: "automatic" | "manual" | "existing"; slackRegistration?: SlackRegistrationState; slackOAuthCallbackUri?: string | null; webhookVerifiedAt?: string | null; diff --git a/ui/src/pages/apps/chat/ChatEndpointSetup.tsx b/ui/src/pages/apps/chat/ChatEndpointSetup.tsx index 8aab442bf74..d5a2bb26c30 100644 --- a/ui/src/pages/apps/chat/ChatEndpointSetup.tsx +++ b/ui/src/pages/apps/chat/ChatEndpointSetup.tsx @@ -428,7 +428,7 @@ function ChatSdkEndpointSetup() { : tryStep : automaticSlack && endpoint.setup?.slackRegistration?.status === "credentials_saved" ? 2 : isSlack && endpoint.providerAccountId && !repairing ? 3 - : isSlack && (slackCredentialsReady || repairing || automaticSlack && endpoint.setup?.slackRegistration?.appId) ? 2 : 1 + : isSlack && (slackCredentialsReady || repairing || endpoint.setup?.slackSetupMethod === "existing" || automaticSlack && endpoint.setup?.slackRegistration?.appId) ? 2 : 1 : 0; const step = Math.min(viewedStep ?? availableStep, availableStep); const avatarAgent = useQuery({ @@ -1670,7 +1670,7 @@ function ProviderConnectStep({ onBusy={setAutomaticBusy} onSaved={onEndpointSaved} onContinue={onSlackAppCreated} onManual={async existing => { if (!registrationLocked && slackValidation.success) await saveSlackApp.mutateAsync(slackValidation.data); - onEndpointSaved(await chatEndpointsApi.update(endpoint.id, { slackSetupMethod: "manual" })); + onEndpointSaved(await chatEndpointsApi.update(endpoint.id, { slackSetupMethod: existing ? "existing" : "manual" })); if (existing) onSlackAppCreated(); }} onSaveExit={() => void saveSlackAndExit()}