diff --git a/server/src/__tests__/connection-management-delegated-policy.integration.test.ts b/server/src/__tests__/connection-management-delegated-policy.integration.test.ts index f7995f5da05..c3af5f1825c 100644 --- a/server/src/__tests__/connection-management-delegated-policy.integration.test.ts +++ b/server/src/__tests__/connection-management-delegated-policy.integration.test.ts @@ -216,13 +216,157 @@ describe("connection management delegated policy and profile access", () => { expiresAt: null, requiredUserAction: { userId: f.userId, resource: { id: created.body.id } }, } }); // The agent links this in chat, so it is a relative app route, never the server's own origin. + // A custom remote MCP server has no app source, so the hand-off goes to the + // draft's own permissions page where the user can click "Connect as me". expect(started.body.authorizationUrl).toMatch(/^\/[^/]/); expect(started.body.requiredUserAction.setupPath).toBe(started.body.authorizationUrl); - expect(new URL(started.body.authorizationUrl, "https://paperclip.example").searchParams.get("resume")).toBe(created.body.id); + expect(new URL(started.body.authorizationUrl, "https://paperclip.example").pathname) + .toMatch(new RegExp(`^/[^/]+/apps/${created.body.id}/permissions$`)); expect(await f.request("POST", path, { asCurrentUser: true })).toMatchObject({ status: 200, body: { authorizationUrl: started.body.authorizationUrl } }); expect(await server.db.select().from(toolOauthStates).where(eq(toolOauthStates.connectionId, created.body.id))).toHaveLength(0); }); + it("keeps an agent-started personal OAuth URL draft alive until the addressed user signs in", async () => { + const f = await fixture(); + const mcpOrigin = "https://8.8.8.8"; + const mcpUrl = `${mcpOrigin}/mcp`; + const issuer = `${mcpOrigin}/tenant/acme`; + let accessToken: string | null = null; + provider = async (url, init) => { + const method = (init?.method ?? "GET").toUpperCase(); + if (url === `${mcpOrigin}/.well-known/oauth-protected-resource/mcp`) { + return Response.json({ resource: mcpUrl, authorization_servers: [issuer] }); + } + if (url === `${mcpOrigin}/.well-known/oauth-authorization-server/tenant/acme`) { + return Response.json({ + issuer, + authorization_endpoint: `${issuer}/authorize`, + token_endpoint: `${issuer}/token`, + registration_endpoint: `${issuer}/register`, + code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["none"], + scopes_supported: ["mcp:read"], + }); + } + if (url === `${issuer}/register` && method === "POST") { + const requested = JSON.parse(String(init?.body ?? "{}")) as Record; + return Response.json({ + client_id: "fixture-dcr-client", + redirect_uris: requested.redirect_uris, + grant_types: requested.grant_types, + response_types: requested.response_types, + token_endpoint_auth_method: requested.token_endpoint_auth_method, + application_type: requested.application_type, + }); + } + if (url === `${issuer}/token` && method === "POST") { + accessToken = `fixture-access-${randomUUID()}`; + return Response.json({ + access_token: accessToken, + refresh_token: "fixture-refresh", + expires_in: 3600, + token_type: "Bearer", + scope: "mcp:read", + }); + } + if (url === mcpUrl && method === "POST") { + const headers = new Headers(init?.headers); + if (headers.get("authorization") !== `Bearer ${accessToken}`) { + return new Response("", { + status: 401, + headers: { "www-authenticate": `Bearer resource_metadata="${mcpOrigin}/.well-known/oauth-protected-resource/mcp"` }, + }); + } + return Response.json({ + jsonrpc: "2.0", + id: "paperclip-catalog-refresh", + result: { tools: [{ name: "list_items", description: "List items", annotations: { readOnlyHint: true } }] }, + }); + } + return Response.json({ error: "not_found" }, { status: 404 }); + }; + try { + const connected = await f.request("POST", `/companies/${f.companyId}/tools/apps/connect`, { + link: mcpUrl, + name: "Agent personal OAuth E2E", + authMode: "oauth", + grantKind: "user", + }); + expect(connected, JSON.stringify(connected)).toMatchObject({ status: 201 }); + const connectionId = connected.body.connectionId as string; + expect(connected.body.auth).toMatchObject({ kind: "oauth", issuer }); + const permissionsPathPattern = new RegExp(`^/[^/]+/apps/${connectionId}/permissions$`); + expect(connected.body.auth.startUrl).toMatch(permissionsPathPattern); + expect(connected.body.requiredUserAction?.setupPath).toBe(connected.body.auth.startUrl); + expect(await server.db.select().from(toolOauthStates).where(eq(toolOauthStates.connectionId, connectionId))).toHaveLength(0); + + // The addressed human opens the handed-off link: the draft is alive (not a 404 dead link) + // and exposes "Connect as me" capability while awaiting first sign-in. + const cookie = await server.humanSession(f.userId); + const getConnectionRes = await fetch(`${server.apiUrl}/api/tool-connections/${connectionId}`, { headers: { cookie } }); + expect(getConnectionRes.status).toBe(200); + expect(await getConnectionRes.json()).toMatchObject({ + id: connectionId, + status: "draft", + credentialPolicy: "per_user", + createdByUserId: f.userId, + }); + + const listBeforeRes = await fetch(`${server.apiUrl}/api/companies/${f.companyId}/tools/connections`, { headers: { cookie } }); + expect(listBeforeRes.status).toBe(200); + const listBefore = await listBeforeRes.json() as { connections: Array<{ id: string; status: string; firstSignInPending?: boolean }> }; + expect(listBefore.connections.find(c => c.id === connectionId)).toMatchObject({ status: "draft", firstSignInPending: true }); + + const grantsBeforeRes = await fetch(`${server.apiUrl}/api/tool-connections/${connectionId}/grants`, { headers: { cookie } }); + expect(grantsBeforeRes.status).toBe(200); + expect(await grantsBeforeRes.json()).toMatchObject({ + grants: [], + currentUserId: f.userId, + capabilities: { canConnectAsCurrentUser: true }, + }); + + // The human clicks "Connect as me" on the draft's permissions page and finishes OAuth. + const startAuthRes = await fetch( + `${server.apiUrl}/api/companies/${f.companyId}/tools/connections/${connectionId}/start-authorization`, + { + method: "POST", + headers: { cookie, "Content-Type": "application/json", origin: server.apiUrl }, + body: JSON.stringify({ subjectUserId: f.userId, returnTo: `/apps/${connectionId}/permissions` }), + }, + ); + const startAuthBody = await startAuthRes.json(); + expect(startAuthRes.status, JSON.stringify(startAuthBody)).toBe(200); + const providerAuthUrl = new URL(startAuthBody.url); + expect(providerAuthUrl.origin + providerAuthUrl.pathname).toBe(`${issuer}/authorize`); + const state = providerAuthUrl.searchParams.get("state")!; + expect(state).toBeTruthy(); + + const callbackRes = await fetch( + `${server.apiUrl}/api/tools/oauth/callback?${new URLSearchParams({ state, code: "fixture-auth-code", iss: issuer })}`, + { headers: { cookie, Accept: "text/html" }, redirect: "manual" }, + ); + expect(callbackRes.status).toBe(303); + expect(callbackRes.headers.get("location")).toMatch(new RegExp(`^/[^/]+/apps/${connectionId}/permissions\\?success=1$`)); + + const getAfterRes = await fetch(`${server.apiUrl}/api/tool-connections/${connectionId}`, { headers: { cookie } }); + expect(getAfterRes.status).toBe(200); + expect(await getAfterRes.json()).toMatchObject({ id: connectionId, status: "active", enabled: true }); + + const listAfterRes = await fetch(`${server.apiUrl}/api/companies/${f.companyId}/tools/connections`, { headers: { cookie } }); + expect(listAfterRes.status).toBe(200); + const listAfter = await listAfterRes.json() as { connections: Array<{ id: string; status: string; firstSignInPending?: boolean }> }; + expect(listAfter.connections.find(c => c.id === connectionId)?.firstSignInPending).toBeUndefined(); + + await expect( + server.db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connectionId)), + ).resolves.toEqual([ + expect.objectContaining({ kind: "user", subjectUserId: f.userId, status: "active" }), + ]); + } finally { + provider = null; + } + }); + it("delegates and revokes an owned credential with actual agent attribution", async () => { const f = await fixture(); const created = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { @@ -257,6 +401,9 @@ describe("connection management delegated policy and profile access", () => { expect(created, JSON.stringify(created)).toMatchObject({ status: 201 }); const handoff = await f.request("POST", `/tools/oauth/${created.body.id}/start`, { asCurrentUser: true }); expect(handoff, JSON.stringify(handoff)).toMatchObject({ status: 200, body: { expiresAt: null, requiredUserAction: { userId: f.userId } } }); + const handoffUrl = new URL(handoff.body.authorizationUrl, "https://paperclip.example"); + expect(handoffUrl.searchParams.get("resume")).toBe(created.body.id); + expect(handoffUrl.searchParams.get("source")).toBe("google-workspace"); const [unselected] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.id)); expect(unselected.config.workspaceSetup).toBeUndefined(); const services = { gmail: "read" as const }; diff --git a/server/src/__tests__/generic-mcp-connection.test.ts b/server/src/__tests__/generic-mcp-connection.test.ts index ae85753be94..c819e2699a8 100644 --- a/server/src/__tests__/generic-mcp-connection.test.ts +++ b/server/src/__tests__/generic-mcp-connection.test.ts @@ -1777,6 +1777,100 @@ describeEmbeddedPostgres("generic remote MCP connections", () => { ]); }); + it("keeps a personal OAuth URL draft that needs its user's sign-in instead of deleting it", async () => { + const fixture = installMcpOAuthFixture({ auth: "oauth" }); + const company = await createCompany(db); + const app = createRouteApp(db); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL); + + // Declaring OAuth up front means the draft has no user grant yet, so its + // first probe answers "needs the current user's authorization". + const response = await request(app) + .post(`/api/companies/${company.id}/tools/apps/connect`) + .send({ + link: MCP_URL, + name: "Fixture personal declared OAuth", + authMode: "oauth", + grantKind: "user", + }); + expect(response.status, JSON.stringify(response.body)).toBe(201); + const connected = response.body; + expect(connected.auth).toMatchObject({ kind: "oauth", issuer: ISSUER, startUrl: expect.any(String) }); + + const [draft] = await db.select().from(toolConnections) + .where(eq(toolConnections.id, connected.connectionId)); + expect(draft).toMatchObject({ status: "draft", credentialPolicy: "per_user", createdByUserId: "board-user" }); + await request(app).get(`/api/tool-connections/${connected.connectionId}`).expect(200); + + const authorizationUrl = new URL(connected.auth.startUrl); + const code = fixture.issueAuthorizationCode(connected.auth.startUrl); + await request(app) + .get("/api/tools/oauth/callback") + .set("Accept", "text/html") + .query({ state: authorizationUrl.searchParams.get("state")!, code, iss: ISSUER }) + .expect(303); + await expect( + db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connected.connectionId)), + ).resolves.toEqual([expect.objectContaining({ kind: "user", subjectUserId: "board-user", status: "active" })]); + }); + + it("does not return a sign-in link to a personal draft that setup removed", async () => { + // No OAuth metadata anywhere, so sign-in cannot start and setup is undone. + vi.spyOn(globalThis, "fetch").mockImplementation(async () => new Response( + JSON.stringify({ error: "not_found" }), + { status: 404, headers: { "content-type": "application/json" } }, + )); + const company = await createCompany(db); + const app = createRouteApp(db); + + const response = await request(app) + .post(`/api/companies/${company.id}/tools/apps/connect`) + .send({ link: MCP_URL, name: "Fixture personal OAuth without metadata", authMode: "oauth", grantKind: "user" }); + expect(response.status, JSON.stringify(response.body)).toBe(422); + expect(response.body.details).toMatchObject({ code: "user_authorization_required", connectionRemoved: true }); + expect(response.body.details).not.toHaveProperty("setupUrl"); + expect(response.body.details).not.toHaveProperty("reconnectUrl"); + await expect( + db.select().from(toolConnections).where(eq(toolConnections.companyId, company.id)), + ).resolves.toHaveLength(0); + }); + + it("hands an agent's custom-server sign-in to the draft's own page", async () => { + installMcpOAuthFixture({ auth: "oauth" }); + const company = await createCompany(db); + const service = toolAccessService(db); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Setup helper", role: "engineer", status: "active", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning(); + const agentActor = { + actorType: "agent" as const, + actorId: agent!.id, + managementContext: { + actor: { type: "agent", agentId: agent!.id, companyId: company.id, source: "agent_key" }, + responsibleUserId: "board-user", + reauthorize: async () => undefined, + }, + } as unknown as Parameters[2]["actor"]; + + const connected = await service.connectGalleryApp(company.id, { + link: MCP_URL, + name: "Fixture agent-started personal OAuth", + authMode: "oauth", + grantKind: "user", + }, agentActor); + expect(connected.auth).toMatchObject({ kind: "oauth" }); + + const handoff = await service.startOAuth(company.id, connected.connectionId, { + redirectUri: REDIRECT_URI, + actor: agentActor, + subjectUserId: "board-user", + }); + // The connect wizard turns a link with no app source back to the Apps + // list; the connection page lets the user sign in as themselves. + expect(handoff.authorizationUrl).toBe(`/${company.issuePrefix}/apps/${connected.connectionId}/permissions`); + const [draft] = await db.select().from(toolConnections) + .where(eq(toolConnections.id, connected.connectionId)); + expect(draft).toMatchObject({ status: "draft", createdByUserId: "board-user" }); + }); + it("creates a separate fresh personal URL connection and keeps explicit reconnect owner-bound", async () => { const fixture = installMcpOAuthFixture({ auth: "oauth" }); const company = await createCompany(db); diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts index 00125148b87..c3a66600839 100644 --- a/server/src/services/tool-access.ts +++ b/server/src/services/tool-access.ts @@ -2993,13 +2993,25 @@ export function toolAccessService( allowUnauthenticatedProbe: unauthenticatedPersonalProbe, }); } catch (error) { + const healthFailureCode = + error instanceof HttpError ? asRecord(error.details).code : null; + // A new personal OAuth draft has no user grant until the callback, so + // its probe stops at "needs the current user's authorization" before + // any request reaches the server. That is the same sign-in-required + // state as a 401 challenge, not a failed setup: keep the draft and + // start sign-in instead of deleting it and returning its dead link. + const personalOAuthDraftNeedsSignIn = + healthFailureCode === "user_authorization_required" && + genericAuthKind === "oauth" && + Boolean(personalIdentityUserId) && + !retainedPersonalIdentity?.grant; if ( (!galleryEntry || remoteMcpConnector) && input.authMode !== "none" && input.authMode !== "bearer" && input.authMode !== "custom_headers" && error instanceof HttpError && - asRecord(error.details).code === "oauth_challenge" + (healthFailureCode === "oauth_challenge" || personalOAuthDraftNeedsSignIn) ) { const [oauthConnection] = await db .select() @@ -3125,6 +3137,7 @@ export function toolAccessService( } catch (error) { if (personalPublicSetupEstablished) throw error; let identityRollbackError: unknown = null; + let removedConnectionId: string | null = null; let preserveConcurrentRevival = false; if (connectionRow && revivedConnectionPrevious) { const attemptedConnection = connectionRow; @@ -3256,10 +3269,11 @@ export function toolAccessService( } } else if (connectionRow) { const failedConnectionId = connectionRow.id; - await writeToolConnectionHealthChange(db, { companyId, id: failedConnectionId }, tx => tx + const removed = await writeToolConnectionHealthChange(db, { companyId, id: failedConnectionId }, tx => tx .delete(toolConnections) .where(eq(toolConnections.id, failedConnectionId))) - .catch(() => undefined); + .then(() => true, () => false); + if (removed) removedConnectionId = failedConnectionId; } if ( !preserveConcurrentRevival && @@ -3303,10 +3317,30 @@ export function toolAccessService( }, ); } - throw error; + throw withoutRemovedConnectionLinks(error, removedConnectionId); } } + // A setup failure deletes its new draft, so a credential error raised while + // probing it must not hand the caller a link to that draft: the link would + // open a connection that no longer exists. Edit the error in place so its + // remote-failure classification, keyed by identity, still applies. + function withoutRemovedConnectionLinks(error: unknown, removedConnectionId: string | null): unknown { + if (!removedConnectionId || !(error instanceof HttpError)) return error; + const details = asRecord(error.details); + const removedPath = `/apps/${removedConnectionId}/permissions`; + if (details.setupUrl !== removedPath && details.reconnectUrl !== removedPath) return error; + const rest = { ...details }; + delete rest.setupUrl; + delete rest.reconnectUrl; + error.details = { + ...rest, + connectionRemoved: true, + nextStep: "This setup was not saved. Start the connection again; do not send a link to this setup.", + }; + return error; + } + async function assertCatalogEntriesForConnection( companyId: string, connectionId: string, diff --git a/server/src/services/tool-access/oauth/authorization-start.ts b/server/src/services/tool-access/oauth/authorization-start.ts index 065eadae0c8..3faef1f6e1c 100644 --- a/server/src/services/tool-access/oauth/authorization-start.ts +++ b/server/src/services/tool-access/oauth/authorization-start.ts @@ -234,9 +234,18 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies if (!company) throw notFound("Company not found"); // A relative app route: the agent links it in chat, where it opens on // whichever host the person uses, never the server's own listen address. - const destination = `/${encodeURIComponent(company.prefix)}/apps/${connection.credentialSource === "vercel_connect" ? "vercel-connect" : "connect"}?${new URLSearchParams({ - [connection.status === "draft" ? "resume" : "reconnect"]: connection.id, - ...(sourceTemplateKey ? { source: sourceTemplateKey } : {}), ...(intentLink ? { intent: intentLink.id } : {}) })}`; + // The connect wizard only opens for a known app source. A custom server + // has none, so send its user to the connection's own page, where they + // sign in as themselves. + const customServer = !sourceTemplateKey && connection.credentialSource !== "vercel_connect"; + const query = new URLSearchParams(customServer + ? { ...(intentLink ? { intent: intentLink.id } : {}) } + : { [connection.status === "draft" ? "resume" : "reconnect"]: connection.id, + ...(sourceTemplateKey ? { source: sourceTemplateKey } : {}), ...(intentLink ? { intent: intentLink.id } : {}) }).toString(); + const destination = (customServer + ? `/${encodeURIComponent(company.prefix)}/apps/${encodeURIComponent(connection.id)}/permissions` + : `/${encodeURIComponent(company.prefix)}/apps/${connection.credentialSource === "vercel_connect" ? "vercel-connect" : "connect"}`) + + (query ? `?${query}` : ""); return { connectionId: connection.id, provider: sourceTemplateKey ?? "oauth", authorizationUrl: destination, expiresAt: null }; }