From 0cae122fe589bdc16191db59775aaf790ff2faa8 Mon Sep 17 00:00:00 2001 From: yannickmonney <102406702+yannickmonney@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:58:38 +0000 Subject: [PATCH 1/7] fix(platform): carry Add or Reconnect intent through the OAuth state Every completed consent for a connector without a workspace id (Gmail, Outlook, Google Drive, Teams) renewed the connector's default grant: a second account added through Add credential silently replaced the first, and Reconnect on any other row rewrote the default instead (#3711). The pending authorization now carries the intent. Migration 0130 adds app.connector_oauth_states.reconnect_credential_id (NULL = Add, no foreign key); the start door takes an optional credentialId and keeps it only when it names an OAuth grant of that organization and connector. The callback reads the intent from the consumed row alone, re-checks the initiator's membership and developer role, and refuses a Reconnect whose credential is gone before redeeming the code. storeOauth2Grant runs as one transaction under a per-(organization, connector) advisory lock, row-locks the Reconnect target before reading the siblings, and lets a pure planner decide: Add stores a new credential under a free name, Reconnect renews exactly its credential (needs-reauth cleared, disabled kept) or saves nothing, Slack keeps one credential per workspace and refuses a Reconnect into another. Every credential create takes the same pair lock, so concurrent first adds no longer die on the name or default index. New fixed pages: credential_missing, account_mismatch, forbidden. The native-Postgres lane checkConnectorOauthIntent proves each case; the claim-race probe's initiator is now a member of its organization. --- .../core/http_connectors/error_page.ts | 27 +- .../0130_connector_oauth_reconnect_target.sql | 26 + .../domains/connector_credentials/service.ts | 220 ++++-- .../connectors/oauth-grant-plan.test.ts | 257 +++++++ .../domains/connectors/oauth-grant-plan.ts | 132 ++++ .../connectors/oauth-intent.integration.ts | 699 ++++++++++++++++++ .../domains/connectors/oauth-routes.test.ts | 143 +++- .../domains/connectors/oauth-routes.ts | 64 +- .../backend/domains/connectors/oauth.test.ts | 434 ++++++++--- .../backend/domains/connectors/oauth.ts | 365 ++++++--- .../platform/backend/integration-check.ts | 24 + .../platform/lib/shared/connector-consent.ts | 22 + 12 files changed, 2088 insertions(+), 325 deletions(-) create mode 100644 services/platform/backend/db/migrations/0130_connector_oauth_reconnect_target.sql create mode 100644 services/platform/backend/domains/connectors/oauth-grant-plan.test.ts create mode 100644 services/platform/backend/domains/connectors/oauth-grant-plan.ts create mode 100644 services/platform/backend/domains/connectors/oauth-intent.integration.ts create mode 100644 services/platform/lib/shared/connector-consent.ts diff --git a/services/platform/backend/core/http_connectors/error_page.ts b/services/platform/backend/core/http_connectors/error_page.ts index 1a15954090..686827e1d8 100644 --- a/services/platform/backend/core/http_connectors/error_page.ts +++ b/services/platform/backend/core/http_connectors/error_page.ts @@ -29,7 +29,14 @@ export type ConnectorErrorKind = /** The Slack workspace is already connected to a different organization. */ | 'workspace_claimed' /** Tokens were obtained but could not be stored. */ - | 'storage_failed'; + | 'storage_failed' + /** The credential a Reconnect named is gone, or no OAuth grant of this + * connector in this organization. */ + | 'credential_missing' + /** A Reconnect was consented in another workspace than its credential's. */ + | 'account_mismatch' + /** The member may no longer write this organization's credentials. */ + | 'forbidden'; interface ErrorCopy { readonly title: string; @@ -80,6 +87,24 @@ const ERROR_COPY: Record = { 'Access was granted but storing it failed, so the connector is not connected. Try again; if it keeps failing, contact an administrator.', status: 500, }, + credential_missing: { + title: 'This credential cannot be reconnected', + detail: + 'It was removed, or it is not an OAuth connection of this connector, so nothing was saved and no other credential changed. Check your connector settings, and add the account again if you still need it.', + status: 404, + }, + account_mismatch: { + title: 'That is a different workspace', + detail: + 'You authorized another workspace than the one this credential connects, so nothing was saved. Reconnect again and choose the same workspace, or use Add credential to connect the other one.', + status: 409, + }, + forbidden: { + title: 'You can no longer connect connectors here', + detail: + 'Your access to this organization changed while the connection was in progress, so nothing was saved. Owners, Admins and Developers can connect connectors; ask an organization admin.', + status: 403, + }, }; function escapeHtml(value: string): string { diff --git a/services/platform/backend/db/migrations/0130_connector_oauth_reconnect_target.sql b/services/platform/backend/db/migrations/0130_connector_oauth_reconnect_target.sql new file mode 100644 index 0000000000..97d83e41a6 --- /dev/null +++ b/services/platform/backend/db/migrations/0130_connector_oauth_reconnect_target.sql @@ -0,0 +1,26 @@ +-- What a pending connector consent is FOR travels with its state row, so the +-- callback never has to guess it. Before this, every completed consent for a +-- connector without a workspace id (Gmail, Outlook, Google Drive, Teams) +-- renewed the connector's default grant: a second account added through Add +-- credential silently replaced the first, and Reconnect on any other row +-- rewrote the default instead (#3711). +-- +-- `reconnect_credential_id` names the credential a Reconnect renews — the one +-- the start door checked belongs to this organization and connector and is an +-- OAuth grant. NULL is an Add: the consent stores a NEW credential. The value +-- lives only on the server-side row keyed by the state's hash, so nothing on +-- the callback request can re-target it. +-- +-- No foreign key, on purpose. The target can be deleted while the vendor asks +-- for consent: CASCADE would drop the pending row (the user would read "link +-- expired"), SET NULL would quietly turn the Reconnect into an Add, and a +-- plain reference would block the delete. The callback re-reads the target +-- under a row lock instead and refuses with its own page when it is gone. +-- +-- Rolling-deploy safe: the column is nullable and the previous image neither +-- writes nor reads it. Its pending rows read as Add here, which never +-- overwrites a credential; a consent this image starts and the previous image +-- completes takes the previous image's path, as every consent does today. + +ALTER TABLE app.connector_oauth_states + ADD COLUMN IF NOT EXISTS reconnect_credential_id text; diff --git a/services/platform/backend/domains/connector_credentials/service.ts b/services/platform/backend/domains/connector_credentials/service.ts index 0eafb8ee16..af4b1bcbdd 100644 --- a/services/platform/backend/domains/connector_credentials/service.ts +++ b/services/platform/backend/domains/connector_credentials/service.ts @@ -449,6 +449,21 @@ function assertNameFree( } } +/** + * Serialize the writes that decide from the pair's sibling list — a new + * credential's default flag and its free name — for the caller's transaction. + * Two adds that read the siblings at once would otherwise pick the same name, + * or both become the default, and the loser would die on the unique index + * instead of numbering past the winner. Re-entrant within one transaction. + */ +export async function lockCredentialPair( + tx: TransactionSql, + organizationId: string, + connectorSlug: string, +): Promise { + await tx`SELECT pg_advisory_xact_lock(hashtextextended(${`connector-credentials:${organizationId}:${connectorSlug}`}, 0))`; +} + async function clearOtherDefaults( tx: TransactionSql, organizationId: string, @@ -497,7 +512,7 @@ function toMasked(row: CredentialRow): MaskedCredential { /** The organization's credentials, masked, connector-then-name ordered. */ export async function listCredentials( - sql: Sql, + sql: Db, organizationId: string, connectorSlug?: string, ): Promise { @@ -519,6 +534,38 @@ export async function getCredential( return toMasked(await requireOwnRow(sql, organizationId, credentialId)); } +/** + * The OAuth grant a Reconnect names, or null when `credentialId` is not this + * organization's, not this connector's, or not an OAuth grant — one answer + * for all three, so a caller cannot tell a foreign id from a missing one. + * `forUpdate` locks the row for the caller's transaction: a delete racing + * the renewal then waits for it, or wins first and this answers null. + */ +export async function findOauth2Grant( + db: Db, + args: { + organizationId: string; + connectorSlug: string; + credentialId: string; + forUpdate?: boolean; + }, +): Promise { + const rows = args.forUpdate + ? await db` + SELECT ${db.unsafe(CREDENTIAL_COLUMNS)} FROM app.connector_credentials + WHERE id = ${args.credentialId} AND org_id = ${args.organizationId} + AND connector_slug = ${args.connectorSlug} AND auth_method = 'oauth2' + FOR UPDATE + ` + : await db` + SELECT ${db.unsafe(CREDENTIAL_COLUMNS)} FROM app.connector_credentials + WHERE id = ${args.credentialId} AND org_id = ${args.organizationId} + AND connector_slug = ${args.connectorSlug} AND auth_method = 'oauth2' + `; + const row = rows[0]; + return row === undefined ? null : toMasked(row); +} + export interface CreateCredentialArgs { organizationId: string; connectorSlug: string; @@ -595,6 +642,7 @@ async function insertPreparedCredential( args: CreateCredentialArgs, prepared: PreparedCredential, ): Promise<{ credentialId: string }> { + await lockCredentialPair(tx, args.organizationId, args.connectorSlug); const siblings = await rowsForConnector( tx, args.organizationId, @@ -675,88 +723,100 @@ export async function updateCredential( sql: Sql, args: UpdateCredentialArgs, ): Promise { - await sql.begin(async (tx) => { - const row = await requireOwnRow(tx, args.organizationId, args.credentialId); - const connector = requireConnectorAuthMethod( + await sql.begin((tx) => updateCredentialInTransaction(tx, args)); +} + +/** + * {@link updateCredential} on a transaction the CALLER owns — for a flow + * whose update must commit together with its own reads and writes. The + * connector OAuth callback renews the credential a Reconnect named inside + * the transaction that row-locked it, so a concurrent delete cannot slip + * between the check and the write. + */ +export async function updateCredentialInTransaction( + tx: TransactionSql, + args: UpdateCredentialArgs, +): Promise { + const row = await requireOwnRow(tx, args.organizationId, args.credentialId); + const connector = requireConnectorAuthMethod( + row.connectorSlug, + row.authMethod, + ); + + let name = row.name; + if (args.name !== undefined) { + name = normalizeName(args.name); + const siblings = await rowsForConnector( + tx, + args.organizationId, row.connectorSlug, - row.authMethod, ); - - let name = row.name; - if (args.name !== undefined) { - name = normalizeName(args.name); - const siblings = await rowsForConnector( - tx, - args.organizationId, - row.connectorSlug, - ); - assertNameFree(siblings, name, row.id); - } - let sealed: ReturnType | undefined; - if (args.secret !== undefined) { - sealed = sealPayload(buildPayload(row.authMethod, args.secret)); - } - let endpointUrl = row.endpointUrl; - if (args.endpointUrl !== undefined) { - endpointUrl = normalizeEndpointUrl(connector, args.endpointUrl) ?? null; - } - let config = row.config; - if (args.config !== undefined) { - try { - config = - withImapFromAddress( - row.connectorSlug, - normalizeConfig(connector, args.config), - args.secret?.username, - ) ?? null; - } catch (error) { - translateAppError(error); - } - } - if (args.isDefault === true) { - await clearOtherDefaults( - tx, - args.organizationId, - row.connectorSlug, - row.id, - ); + assertNameFree(siblings, name, row.id); + } + let sealed: ReturnType | undefined; + if (args.secret !== undefined) { + sealed = sealPayload(buildPayload(row.authMethod, args.secret)); + } + let endpointUrl = row.endpointUrl; + if (args.endpointUrl !== undefined) { + endpointUrl = normalizeEndpointUrl(connector, args.endpointUrl) ?? null; + } + let config = row.config; + if (args.config !== undefined) { + try { + config = + withImapFromAddress( + row.connectorSlug, + normalizeConfig(connector, args.config), + args.secret?.username, + ) ?? null; + } catch (error) { + translateAppError(error); } - await tx` - UPDATE app.connector_credentials SET - name = ${name}, - encrypted_data = ${sealed !== undefined ? tx.json(toJson(sealed.encryptedData)) : tx.unsafe('encrypted_data')}, - masked_preview = ${sealed !== undefined ? (sealed.maskedPreview ?? null) : tx.unsafe('masked_preview')}, - endpoint_url = ${endpointUrl}, - config = ${config === null ? null : tx.json(toJson(config))}, - status = ${args.status ?? tx.unsafe('status')}, - status_detail = ${args.statusDetail !== undefined ? args.statusDetail : tx.unsafe('status_detail')}, - is_default = ${args.isDefault ?? tx.unsafe('is_default')}, - updated_at_ms = ${Date.now()} - WHERE id = ${row.id} - `; - await createAuditLog(tx, { - organizationId: args.organizationId, - ...actorFields(args.actor), - action: 'connector_credential.updated', - category: 'connector', - resourceType: 'connector_credential', - resourceId: row.id, - resourceName: name, - previousState: credentialState(row), - newState: credentialState({ - name, - status: args.status ?? row.status, - isDefault: args.isDefault ?? row.isDefault, - }), - changedFields: UPDATABLE_FIELDS.filter( - (field) => args[field] !== undefined, - ), - metadata: { - connectorSlug: row.connectorSlug, - authMethod: row.authMethod, - }, - status: 'success', - }); + } + if (args.isDefault === true) { + await clearOtherDefaults( + tx, + args.organizationId, + row.connectorSlug, + row.id, + ); + } + await tx` + UPDATE app.connector_credentials SET + name = ${name}, + encrypted_data = ${sealed !== undefined ? tx.json(toJson(sealed.encryptedData)) : tx.unsafe('encrypted_data')}, + masked_preview = ${sealed !== undefined ? (sealed.maskedPreview ?? null) : tx.unsafe('masked_preview')}, + endpoint_url = ${endpointUrl}, + config = ${config === null ? null : tx.json(toJson(config))}, + status = ${args.status ?? tx.unsafe('status')}, + status_detail = ${args.statusDetail !== undefined ? args.statusDetail : tx.unsafe('status_detail')}, + is_default = ${args.isDefault ?? tx.unsafe('is_default')}, + updated_at_ms = ${Date.now()} + WHERE id = ${row.id} + `; + await createAuditLog(tx, { + organizationId: args.organizationId, + ...actorFields(args.actor), + action: 'connector_credential.updated', + category: 'connector', + resourceType: 'connector_credential', + resourceId: row.id, + resourceName: name, + previousState: credentialState(row), + newState: credentialState({ + name, + status: args.status ?? row.status, + isDefault: args.isDefault ?? row.isDefault, + }), + changedFields: UPDATABLE_FIELDS.filter( + (field) => args[field] !== undefined, + ), + metadata: { + connectorSlug: row.connectorSlug, + authMethod: row.authMethod, + }, + status: 'success', }); } diff --git a/services/platform/backend/domains/connectors/oauth-grant-plan.test.ts b/services/platform/backend/domains/connectors/oauth-grant-plan.test.ts new file mode 100644 index 0000000000..d040074720 --- /dev/null +++ b/services/platform/backend/domains/connectors/oauth-grant-plan.test.ts @@ -0,0 +1,257 @@ +// @vitest-environment node + +/** + * Where a completed consent lands, per intent (#3711). An Add never renews + * another credential — the connector's default least of all; a Reconnect + * renews exactly the credential it named or nothing; Slack keeps one + * credential per workspace. + */ + +import { describe, expect, it } from 'vitest'; + +import type { ConsentIntent } from '../../../lib/shared/connector-consent.ts'; +import { + planOauth2Grant, + type GrantPlanInput, + type GrantSibling, +} from './oauth-grant-plan.ts'; + +const row = ( + id: string, + name: string, + extra: Partial = {}, +): GrantSibling => ({ + id, + name, + authMethod: 'oauth2', + status: 'active', + ...extra, +}); + +const ADD: ConsentIntent = { kind: 'add' }; +const reconnect = (credentialId: string): ConsentIntent => ({ + kind: 'reconnect', + credentialId, +}); + +const plan = (overrides: Partial) => + planOauth2Grant({ + organizationId: 'org-1', + intent: ADD, + displayName: 'Gmail', + nameMax: 100, + siblings: [], + target: null, + route: null, + targetTeams: [], + ...overrides, + }); + +describe('planOauth2Grant — Add', () => { + it('stores the first credential under the connector name', () => { + expect(plan({})).toEqual({ kind: 'create', name: 'Gmail' }); + }); + + it('adds a second account as a NEW credential instead of renewing the default', () => { + expect( + plan({ siblings: [row('cred-default', 'Gmail', { status: 'active' })] }), + ).toEqual({ kind: 'create', name: 'Gmail 2' }); + }); + + it('numbers past every sibling name, whatever its method, case-insensitively', () => { + expect( + plan({ + siblings: [ + row('a', 'gmail'), + row('b', 'Gmail 2', { status: 'needs-reauth' }), + row('c', 'GMAIL 3', { authMethod: 'api-key' }), + ], + }), + ).toEqual({ kind: 'create', name: 'Gmail 4' }); + }); +}); + +describe('planOauth2Grant — Reconnect', () => { + const siblings = [ + row('cred-default', 'Gmail'), + row('cred-sales', 'Gmail sales', { status: 'needs-reauth' }), + ]; + + it('renews exactly the credential it named — not the default', () => { + expect( + plan({ + intent: reconnect('cred-sales'), + siblings, + target: siblings[1] ?? null, + }), + ).toEqual({ kind: 'renew', credentialId: 'cred-sales', reactivate: true }); + }); + + it('refuses when the credential is gone, rather than landing on a sibling', () => { + expect( + plan({ intent: reconnect('cred-sales'), siblings, target: null }), + ).toEqual({ kind: 'refuse', reason: 'credential_missing' }); + }); + + it('refuses a locked row that is not the one the intent names', () => { + expect( + plan({ + intent: reconnect('cred-sales'), + siblings, + target: siblings[0] ?? null, + }), + ).toEqual({ kind: 'refuse', reason: 'credential_missing' }); + }); + + it('renews a disabled credential without lifting the pause', () => { + const disabled = row('cred-paused', 'Gmail paused', { status: 'disabled' }); + expect( + plan({ + intent: reconnect('cred-paused'), + siblings: [...siblings, disabled], + target: disabled, + }), + ).toEqual({ + kind: 'renew', + credentialId: 'cred-paused', + reactivate: false, + }); + }); +}); + +describe('planOauth2Grant — Slack workspaces', () => { + const slack = (overrides: Partial) => + plan({ displayName: 'Slack', ...overrides }); + const routed = (credentialId: string, organizationId = 'org-1') => ({ + organizationId, + credentialId, + }); + + it('claims the workspace for a first connection', () => { + expect(slack({ team: { id: 'T-1', name: 'Acme' } })).toEqual({ + kind: 'create', + name: 'Slack', + claimTeamId: 'T-1', + }); + }); + + it('renews the credential an already connected workspace routes to, even on Add', () => { + expect( + slack({ + siblings: [row('cred-1', 'Slack')], + team: { id: 'T-1' }, + route: routed('cred-1'), + }), + ).toEqual({ kind: 'renew', credentialId: 'cred-1', reactivate: true }); + }); + + it('keeps a disabled workspace credential disabled when it is renewed', () => { + expect( + slack({ + siblings: [row('cred-1', 'Slack', { status: 'disabled' })], + team: { id: 'T-1' }, + route: routed('cred-1'), + }), + ).toEqual({ kind: 'renew', credentialId: 'cred-1', reactivate: false }); + }); + + it('names a second workspace after itself', () => { + expect( + slack({ + siblings: [row('cred-1', 'Slack')], + team: { id: 'T-2', name: 'Second Workspace' }, + }), + ).toEqual({ + kind: 'create', + name: 'Slack (Second Workspace)', + claimTeamId: 'T-2', + }); + }); + + it('falls back to a counter when the workspace name is unknown or taken', () => { + expect( + slack({ + siblings: [row('cred-1', 'Slack'), row('cred-2', 'Slack 2')], + team: { id: 'T-3' }, + }), + ).toEqual({ kind: 'create', name: 'Slack 3', claimTeamId: 'T-3' }); + }); + + it('keeps a long workspace label within the name limit, with room for a counter', () => { + const outcome = slack({ + nameMax: 30, + siblings: [row('cred-1', 'Slack')], + team: { id: 'T-4', name: 'A workspace with a very long name' }, + }); + expect(outcome).toMatchObject({ kind: 'create', claimTeamId: 'T-4' }); + expect(outcome.kind === 'create' && outcome.name.length).toBe(24); + }); + + it('refuses a workspace another organization holds, for either intent', () => { + for (const intent of [ADD, reconnect('cred-1')]) { + expect( + slack({ + intent, + siblings: [row('cred-1', 'Slack')], + target: row('cred-1', 'Slack'), + team: { id: 'T-1' }, + route: routed('cred-x', 'org-other'), + }), + ).toEqual({ kind: 'refuse', reason: 'workspace_claimed' }); + } + }); + + it('renews a Reconnect in the workspace the credential is routed from', () => { + expect( + slack({ + intent: reconnect('cred-2'), + siblings: [row('cred-1', 'Slack'), row('cred-2', 'Slack (B)')], + target: row('cred-2', 'Slack (B)'), + team: { id: 'T-B' }, + route: routed('cred-2'), + targetTeams: ['T-B'], + }), + ).toEqual({ kind: 'renew', credentialId: 'cred-2', reactivate: true }); + }); + + it("refuses a Reconnect into a workspace another of this organization's credentials holds", () => { + expect( + slack({ + intent: reconnect('cred-2'), + siblings: [row('cred-1', 'Slack'), row('cred-2', 'Slack (B)')], + target: row('cred-2', 'Slack (B)'), + team: { id: 'T-A' }, + route: routed('cred-1'), + targetTeams: ['T-B'], + }), + ).toEqual({ kind: 'refuse', reason: 'account_mismatch' }); + }); + + it('refuses a Reconnect into an unrouted workspace when the credential holds another', () => { + expect( + slack({ + intent: reconnect('cred-2'), + siblings: [row('cred-2', 'Slack (B)')], + target: row('cred-2', 'Slack (B)'), + team: { id: 'T-NEW' }, + targetTeams: ['T-B'], + }), + ).toEqual({ kind: 'refuse', reason: 'account_mismatch' }); + }); + + it('routes a workspace to a Reconnect target that holds none yet', () => { + expect( + slack({ + intent: reconnect('cred-9'), + siblings: [row('cred-9', 'Slack imported')], + target: row('cred-9', 'Slack imported'), + team: { id: 'T-9' }, + }), + ).toEqual({ + kind: 'renew', + credentialId: 'cred-9', + reactivate: true, + claimTeamId: 'T-9', + }); + }); +}); diff --git a/services/platform/backend/domains/connectors/oauth-grant-plan.ts b/services/platform/backend/domains/connectors/oauth-grant-plan.ts new file mode 100644 index 0000000000..21a038f464 --- /dev/null +++ b/services/platform/backend/domains/connectors/oauth-grant-plan.ts @@ -0,0 +1,132 @@ +import type { ConsentIntent } from '../../../lib/shared/connector-consent.ts'; +import { uniqueCredentialName } from '../../../lib/shared/utils/credential-name.ts'; + +/** + * Where a completed connector consent lands — the pure half of + * `storeOauth2Grant`, decided from what the store transaction read under its + * locks, so every branch is testable without a database. + * + * The consent carries its INTENT from the start door, on the state row: + * + * - **Add** stores a NEW credential under a name no sibling holds (the + * connector's display name, then `Gmail 2`, …). It never renews another + * credential — with one exception that is not a different account: a Slack + * workspace this organization already connected renews its own credential, + * because the team route (one workspace, one credential) says the consent + * is for exactly that row. + * - **Reconnect** renews exactly the credential it named, keeping its id, + * name, default flag and references. Gone meanwhile: refused, nothing + * written — never redirected onto a sibling. For Slack, the consent must be + * for that credential's own workspace; another workspace is refused instead + * of leaving one workspace's token behind another's route. + * + * A renewal clears `needs-reauth`; a DISABLED credential stays disabled — the + * pause is the operator's decision and only Enable lifts it. + */ + +/** Room a workspace-named label leaves for the ` N` a collision appends. */ +const NAME_COUNTER_ROOM = 6; + +export interface GrantSibling { + id: string; + name: string; + authMethod: string; + status: string; +} + +export interface GrantPlanInput { + organizationId: string; + intent: ConsentIntent; + /** The connector's catalog display name — the first credential's label. */ + displayName: string; + /** The longest label a credential may carry. */ + nameMax: number; + /** Every credential of the (organization, connector) pair, any method. */ + siblings: readonly GrantSibling[]; + /** A Reconnect's target as the transaction locked it; null when it is + * gone, foreign, of another connector or no OAuth grant. */ + target: GrantSibling | null; + /** The workspace the vendor reported (Slack's `team`), when it has one. */ + team?: { id: string; name?: string }; + /** The team route of `team.id`, when one exists. */ + route: { organizationId: string; credentialId: string } | null; + /** Workspaces already routed to the Reconnect target. */ + targetTeams: readonly string[]; +} + +export type GrantPlan = + | { + kind: 'renew'; + credentialId: string; + /** False for a disabled credential: the grant is renewed, the pause kept. */ + reactivate: boolean; + /** Route this workspace to the renewed credential in the same transaction. */ + claimTeamId?: string; + } + | { kind: 'create'; name: string; claimTeamId?: string } + | { + kind: 'refuse'; + reason: 'credential_missing' | 'account_mismatch' | 'workspace_claimed'; + }; + +export function planOauth2Grant(input: GrantPlanInput): GrantPlan { + const { team, route } = input; + // A workspace belongs to one organization, whatever the intent. + if (route !== null && route.organizationId !== input.organizationId) { + return { kind: 'refuse', reason: 'workspace_claimed' }; + } + + if (input.intent.kind === 'reconnect') { + const { target } = input; + if (target === null || target.id !== input.intent.credentialId) { + return { kind: 'refuse', reason: 'credential_missing' }; + } + const renew = { + kind: 'renew' as const, + credentialId: target.id, + reactivate: target.status !== 'disabled', + }; + if (team === undefined) return renew; + if (route !== null) { + return route.credentialId === target.id + ? renew + : { kind: 'refuse', reason: 'account_mismatch' }; + } + // An unrouted workspace joins the target only when the target holds no + // other one — never one workspace's token behind another's route. + if (input.targetTeams.some((teamId) => teamId !== team.id)) { + return { kind: 'refuse', reason: 'account_mismatch' }; + } + return { ...renew, claimTeamId: team.id }; + } + + const grants = input.siblings.filter((row) => row.authMethod === 'oauth2'); + const routed = + team === undefined || route === null + ? undefined + : grants.find((row) => row.id === route.credentialId); + if (routed !== undefined) { + return { + kind: 'renew', + credentialId: routed.id, + reactivate: routed.status !== 'disabled', + }; + } + + const workspace = team?.name?.trim() ?? ''; + const base = + grants.length === 0 || workspace.length === 0 + ? input.displayName + : `${input.displayName} (${workspace})`.slice( + 0, + input.nameMax - NAME_COUNTER_ROOM, + ); + return { + kind: 'create', + name: uniqueCredentialName( + input.siblings.map((row) => row.name), + base, + ), + ...(team !== undefined ? { claimTeamId: team.id } : {}), + }; +} diff --git a/services/platform/backend/domains/connectors/oauth-intent.integration.ts b/services/platform/backend/domains/connectors/oauth-intent.integration.ts new file mode 100644 index 0000000000..0133b024d0 --- /dev/null +++ b/services/platform/backend/domains/connectors/oauth-intent.integration.ts @@ -0,0 +1,699 @@ +/** Real Postgres proof that a connector consent lands where its intent says + * (#3711). Add credential stores a NEW credential and never renews the + * connector's default; Reconnect renews exactly the credential its row named + * — id, name, default flag and references kept — or saves nothing when that + * credential is gone. The intent rides the pending authorization row the + * start door minted (migration 0130), so an expired or tampered one, a + * denied consent, a member who lost the role mid-consent and a row the + * previous image minted all behave; two Adds completing at once number past + * each other; Slack keeps one credential per workspace. + * + * The start door runs over HTTP. The consent completes at the service seam + * with an injected token endpoint answered in process — no vendor is called. */ +import { randomUUID } from 'node:crypto'; + +import type { Sql } from 'postgres'; +import { z } from 'zod'; + +import { hashStateToken } from '../../core/http_connectors/oauth_state.ts'; +import { + createCredential, + deleteCredential, + updateCredential, +} from '../connector_credentials/service.ts'; +import { + completeOauth2, + resolveTeamRoute, + type CallbackOutcome, +} from './oauth.ts'; + +type RecordCheck = (name: string, ok: boolean, detail: string) => void; + +interface StoredRow { + id: string; + name: string; + isDefault: boolean; + status: string; + statusDetail: string | null; + maskedPreview: string | null; + sealed: string; + createdAt: number; + updatedAt: number; + inboundSince: number | null; +} + +function cookieOf(response: Response): string { + return response.headers + .getSetCookie() + .map((entry) => entry.split(';')[0] ?? '') + .filter((pair) => pair.length > 0) + .join('; '); +} + +async function signUp( + base: string, + label: string, +): Promise<{ cookie: string; userId: string }> { + const response = await fetch(`${base}/api/auth/sign-up/email`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: base }, + body: JSON.stringify({ + email: `itest-${label}-${randomUUID().slice(0, 8)}@example.com`, + password: 'itest-password-1', + name: `Itest ${label}`, + }), + }); + const body = z + .object({ user: z.object({ id: z.string() }) }) + .safeParse(await response.json()); + return { + cookie: cookieOf(response), + userId: body.success ? body.data.user.id : '', + }; +} + +async function waitUntil( + predicate: () => Promise, + timeoutMs: number, +): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (await predicate()) return true; + await new Promise((resolve) => setTimeout(resolve, 50)); + } + return predicate(); +} + +export async function checkConnectorOauthIntent( + sql: Sql, + base: string, + record: RecordCheck, +): Promise { + const suffix = randomUUID().slice(0, 8); + const owner = await signUp(base, `oauth-intent-owner-${suffix}`); + const orgResponse = await fetch(`${base}/api/auth/organization/create`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + cookie: owner.cookie, + origin: base, + }, + body: JSON.stringify({ + name: 'OAuth intent', + slug: `oauth-intent-${suffix}`, + }), + }); + const orgBody = z + .object({ id: z.string() }) + .safeParse(await orgResponse.json()); + const orgId = orgBody.success ? orgBody.data.id : ''; + const headers = { cookie: owner.cookie, origin: base }; + + const saved = { + siteUrl: process.env.SITE_URL, + slackId: process.env.CONNECTOR_OAUTH_SLACK_CLIENT_ID, + slackSecret: process.env.CONNECTOR_OAUTH_SLACK_CLIENT_SECRET, + }; + process.env.SITE_URL = base; + process.env.CONNECTOR_OAUTH_SLACK_CLIENT_ID = 'itest-intent-slack-client'; + process.env.CONNECTOR_OAUTH_SLACK_CLIENT_SECRET = 'itest-intent-slack-secret'; + try { + // Organization OAuth apps through the real admin door, the way the + // settings card registers them. Synthetic client ids only. + const apps = await Promise.all( + ['gmail', 'outlook'].map( + async (slug) => + ( + await fetch( + `${base}/api/app/connector-oauth-apps/${slug}?orgId=${orgId}`, + { + method: 'PUT', + headers: { ...headers, 'content-type': 'application/json' }, + body: JSON.stringify({ + clientId: `itest-intent-${slug}.apps.local`, + clientSecret: `itest-intent-${slug}-secret`, + }), + }, + ) + ).status, + ), + ); + + // ---- the token endpoint, answered in process ------------------------ + // `account` is who "consents" next; the access token starts with it, so + // the stored masked preview (first 4 + last 2) names the account. + const vendor = { + account: 'ACCA', + reject: false, + calls: [] as string[], + /** When set, every exchange waits here — lets two completions overlap. */ + gate: null as Promise | null, + counter: 0, + }; + const tokenUrls = new Set([ + 'https://oauth2.googleapis.com/token', + 'https://login.microsoftonline.com/common/oauth2/v2.0/token', + 'https://slack.com/api/oauth.v2.access', + ]); + const fetchImpl = async ( + input: string | URL | Request, + init?: RequestInit, + ): Promise => { + const url = input instanceof Request ? input.url : input.toString(); + if (!tokenUrls.has(url)) { + throw new Error(`itest fake vendor: unexpected token URL ${url}`); + } + const account = vendor.account; + vendor.calls.push(`${url} ${account}`); + if (vendor.gate !== null) await vendor.gate; + if (vendor.reject) { + return Response.json({ error: 'invalid_grant' }, { status: 400 }); + } + const body = new URLSearchParams( + typeof init?.body === 'string' ? init.body : '', + ); + vendor.counter += 1; + const n = String(vendor.counter).padStart(6, '0'); + const tokens = { + access_token: `${account}.itest.${n}`, + refresh_token: `rt.${account}.${n}`, + expires_in: 3600, + scope: body.get('grant_type') === 'authorization_code' ? 'x' : 'y', + }; + return Response.json( + url.startsWith('https://slack.com/') + ? { + ok: true, + ...tokens, + team: { id: `T-${account}-${suffix}`, name: `Team ${account}` }, + } + : tokens, + ); + }; + + // ---- helpers ------------------------------------------------------------ + const pendingCount = async () => + Number( + ( + await sql<{ count: string }[]>` + SELECT count(*)::text AS count FROM app.connector_oauth_states + WHERE org_id = ${orgId} + ` + )[0]?.count ?? '-1', + ); + const rows = async (slug: string): Promise => + sql` + SELECT id, name, is_default AS "isDefault", status, + status_detail AS "statusDetail", + masked_preview AS "maskedPreview", + encrypted_data::text AS sealed, + created_at_ms::float8 AS "createdAt", + updated_at_ms::float8 AS "updatedAt", + mail_sync_inbound_since_ms::float8 AS "inboundSince" + FROM app.connector_credentials + WHERE org_id = ${orgId} AND connector_slug = ${slug} + ORDER BY created_at_ms, name + `; + const show = (list: StoredRow[]) => + list + .map( + (row) => + `${row.name}${row.isDefault ? '*' : ''}=${row.maskedPreview ?? '-'}/${row.status}`, + ) + .join(' | '); + /** The start door over HTTP; the state from the vendor redirect. */ + const start = async ( + slug: string, + credentialId?: string, + cookie = owner.cookie, + ) => { + const query = new URLSearchParams({ + connector: slug, + organizationId: orgId, + }); + if (credentialId !== undefined) query.set('credentialId', credentialId); + const response = await fetch( + `${base}/api/connectors/oauth2/start?${query.toString()}`, + { redirect: 'manual', headers: { cookie, origin: base } }, + ); + const location = response.headers.get('location') ?? ''; + const state = + location === '' + ? '' + : (new URL(location).searchParams.get('state') ?? ''); + return { status: response.status, state, body: await response.text() }; + }; + const complete = ( + state: string, + userId = owner.userId, + vendorError: string | null = null, + ): Promise => + completeOauth2( + sql, + { + state, + code: vendorError === null ? `code-${randomUUID()}` : null, + vendorError, + requesterUserId: userId, + }, + { fetchImpl }, + ); + const consent = async ( + slug: string, + account: string, + credentialId?: string, + ) => { + vendor.account = account; + const started = await start(slug, credentialId); + return { started, outcome: await complete(started.state) }; + }; + const outcomeOf = (outcome: CallbackOutcome) => + outcome.kind === 'error' ? `error/${outcome.error}` : 'connected'; + + const column = await sql<{ nullable: string }[]>` + SELECT is_nullable AS nullable FROM information_schema.columns + WHERE table_schema = 'app' AND table_name = 'connector_oauth_states' + AND column_name = 'reconnect_credential_id' + `; + + // ---- 1. two Adds: a second account is a second credential ----------- + const first = await consent('gmail', 'ACCA'); + const afterFirst = await rows('gmail'); + const second = await consent('gmail', 'ACCB'); + const afterSecond = await rows('gmail'); + const gmail = afterFirst[0]; + const gmailAfter = afterSecond.find((row) => row.id === gmail?.id); + const added = afterSecond.find((row) => row.id !== gmail?.id); + record( + 'connector oauth intent: a second Add stores a new credential and leaves the default grant as it was (#3711)', + column[0]?.nullable === 'YES' && + apps.every((status) => status === 200) && + first.started.status === 302 && + first.outcome.kind === 'connected' && + second.outcome.kind === 'connected' && + afterFirst.length === 1 && + gmail?.name === 'Gmail' && + gmail.isDefault && + (gmail.maskedPreview ?? '').startsWith('ACCA') && + afterSecond.length === 2 && + JSON.stringify(gmailAfter) === JSON.stringify(gmail) && + added?.name === 'Gmail 2' && + !added.isDefault && + (added.maskedPreview ?? '').startsWith('ACCB'), + `column=${column[0]?.nullable ?? 'MISSING'} (want YES), apps=${apps.join('/')}, outcomes=${outcomeOf(first.outcome)}/${outcomeOf(second.outcome)}, after first=${show(afterFirst)}, after second=${show(afterSecond)} (want Gmail*=ACCA… unchanged | Gmail 2=ACCB…)`, + ); + + // ---- 2. the start door keeps a target only when it is ours ---------- + const github = await createCredential(sql, { + organizationId: orgId, + connectorSlug: 'github', + authMethod: 'bearer', + name: 'GitHub bot', + secret: { token: 'ghp_itest_intent' }, + createdBy: owner.userId, + }); + const foreignOrg = `itest-intent-foreign-${suffix}`; + const foreign = await createCredential(sql, { + organizationId: foreignOrg, + connectorSlug: 'gmail', + authMethod: 'oauth2', + name: 'Gmail', + secret: { accessToken: 'FORE.itest.000000', scopes: ['x'] }, + createdBy: owner.userId, + }); + const pendingBefore = await pendingCount(); + const refusals = await Promise.all( + [ + ['another connector', github.credentialId], + ['another organization', foreign.credentialId], + ['an unknown id', randomUUID()], + ['an empty id', ''], + ].map(async ([what, id]) => { + const started = await start('gmail', id); + return { + what, + ok: + started.status === 404 && + started.state === '' && + started.body.includes('This credential cannot be reconnected'), + status: started.status, + }; + }), + ); + const pendingAfter = await pendingCount(); + const kept = await start('gmail', added?.id ?? ''); + const keptRow = await sql<{ target: string | null }[]>` + SELECT reconnect_credential_id AS target FROM app.connector_oauth_states + WHERE state_hash = ${await hashStateToken(kept.state)} + `; + const plainAdd = await start('gmail'); + const plainRow = await sql<{ target: string | null }[]>` + SELECT reconnect_credential_id AS target FROM app.connector_oauth_states + WHERE state_hash = ${await hashStateToken(plainAdd.state)} + `; + record( + 'connector oauth intent: the start door keeps a Reconnect target only when it is this organization’s OAuth grant of that connector', + refusals.every((entry) => entry.ok) && + pendingAfter === pendingBefore && + kept.status === 302 && + keptRow[0]?.target === added?.id && + plainAdd.status === 302 && + plainRow.length === 1 && + plainRow[0]?.target === null, + `${refusals.map((entry) => `${entry.what}=${entry.status}${entry.ok ? '' : ' (WRONG)'}`).join(', ')} (want 404, no state), pending minted by refusals=${pendingAfter - pendingBefore} (want 0), own target=${kept.status}/${keptRow[0]?.target === added?.id ? 'carried' : 'LOST'}, add=${plainAdd.status}/${plainRow[0]?.target === null ? 'null' : 'SET'}`, + ); + + // ---- 3. Reconnect renews exactly the named row ------------------------ + const sales = await createCredential(sql, { + organizationId: orgId, + connectorSlug: 'gmail', + authMethod: 'oauth2', + name: 'Gmail sales', + secret: { accessToken: 'SALE.itest.000000', scopes: ['x'] }, + createdBy: owner.userId, + }); + await updateCredential(sql, { + organizationId: orgId, + credentialId: sales.credentialId, + status: 'needs-reauth', + statusDetail: 'itest: token revoked', + }); + // A reference the renewal must keep: the mailbox sync's cursor. + await sql` + UPDATE app.connector_credentials SET mail_sync_inbound_since_ms = 1700000000000 + WHERE id = ${sales.credentialId} + `; + const beforeReconnect = await rows('gmail'); + const reconnected = await consent('gmail', 'ACCS', sales.credentialId); + const afterReconnect = await rows('gmail'); + const salesBefore = beforeReconnect.find( + (row) => row.id === sales.credentialId, + ); + const salesAfter = afterReconnect.find( + (row) => row.id === sales.credentialId, + ); + const othersUnchanged = + JSON.stringify( + afterReconnect.filter((row) => row.id !== sales.credentialId), + ) === + JSON.stringify( + beforeReconnect.filter((row) => row.id !== sales.credentialId), + ); + const audit = await sql<{ actorId: string }[]>` + SELECT actor_id AS "actorId" FROM app.audit_logs + WHERE org_id = ${orgId} AND resource_type = 'connector_credential' + AND resource_id = ${sales.credentialId} + AND action = 'connector_credential.updated' + ORDER BY ts DESC LIMIT 1 + `; + record( + 'connector oauth intent: Reconnect renews exactly the credential its row named — id, name, default and references kept (#3711)', + reconnected.outcome.kind === 'connected' && + afterReconnect.length === beforeReconnect.length && + salesAfter !== undefined && + salesAfter.name === 'Gmail sales' && + !salesAfter.isDefault && + salesAfter.createdAt === salesBefore?.createdAt && + salesAfter.inboundSince === 1_700_000_000_000 && + salesAfter.status === 'active' && + salesAfter.statusDetail === null && + (salesAfter.maskedPreview ?? '').startsWith('ACCS') && + salesAfter.sealed !== salesBefore?.sealed && + othersUnchanged && + audit[0]?.actorId === owner.userId, + `outcome=${outcomeOf(reconnected.outcome)}, before=${show(beforeReconnect)}, after=${show(afterReconnect)}, othersUnchanged=${othersUnchanged}, cursorKept=${salesAfter?.inboundSince === 1_700_000_000_000}, auditActor=${audit[0]?.actorId === owner.userId ? 'initiator' : (audit[0]?.actorId ?? 'none')}`, + ); + + // ---- 4. a denied consent, and a vendor that refuses the code ---------- + const beforeDenied = await rows('gmail'); + vendor.account = 'ACCX'; + const deniedStart = await start('gmail', sales.credentialId); + const callsBeforeDenied = vendor.calls.length; + const denied = await complete( + deniedStart.state, + owner.userId, + 'access_denied', + ); + const callsAfterDenied = vendor.calls.length; + vendor.reject = true; + const refused = await consent('gmail', 'ACCX', sales.credentialId); + vendor.reject = false; + const afterDenied = await rows('gmail'); + record( + 'connector oauth intent: a denied or refused consent on Reconnect leaves every credential as it was', + outcomeOf(denied) === 'error/vendor_declined' && + callsAfterDenied === callsBeforeDenied && + outcomeOf(refused.outcome) === 'error/vendor_declined' && + JSON.stringify(afterDenied) === JSON.stringify(beforeDenied), + `denied=${outcomeOf(denied)} (exchanges ${callsAfterDenied - callsBeforeDenied}, want 0), refused=${outcomeOf(refused.outcome)}, unchanged=${JSON.stringify(afterDenied) === JSON.stringify(beforeDenied)}`, + ); + + // ---- 5. an expired or tampered intent ----------------------------- + const expiring = await start('gmail', sales.credentialId); + await sql` + UPDATE app.connector_oauth_states SET expires_at_ms = ${Date.now() - 1} + WHERE state_hash = ${await hashStateToken(expiring.state)} + `; + const callsBeforeExpired = vendor.calls.length; + const expired = await complete(expiring.state); + const tamperedStart = await start('gmail', sales.credentialId); + const tampered = await complete(`${tamperedStart.state.slice(0, -2)}xx`); + const leftover = await sql<{ count: string }[]>` + SELECT count(*)::text AS count FROM app.connector_oauth_states + WHERE state_hash = ${await hashStateToken(expiring.state)} + `; + const afterExpired = await rows('gmail'); + record( + 'connector oauth intent: an expired or tampered state writes nothing and redeems no code', + outcomeOf(expired) === 'error/invalid_state' && + outcomeOf(tampered) === 'error/invalid_state' && + leftover[0]?.count === '0' && + vendor.calls.length === callsBeforeExpired && + JSON.stringify(afterExpired) === JSON.stringify(afterDenied), + `expired=${outcomeOf(expired)}, tampered=${outcomeOf(tampered)} (want invalid_state), expiredRowLeft=${leftover[0]?.count} (want 0, burned), exchanges=${vendor.calls.length - callsBeforeExpired} (want 0), unchanged=${JSON.stringify(afterExpired) === JSON.stringify(afterDenied)}`, + ); + + // ---- 6. the Reconnect target removed mid-consent -------------------- + const doomed = await createCredential(sql, { + organizationId: orgId, + connectorSlug: 'gmail', + authMethod: 'oauth2', + name: 'Gmail doomed', + secret: { accessToken: 'DOOM.itest.000000', scopes: ['x'] }, + createdBy: owner.userId, + }); + vendor.account = 'ACCR'; + const doomedStart = await start('gmail', doomed.credentialId); + await deleteCredential(sql, orgId, doomed.credentialId); + const beforeGone = await rows('gmail'); + const callsBeforeGone = vendor.calls.length; + const gone = await complete(doomedStart.state); + const callsAfterGone = vendor.calls.length; + const afterGone = await rows('gmail'); + + // The race: the delete is in flight (uncommitted) when the consent + // returns. The pre-check still sees the row and the code is redeemed, + // but the store's row lock queues behind the delete — and then finds + // nothing to write. Nothing may land on a sibling. + const racer = await createCredential(sql, { + organizationId: orgId, + connectorSlug: 'gmail', + authMethod: 'oauth2', + name: 'Gmail raced', + secret: { accessToken: 'RACE.itest.000000', scopes: ['x'] }, + createdBy: owner.userId, + }); + const racerStart = await start('gmail', racer.credentialId); + const beforeRace = (await rows('gmail')).filter( + (row) => row.id !== racer.credentialId, + ); + let releaseDelete: () => void = () => undefined; + const deleteReleased = new Promise((resolve) => { + releaseDelete = resolve; + }); + let deleteHeld: () => void = () => undefined; + const deleteInPlace = new Promise((resolve) => { + deleteHeld = resolve; + }); + const deleting = sql.begin(async (tx) => { + await tx`DELETE FROM app.connector_credentials WHERE id = ${racer.credentialId}`; + deleteHeld(); + await deleteReleased; + }); + await deleteInPlace; + const racing = complete(racerStart.state); + const queuedBehindDelete = await waitUntil(async () => { + const waiting = await sql<{ count: string }[]>` + SELECT count(*)::text AS count FROM pg_stat_activity + WHERE wait_event_type = 'Lock' AND query ILIKE '%FOR UPDATE%' + AND query ILIKE '%connector_credentials%' + `; + return waiting[0]?.count !== '0'; + }, 10_000); + releaseDelete(); + await deleting; + const raced = await racing; + const afterRace = await rows('gmail'); + record( + 'connector oauth intent: a Reconnect whose credential is removed mid-consent saves nothing and touches no sibling', + outcomeOf(gone) === 'error/credential_missing' && + callsAfterGone === callsBeforeGone && + JSON.stringify(afterGone) === JSON.stringify(beforeGone) && + queuedBehindDelete && + outcomeOf(raced) === 'error/credential_missing' && + JSON.stringify(afterRace) === JSON.stringify(beforeRace), + `deleted before the callback=${outcomeOf(gone)} (exchanges ${callsAfterGone - callsBeforeGone}, want 0), unchanged=${JSON.stringify(afterGone) === JSON.stringify(beforeGone)}; deleted during the store=${outcomeOf(raced)}, queuedBehindDelete=${queuedBehindDelete}, siblingsUnchanged=${JSON.stringify(afterRace) === JSON.stringify(beforeRace)}`, + ); + + // ---- 7. two Adds completing at once -------------------------------- + // A connector with no credential yet: both would otherwise take its + // display name and the default, and one would die on a unique index. + vendor.account = 'ACCC'; + const [one, two] = [await start('outlook'), await start('outlook')]; + let openGate: () => void = () => undefined; + vendor.gate = new Promise((resolve) => { + openGate = resolve; + }); + const both = Promise.all([complete(one.state), complete(two.state)]); + const bothExchanging = await waitUntil( + async () => + vendor.calls.filter((call) => call.includes('microsoftonline')) + .length >= 2, + 10_000, + ); + openGate(); + const outcomes = await both; + vendor.gate = null; + const outlook = await rows('outlook'); + record( + 'connector oauth intent: two Adds completing at once store two credentials under distinct names, one of them the default', + bothExchanging && + outcomes.every((outcome) => outcome.kind === 'connected') && + outlook.length === 2 && + new Set(outlook.map((row) => row.name)).size === 2 && + outlook.some((row) => row.name === 'Microsoft Outlook') && + outlook.some((row) => row.name === 'Microsoft Outlook 2') && + outlook.filter((row) => row.isDefault).length === 1, + `overlapping=${bothExchanging}, outcomes=${outcomes.map(outcomeOf).join('/')}, rows=${show(outlook)} (want Microsoft Outlook + Microsoft Outlook 2, one default)`, + ); + + // ---- 8. the initiator's access, re-checked at the callback ---------- + const developer = await signUp(base, `oauth-intent-dev-${suffix}`); + await sql` + INSERT INTO "member" ("id", "organizationId", "userId", "role", "createdAt") + VALUES (gen_random_uuid(), ${orgId}, ${developer.userId}, 'developer', ${new Date()}) + `; + const beforeDemotion = await rows('gmail'); + const demotedStart = await start('gmail', undefined, developer.cookie); + await sql` + UPDATE "member" SET "role" = 'member' + WHERE "organizationId" = ${orgId} AND "userId" = ${developer.userId} + `; + const callsBeforeDemoted = vendor.calls.length; + const demoted = await complete(demotedStart.state, developer.userId); + await sql` + UPDATE "member" SET "role" = 'developer' + WHERE "organizationId" = ${orgId} AND "userId" = ${developer.userId} + `; + const removedStart = await start( + 'gmail', + sales.credentialId, + developer.cookie, + ); + await sql` + DELETE FROM "member" + WHERE "organizationId" = ${orgId} AND "userId" = ${developer.userId} + `; + const removed = await complete(removedStart.state, developer.userId); + const afterAccess = await rows('gmail'); + record( + 'connector oauth intent: a member who lost the role or left while the vendor asked for consent stores nothing', + demotedStart.status === 302 && + removedStart.status === 302 && + outcomeOf(demoted) === 'error/forbidden' && + outcomeOf(removed) === 'error/forbidden' && + vendor.calls.length === callsBeforeDemoted && + JSON.stringify(afterAccess) === JSON.stringify(beforeDemotion), + `starts=${demotedStart.status}/${removedStart.status} (want 302), demoted=${outcomeOf(demoted)}, removed=${outcomeOf(removed)} (want forbidden), exchanges=${vendor.calls.length - callsBeforeDemoted} (want 0), unchanged=${JSON.stringify(afterAccess) === JSON.stringify(beforeDemotion)}`, + ); + + // ---- 9. a pending row the previous image minted ---------------------- + // Written with the old column list — no reconnect_credential_id. It + // must read as an Add: a new credential, the default untouched. + const legacyState = `itest-intent-legacy-${suffix}`; + const now = Date.now(); + await sql` + INSERT INTO app.connector_oauth_states ( + state_hash, org_id, user_id, connector_slug, code_verifier, + redirect_uri, created_at_ms, expires_at_ms + ) VALUES ( + ${await hashStateToken(legacyState)}, ${orgId}, ${owner.userId}, + 'gmail', 'itest-verifier-value-legacy-000000000000000', + ${`${base}/api/connectors/oauth2/callback`}, ${now}, ${now + 60_000} + ) + `; + const beforeLegacy = await rows('gmail'); + vendor.account = 'ACCL'; + const legacy = await complete(legacyState); + const afterLegacy = await rows('gmail'); + const legacyNew = afterLegacy.filter( + (row) => !beforeLegacy.some((old) => old.id === row.id), + ); + record( + 'connector oauth intent: a pending row the previous image minted completes as an Add and overwrites nothing', + legacy.kind === 'connected' && + legacyNew.length === 1 && + (legacyNew[0]?.maskedPreview ?? '').startsWith('ACCL') && + beforeLegacy.every( + (old) => + JSON.stringify(afterLegacy.find((row) => row.id === old.id)) === + JSON.stringify(old), + ), + `outcome=${outcomeOf(legacy)}, new=${show(legacyNew)}, existing unchanged=${beforeLegacy.every((old) => JSON.stringify(afterLegacy.find((row) => row.id === old.id)) === JSON.stringify(old))}`, + ); + + // ---- 10. Slack: one credential per workspace ------------------------- + await consent('slack', 'WSA'); + await consent('slack', 'WSB'); + const slackTwo = await rows('slack'); + const again = await consent('slack', 'WSA'); + const slackAgain = await rows('slack'); + const wsa = slackTwo.find((row) => row.name === 'Slack'); + const wsb = slackTwo.find((row) => row.name === 'Slack (Team WSB)'); + const wsaAgain = slackAgain.find((row) => row.id === wsa?.id); + const mismatch = await consent('slack', 'WSA', wsb?.id); + const slackMismatch = await rows('slack'); + const own = await consent('slack', 'WSB', wsb?.id); + const slackOwn = await rows('slack'); + const wsbOwn = slackOwn.find((row) => row.id === wsb?.id); + const routeB = await resolveTeamRoute(sql, `T-WSB-${suffix}`); + record( + 'connector oauth intent: Slack keeps one credential per workspace, and a Reconnect into another workspace is refused', + slackTwo.length === 2 && + wsa?.isDefault === true && + wsb !== undefined && + again.outcome.kind === 'connected' && + slackAgain.length === 2 && + wsaAgain !== undefined && + wsaAgain.sealed !== wsa.sealed && + outcomeOf(mismatch.outcome) === 'error/account_mismatch' && + JSON.stringify(slackMismatch) === JSON.stringify(slackAgain) && + own.outcome.kind === 'connected' && + wsbOwn !== undefined && + wsbOwn.sealed !== wsb.sealed && + routeB?.credentialId === wsb.id && + JSON.stringify(slackOwn.find((row) => row.id === wsa.id)) === + JSON.stringify(wsaAgain), + `after two workspaces=${show(slackTwo)}, repeat WSA=${outcomeOf(again.outcome)} rows=${slackAgain.length} renewedWSA=${wsaAgain?.sealed !== wsa?.sealed}, reconnect WSB row in WSA=${outcomeOf(mismatch.outcome)} (want account_mismatch) unchanged=${JSON.stringify(slackMismatch) === JSON.stringify(slackAgain)}, reconnect WSB row in WSB=${outcomeOf(own.outcome)} renewed=${wsbOwn?.sealed !== wsb?.sealed} route=${routeB?.credentialId === wsb?.id}`, + ); + } finally { + if (saved.siteUrl === undefined) delete process.env.SITE_URL; + else process.env.SITE_URL = saved.siteUrl; + if (saved.slackId === undefined) { + delete process.env.CONNECTOR_OAUTH_SLACK_CLIENT_ID; + } else process.env.CONNECTOR_OAUTH_SLACK_CLIENT_ID = saved.slackId; + if (saved.slackSecret === undefined) { + delete process.env.CONNECTOR_OAUTH_SLACK_CLIENT_SECRET; + } else process.env.CONNECTOR_OAUTH_SLACK_CLIENT_SECRET = saved.slackSecret; + } +} diff --git a/services/platform/backend/domains/connectors/oauth-routes.test.ts b/services/platform/backend/domains/connectors/oauth-routes.test.ts index 6f0411df51..ceefb38c26 100644 --- a/services/platform/backend/domains/connectors/oauth-routes.test.ts +++ b/services/platform/backend/domains/connectors/oauth-routes.test.ts @@ -3,10 +3,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { Auth } from '../../auth/auth.ts'; import type { SessionBundle } from '../../auth/session.ts'; -const { completeOauth2 } = vi.hoisted(() => ({ - completeOauth2: vi.fn(), +const { completeOauth2, connectorWriteAccess, startOauth2 } = vi.hoisted( + () => ({ + completeOauth2: vi.fn(), + connectorWriteAccess: vi.fn(), + startOauth2: vi.fn(), + }), +); +vi.mock('./oauth.ts', () => ({ + completeOauth2, + connectorWriteAccess, + startOauth2, })); -vi.mock('./oauth.ts', () => ({ completeOauth2, startOauth2: vi.fn() })); import { createConnectorOauthRoutes } from './oauth-routes.ts'; @@ -17,6 +25,11 @@ function app(session: SessionBundle | null) { }); } +const SIGNED_IN: SessionBundle = { + user: { id: 'u1', email: 'u@example.test', name: 'User' }, + session: { id: 's1', activeOrganizationId: 'org-1' }, +}; + describe('OAuth error recovery', () => { beforeEach(() => { vi.stubEnv('SITE_URL', 'https://tale.example'); @@ -43,10 +56,7 @@ describe('OAuth error recovery', () => { }); it('uses the signed-in session organization and a configured origin for expired state', async () => { - const response = await app({ - user: { id: 'u1', email: 'u@example.test', name: 'User' }, - session: { id: 's1', activeOrganizationId: 'org-1' }, - }).request( + const response = await app(SIGNED_IN).request( 'https://other.example/callback?state=expired&organizationId=attacker', { headers: { host: 'other.example', 'x-forwarded-proto': 'https' }, @@ -57,3 +67,122 @@ describe('OAuth error recovery', () => { ); }); }); + +describe('the consent intent', () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.stubEnv('SITE_URL', 'https://tale.example'); + vi.stubEnv('BASE_PATH', ''); + connectorWriteAccess.mockResolvedValue('allowed'); + startOauth2.mockResolvedValue({ + kind: 'redirect', + url: 'https://vendor.example/authorize?state=s', + }); + }); + afterEach(() => vi.unstubAllEnvs()); + + it('starts an Add when no credential is named', async () => { + const response = await app(SIGNED_IN).request( + '/start?connector=gmail&organizationId=org-1', + ); + expect(response.status).toBe(302); + expect(startOauth2).toHaveBeenCalledWith(expect.anything(), { + connectorSlug: 'gmail', + organizationId: 'org-1', + userId: 'u1', + publicOrigin: expect.anything(), + }); + }); + + it('starts a Reconnect of exactly the credential the link names', async () => { + await app(SIGNED_IN).request( + '/start?connector=gmail&organizationId=org-1&credentialId=cred-sales', + ); + expect(startOauth2).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ reconnectCredentialId: 'cred-sales' }), + ); + }); + + it.each([ + ['an empty credential id', ''], + ['an absurdly long credential id', 'x'.repeat(129)], + ])( + 'refuses %s instead of reading it as an Add', + async (_what, credentialId) => { + const response = await app(SIGNED_IN).request( + `/start?connector=gmail&organizationId=org-1&credentialId=${credentialId}`, + ); + expect(response.status).toBe(404); + expect(await response.text()).toContain( + 'This credential cannot be reconnected', + ); + expect(startOauth2).not.toHaveBeenCalled(); + }, + ); + + it('answers a Reconnect the service refused with the fixed page, before the vendor', async () => { + startOauth2.mockResolvedValue({ + kind: 'error', + error: 'credential_missing', + }); + const response = await app(SIGNED_IN).request( + '/start?connector=gmail&organizationId=org-1&credentialId=cred-foreign', + ); + expect(response.status).toBe(404); + expect(response.headers.get('location')).toBeNull(); + expect(await response.text()).toContain( + 'href="https://tale.example/dashboard/org-1/settings/connectors"', + ); + }); + + it('keeps the membership and role gate in front of the intent', async () => { + connectorWriteAccess.mockResolvedValue('role_forbidden'); + const denied = await app(SIGNED_IN).request( + '/start?connector=gmail&organizationId=org-1&credentialId=cred-sales', + ); + connectorWriteAccess.mockResolvedValue('not_member'); + const foreign = await app(SIGNED_IN).request( + '/start?connector=gmail&organizationId=org-2&credentialId=cred-sales', + ); + expect([denied.status, foreign.status]).toEqual([403, 403]); + expect(await foreign.text()).toBe( + 'You do not have access to this organization.', + ); + expect(startOauth2).not.toHaveBeenCalled(); + }); + + it('never lets the callback request name the credential it writes', async () => { + completeOauth2.mockResolvedValue({ + kind: 'connected', + settingsUrl: 'https://tale.example/dashboard/org-1/settings/connectors', + connectorSlug: 'gmail', + }); + const response = await app(SIGNED_IN).request( + '/callback?state=s&code=c&credentialId=cred-other&organizationId=org-2', + ); + expect(response.status).toBe(302); + expect(completeOauth2).toHaveBeenCalledWith(expect.anything(), { + state: 's', + code: 'c', + vendorError: null, + requesterUserId: 'u1', + }); + }); + + it.each([ + ['credential_missing', 404, 'This credential cannot be reconnected'], + ['account_mismatch', 409, 'That is a different workspace'], + ['forbidden', 403, 'You can no longer connect connectors here'], + ] as const)( + 'renders the %s refusal as a fixed page', + async (error, status, title) => { + completeOauth2.mockResolvedValue({ kind: 'error', error }); + const response = await app(SIGNED_IN).request('/callback?state=s&code=c'); + expect(response.status).toBe(status); + const html = await response.text(); + expect(html).toContain(`

${title}

`); + expect(html).toContain('nothing was saved'); + }, + ); +}); diff --git a/services/platform/backend/domains/connectors/oauth-routes.ts b/services/platform/backend/domains/connectors/oauth-routes.ts index 38387bd3e0..6bfedfa1fd 100644 --- a/services/platform/backend/domains/connectors/oauth-routes.ts +++ b/services/platform/backend/domains/connectors/oauth-routes.ts @@ -1,12 +1,8 @@ import { Hono } from 'hono'; import type { Sql } from 'postgres'; -import { defineAbilityFor } from '../../../lib/permissions/ability.ts'; +import { RECONNECT_CREDENTIAL_PARAM } from '../../../lib/shared/connector-consent.ts'; import type { Auth } from '../../auth/auth.ts'; -import { - MembershipError, - requireOrganizationMember, -} from '../../auth/membership.ts'; import { requireSession, type AuthEnv, @@ -18,7 +14,10 @@ import { } from '../../core/http_connectors/deployment_config.ts'; import { renderConnectorErrorPage } from '../../core/http_connectors/error_page.ts'; import { publicOrigin } from '../../core/lib/helpers/public_origin.ts'; -import { completeOauth2, startOauth2 } from './oauth.ts'; +import { completeOauth2, connectorWriteAccess, startOauth2 } from './oauth.ts'; + +/** Longer than any id a credential row carries — a probe, not a Reconnect. */ +const CREDENTIAL_ID_MAX = 128; /** * `/api/connectors/oauth2` — the browser-facing halves of the connector @@ -26,14 +25,17 @@ import { completeOauth2, startOauth2 } from './oauth.ts'; * * `start` is session-gated: it must know WHO is asking and that their role * may add credentials to the named organization — connecting a connector IS - * a credential write, just spelled as a consent flow. `callback` is - * authorized by the single-use state row, which carries the organization the - * credential is written for — nothing in the callback request can move it — - * AND bound to the session on the returning browser: the completer must be - * the member who started the flow, so a forwarded consent link cannot land a - * stranger's vendor grant in the initiator's organization. A completion - * without that session gets the same page as a forged state (not a JSON - * 401): a person is looking at this in a browser tab. + * a credential write, just spelled as a consent flow. It also takes the + * consent's intent (`lib/shared/connector-consent.ts`): no `credentialId` + * adds a new credential, a `credentialId` reconnects that one (an OAuth grant of this organization and connector, or + * the flow does not start). `callback` is authorized by the single-use state + * row, which carries the organization, the connector and that intent — + * nothing in the callback request can move them — AND bound to the session + * on the returning browser: the completer must be the member who started the + * flow, so a forwarded consent link cannot land a stranger's vendor grant in + * the initiator's organization, and must still hold the role `start` checked. + * A completion without that session gets the same page as a forged state + * (not a JSON 401): a person is looking at this in a browser tab. * * Both answer HTML error pages rather than JSON: a person is looking at this * in a browser tab, mid-flow, and needs a way back to settings. @@ -76,23 +78,20 @@ export function createConnectorOauthRoutes(deps: { app.get('/start', requireSession(deps.auth), async (c) => { const connectorSlug = c.req.query('connector') ?? ''; const organizationId = c.req.query('organizationId') ?? ''; + // Absent: an Add. Present, it must name something — an empty or absurd + // id is a broken Reconnect link, never quietly read as an Add. + const credentialId = c.req.query(RECONNECT_CREDENTIAL_PARAM); if (connectorSlug === '' || organizationId === '') { return errorPage('unsupported_connector'); } const userId = c.get('sessionBundle').user.id; - let role: string; - try { - role = (await requireOrganizationMember(deps.sql, organizationId, userId)) - .role; - } catch (error) { - if (error instanceof MembershipError) { - // Same answer for "no such organization" and "not your organization": - // the difference only helps someone enumerating org ids. - return plainText('You do not have access to this organization.', 403); - } - throw error; + const access = await connectorWriteAccess(deps.sql, organizationId, userId); + if (access === 'not_member') { + // Same answer for "no such organization" and "not your organization": + // the difference only helps someone enumerating org ids. + return plainText('You do not have access to this organization.', 403); } - if (defineAbilityFor(role).cannot('read', 'developerSettings')) { + if (access === 'role_forbidden') { return plainText( 'Your role cannot connect connectors for this organization.', 403, @@ -102,10 +101,23 @@ export function createConnectorOauthRoutes(deps: { // The consent flow returns to the domain it started on: the session // cookie the callback needs lives there, not on the canonical origin. const origin = publicOrigin(c.req.raw); + if ( + credentialId !== undefined && + (credentialId.length === 0 || credentialId.length > CREDENTIAL_ID_MAX) + ) { + return errorPage( + 'credential_missing', + organizationId, + resolvePublicBaseUrl(origin), + ); + } const outcome = await startOauth2(deps.sql, { connectorSlug, organizationId, userId, + ...(credentialId !== undefined + ? { reconnectCredentialId: credentialId } + : {}), publicOrigin: origin, }); if (outcome.kind === 'error') { diff --git a/services/platform/backend/domains/connectors/oauth.test.ts b/services/platform/backend/domains/connectors/oauth.test.ts index ae19dff952..47fcd06a0b 100644 --- a/services/platform/backend/domains/connectors/oauth.test.ts +++ b/services/platform/backend/domains/connectors/oauth.test.ts @@ -1,30 +1,38 @@ // @vitest-environment node /** - * Where a completed consent lands. The settings card advertises Reconnect for - * an oauth2 credential, and an organization may connect several Slack - * workspaces — neither may fail on the label the first credential already - * holds. A workspace already routed here renews ITS credential; a new - * workspace (or a first connection) is stored under a label no sibling has — - * and its workspace claim commits in the same transaction, so a lost claim - * keeps nothing. + * Where a completed consent lands, and who may complete it. The decision + * itself is `planOauth2Grant` (its own test); these pin the wiring around + * it: one transaction under the pair lock, the Reconnect target row-locked + * and renewed in place, an Add stored as a new credential, a lost workspace + * claim rolled back — and a callback that re-checks the initiator's access + * and the Reconnect target before the code is ever redeemed. */ import type { Sql } from 'postgres'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -const { createCredentialInTransaction, listCredentials, updateCredential } = - vi.hoisted(() => ({ - createCredentialInTransaction: vi.fn(), - listCredentials: vi.fn(), - updateCredential: vi.fn(), - })); +const { + createCredentialInTransaction, + findOauth2Grant, + listCredentials, + lockCredentialPair, + updateCredentialInTransaction, +} = vi.hoisted(() => ({ + createCredentialInTransaction: vi.fn(), + findOauth2Grant: vi.fn(), + listCredentials: vi.fn(), + lockCredentialPair: vi.fn(), + updateCredentialInTransaction: vi.fn(), +})); vi.mock('../connector_credentials/service.ts', () => ({ CREDENTIAL_NAME_MAX: 100, createCredentialInTransaction, + findOauth2Grant, listCredentials, - updateCredential, + lockCredentialPair, + updateCredentialInTransaction, })); import { @@ -39,13 +47,14 @@ interface Route { } /** - * A tagged-template `sql` that answers the team-route lookup and the route - * claim, and runs `begin` callbacks against itself — the store-and-claim - * transaction is what a NEW credential lands in. A claim on a workspace whose - * route names another organization answers no row, exactly as the - * `ON CONFLICT … WHERE org_id = $me` insert does. + * A tagged-template `sql` that answers the team-route reads and the route + * claim, and runs `begin` callbacks against itself. A claim on a workspace + * whose route names another organization answers no row, exactly as the + * `ON CONFLICT … WHERE org_id = $me` insert does. `rolledBack` records a + * transaction whose callback threw. */ -function sqlWithRoutes(routes: Record): Sql { +function sqlWithRoutes(routes: Record) { + const state = { rolledBack: 0 }; const tag = ( strings: TemplateStringsArray, ...values: unknown[] @@ -61,29 +70,44 @@ function sqlWithRoutes(routes: Record): Sql { : [{ teamId }], ); } + if (text.includes('credential_id = ')) { + const credentialId = String(values[1]); + return Promise.resolve( + Object.entries(routes) + .filter(([, route]) => route.credentialId === credentialId) + .map(([teamId]) => ({ teamId })), + ); + } if (text.includes('FROM app.connector_team_routes')) { - const teamId = String(values[0]); - const route = routes[teamId]; + const route = routes[String(values[0])]; return Promise.resolve(route === undefined ? [] : [route]); } return Promise.resolve([]); }; - const begin = (callback: (tx: unknown) => Promise) => callback(tag); + const begin = async (callback: (tx: unknown) => Promise) => { + try { + return await callback(tag); + } catch (error) { + state.rolledBack += 1; + throw error; + } + }; // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- only the tag call and `begin` are exercised - return Object.assign(tag, { begin }) as unknown as Sql; + return { sql: Object.assign(tag, { begin }) as unknown as Sql, state }; } const credential = ( id: string, name: string, extra: Partial<{ + connectorSlug: string; authMethod: string; isDefault: boolean; - createdAt: number; + status: string; }> = {}, ) => ({ id, - connectorSlug: 'slack', + connectorSlug: 'gmail', authMethod: 'oauth2', name, isDefault: false, @@ -94,137 +118,255 @@ const credential = ( }); const TOKENS = { - accessToken: 'xoxb-fresh', - refreshToken: 'xoxe-fresh', + accessToken: 'ya29.fresh', + refreshToken: '1//fresh', expiresAt: 4_102_444_800_000, - scopes: ['chat:write'], + scopes: ['https://www.googleapis.com/auth/gmail.readonly'], }; -const grant = ( +const gmailGrant = ( sql: Sql, - tokens: typeof TOKENS & { teamId?: string; teamName?: string }, + intent: { kind: 'add' } | { kind: 'reconnect'; credentialId: string }, ) => storeOauth2Grant(sql, { organizationId: 'org-1', - connectorSlug: 'slack', + connectorSlug: 'gmail', userId: 'user-1', - displayName: 'Slack', - tokens, + displayName: 'Gmail', + intent, + tokens: TOKENS, }); beforeEach(() => { vi.clearAllMocks(); createCredentialInTransaction.mockResolvedValue({ credentialId: 'cred-new' }); - updateCredential.mockResolvedValue(undefined); + updateCredentialInTransaction.mockResolvedValue(undefined); + lockCredentialPair.mockResolvedValue(undefined); + findOauth2Grant.mockResolvedValue(null); + listCredentials.mockResolvedValue([]); }); describe('storeOauth2Grant', () => { - it('stores the first connection under the connector display name', async () => { - listCredentials.mockResolvedValue([]); - const outcome = await grant(sqlWithRoutes({}), { - ...TOKENS, - teamId: 'T-1', - teamName: 'Acme', + it('adds a second account as a new credential and never touches the default (#3711)', async () => { + listCredentials.mockResolvedValue([ + credential('cred-default', 'Gmail', { isDefault: true }), + ]); + const { sql } = sqlWithRoutes({}); + await expect(gmailGrant(sql, { kind: 'add' })).resolves.toEqual({ + ok: true, + credentialId: 'cred-new', + renewed: false, }); - expect(outcome).toEqual({ credentialId: 'cred-new', renewed: false }); - expect(updateCredential).not.toHaveBeenCalled(); + expect(updateCredentialInTransaction).not.toHaveBeenCalled(); expect(createCredentialInTransaction).toHaveBeenCalledWith( expect.anything(), expect.objectContaining({ - name: 'Slack', + connectorSlug: 'gmail', authMethod: 'oauth2', + name: 'Gmail 2', secret: TOKENS, + createdBy: 'user-1', }), ); + // Serialized per pair before the siblings are read, so two adds number + // past each other instead of colliding. + expect(lockCredentialPair.mock.invocationCallOrder[0]).toBeLessThan( + listCredentials.mock.invocationCallOrder[0] ?? 0, + ); + expect(lockCredentialPair).toHaveBeenCalledWith( + expect.anything(), + 'org-1', + 'gmail', + ); }); - it('renews the credential a connected workspace already routes to', async () => { - listCredentials.mockResolvedValue([credential('cred-1', 'Slack')]); - const outcome = await grant( - sqlWithRoutes({ - 'T-1': { organizationId: 'org-1', credentialId: 'cred-1' }, - }), - { ...TOKENS, teamId: 'T-1' }, - ); - expect(outcome).toEqual({ credentialId: 'cred-1', renewed: true }); - expect(createCredentialInTransaction).not.toHaveBeenCalled(); - expect(updateCredential).toHaveBeenCalledWith(expect.anything(), { + it('renews exactly the credential a Reconnect named, locked, keeping its name (#3711)', async () => { + const sales = credential('cred-sales', 'Gmail sales', { + status: 'needs-reauth', + }); + listCredentials.mockResolvedValue([ + credential('cred-default', 'Gmail', { isDefault: true }), + sales, + ]); + findOauth2Grant.mockResolvedValue(sales); + const { sql } = sqlWithRoutes({}); + await expect( + gmailGrant(sql, { kind: 'reconnect', credentialId: 'cred-sales' }), + ).resolves.toEqual({ ok: true, credentialId: 'cred-sales', renewed: true }); + expect(findOauth2Grant).toHaveBeenCalledWith(expect.anything(), { organizationId: 'org-1', - credentialId: 'cred-1', - secret: TOKENS, - status: 'active', - statusDetail: null, - // The renewal is audited under the person who completed the grant. - actor: { userId: 'user-1' }, + connectorSlug: 'gmail', + credentialId: 'cred-sales', + forUpdate: true, }); + // Locked before the siblings are read: a delete that won is missing + // from both reads. + expect(findOauth2Grant.mock.invocationCallOrder[0]).toBeLessThan( + listCredentials.mock.invocationCallOrder[0] ?? 0, + ); + expect(updateCredentialInTransaction).toHaveBeenCalledTimes(1); + expect(updateCredentialInTransaction).toHaveBeenCalledWith( + expect.anything(), + { + organizationId: 'org-1', + credentialId: 'cred-sales', + secret: TOKENS, + status: 'active', + statusDetail: null, + // The renewal is audited under the person who completed the grant. + actor: { userId: 'user-1' }, + }, + ); + expect(createCredentialInTransaction).not.toHaveBeenCalled(); }); - it('names a second workspace after itself instead of colliding', async () => { - listCredentials.mockResolvedValue([credential('cred-1', 'Slack')]); - const outcome = await grant( - sqlWithRoutes({ - 'T-1': { organizationId: 'org-1', credentialId: 'cred-1' }, - }), - { ...TOKENS, teamId: 'T-2', teamName: 'Second Workspace' }, - ); - expect(outcome.renewed).toBe(false); - expect(createCredentialInTransaction).toHaveBeenCalledWith( + it('renews a disabled credential without re-enabling it', async () => { + const paused = credential('cred-paused', 'Gmail paused', { + status: 'disabled', + }); + listCredentials.mockResolvedValue([paused]); + findOauth2Grant.mockResolvedValue(paused); + const { sql } = sqlWithRoutes({}); + await gmailGrant(sql, { kind: 'reconnect', credentialId: 'cred-paused' }); + expect(updateCredentialInTransaction).toHaveBeenCalledWith( expect.anything(), - expect.objectContaining({ name: 'Slack (Second Workspace)' }), + { + organizationId: 'org-1', + credentialId: 'cred-paused', + secret: TOKENS, + actor: { userId: 'user-1' }, + }, ); }); - it('falls back to a counter when the workspace name is unknown or taken', async () => { + it('writes nothing when the Reconnect target is gone', async () => { listCredentials.mockResolvedValue([ - credential('cred-1', 'Slack'), - credential('cred-2', 'Slack 2'), + credential('cred-default', 'Gmail', { isDefault: true }), ]); - await grant(sqlWithRoutes({}), { ...TOKENS, teamId: 'T-3' }); - expect(createCredentialInTransaction).toHaveBeenCalledWith( + const { sql } = sqlWithRoutes({}); + await expect( + gmailGrant(sql, { kind: 'reconnect', credentialId: 'cred-gone' }), + ).resolves.toEqual({ ok: false, reason: 'credential_missing' }); + expect(updateCredentialInTransaction).not.toHaveBeenCalled(); + expect(createCredentialInTransaction).not.toHaveBeenCalled(); + }); + + it('renews the credential an already connected Slack workspace routes to', async () => { + const routedGrant = credential('cred-1', 'Slack', { + connectorSlug: 'slack', + }); + listCredentials.mockResolvedValue([routedGrant]); + findOauth2Grant.mockResolvedValue(routedGrant); + const { sql } = sqlWithRoutes({ + 'T-1': { organizationId: 'org-1', credentialId: 'cred-1' }, + }); + const outcome = await storeOauth2Grant(sql, { + organizationId: 'org-1', + connectorSlug: 'slack', + userId: 'user-1', + displayName: 'Slack', + intent: { kind: 'add' }, + tokens: { ...TOKENS, teamId: 'T-1' }, + }); + expect(outcome).toEqual({ + ok: true, + credentialId: 'cred-1', + renewed: true, + }); + // The routed row is locked before it is renewed. + expect(findOauth2Grant).toHaveBeenCalledWith( expect.anything(), - expect.objectContaining({ name: 'Slack 3' }), + expect.objectContaining({ credentialId: 'cred-1', forUpdate: true }), ); + expect(createCredentialInTransaction).not.toHaveBeenCalled(); }); - it("never renews another organization's credential for the same workspace — the claim refuses and nothing is kept", async () => { - listCredentials.mockResolvedValue([]); + it('never keeps a credential for a workspace another organization claims — the transaction rolls back', async () => { + const { sql, state } = sqlWithRoutes({ + 'T-1': { organizationId: 'org-other', credentialId: 'cred-x' }, + }); + // The in-transaction read sees the foreign route and refuses outright. await expect( - grant( - sqlWithRoutes({ - 'T-1': { organizationId: 'org-other', credentialId: 'cred-x' }, - }), - { ...TOKENS, teamId: 'T-1' }, - ), - ).rejects.toThrow('workspace already connected to another organization'); - expect(updateCredential).not.toHaveBeenCalled(); - // The credential row was written INSIDE the transaction the lost claim - // rolls back — the database keeps nothing. + storeOauth2Grant(sql, { + organizationId: 'org-1', + connectorSlug: 'slack', + userId: 'user-1', + displayName: 'Slack', + intent: { kind: 'add' }, + tokens: { ...TOKENS, teamId: 'T-1' }, + }), + ).resolves.toEqual({ ok: false, reason: 'workspace_claimed' }); + expect(createCredentialInTransaction).not.toHaveBeenCalled(); + expect(state.rolledBack).toBe(0); + }); + + it('rolls back the new credential when the claim loses a race it could not see', async () => { + // The route read finds nothing (the other claim is uncommitted); the + // claim insert then loses on the key. + const routes: Record = {}; + const { sql, state } = sqlWithRoutes(routes); + createCredentialInTransaction.mockImplementation(async () => { + routes['T-RACE'] = { + organizationId: 'org-other', + credentialId: 'cred-x', + }; + return { credentialId: 'cred-new' }; + }); + await expect( + storeOauth2Grant(sql, { + organizationId: 'org-1', + connectorSlug: 'slack', + userId: 'user-1', + displayName: 'Slack', + intent: { kind: 'add' }, + tokens: { ...TOKENS, teamId: 'T-RACE' }, + }), + ).resolves.toEqual({ ok: false, reason: 'workspace_claimed' }); expect(createCredentialInTransaction).toHaveBeenCalledTimes(1); + expect(state.rolledBack).toBe(1); }); - it('reconnects a connector without a workspace notion through its default grant', async () => { + it('refuses a Slack Reconnect consented in a workspace another credential holds', async () => { + const target = credential('cred-2', 'Slack (B)', { + connectorSlug: 'slack', + }); listCredentials.mockResolvedValue([ - credential('cred-old', 'Gmail 2', { createdAt: 1 }), - credential('cred-default', 'Gmail', { isDefault: true, createdAt: 2 }), - credential('cred-key', 'Gmail key', { authMethod: 'api-key' }), + credential('cred-1', 'Slack', { connectorSlug: 'slack' }), + target, ]); - const outcome = await storeOauth2Grant(sqlWithRoutes({}), { - organizationId: 'org-1', - connectorSlug: 'gmail', - userId: 'user-1', - displayName: 'Gmail', - tokens: TOKENS, + findOauth2Grant.mockResolvedValue(target); + const { sql } = sqlWithRoutes({ + 'T-A': { organizationId: 'org-1', credentialId: 'cred-1' }, + 'T-B': { organizationId: 'org-1', credentialId: 'cred-2' }, }); - expect(outcome).toEqual({ credentialId: 'cred-default', renewed: true }); - expect(createCredentialInTransaction).not.toHaveBeenCalled(); + await expect( + storeOauth2Grant(sql, { + organizationId: 'org-1', + connectorSlug: 'slack', + userId: 'user-1', + displayName: 'Slack', + intent: { kind: 'reconnect', credentialId: 'cred-2' }, + tokens: { ...TOKENS, teamId: 'T-A' }, + }), + ).resolves.toEqual({ ok: false, reason: 'account_mismatch' }); + expect(updateCredentialInTransaction).not.toHaveBeenCalled(); }); }); -describe('completeOauth2 — the completer must be the initiator', () => { +describe('completeOauth2 — the completer must be the initiator, and still allowed', () => { /** A `sql` whose state consume answers the pending row for `stateHash` - * (once — a second consume finds nothing, like `DELETE … RETURNING`). */ - function sqlWithPending(stateHash: string, userId: string): Sql { + * (once — a second consume finds nothing, like `DELETE … RETURNING`), and + * whose membership read answers `roles`. */ + function sqlWithPending( + stateHash: string, + userId: string, + options: { + roles?: Record; + reconnectCredentialId?: string | null; + } = {}, + ): Sql { let consumed = false; + const roles = options.roles ?? { 'user-1': 'developer' }; const tag = ( strings: TemplateStringsArray, ...values: unknown[] @@ -237,13 +379,32 @@ describe('completeOauth2 — the completer must be the initiator', () => { { organizationId: 'org-1', userId, - connectorSlug: 'slack', + connectorSlug: 'gmail', codeVerifier: 'verifier', redirectUri: 'https://tale.example/api/connectors/oauth2/callback', + reconnectCredentialId: options.reconnectCredentialId ?? null, expiresAt: Date.now() + 60_000, }, ]); } + if (text.includes('FROM "member"')) { + const role = roles[String(values[1])]; + return Promise.resolve( + role === undefined + ? [] + : [ + { + id: 'm-1', + organizationId: 'org-1', + userId: values[1], + role, + }, + ], + ); + } + if (text.includes('FROM "organization"')) { + return Promise.resolve([{ id: 'org-1' }]); + } return Promise.resolve([]); }; // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- only the tag call is exercised @@ -264,7 +425,7 @@ describe('completeOauth2 — the completer must be the initiator', () => { expect(outcome).toEqual({ kind: 'error', error: 'invalid_state' }); expect(fetchImpl).not.toHaveBeenCalled(); expect(createCredentialInTransaction).not.toHaveBeenCalled(); - expect(updateCredential).not.toHaveBeenCalled(); + expect(updateCredentialInTransaction).not.toHaveBeenCalled(); // The state is gone: the rightful user cannot finish it either. await expect( completeOauth2( @@ -288,11 +449,66 @@ describe('completeOauth2 — the completer must be the initiator', () => { ).resolves.toEqual({ kind: 'error', error: 'invalid_state' }); }); + it.each([ + ['lost the role that writes credentials', { 'user-1': 'member' }], + ['was disabled', { 'user-1': 'disabled' }], + ['left the organization', {}], + ])( + 'refuses an initiator who %s while the vendor asked for consent', + async (_what, roles) => { + const state = mintStateToken(); + const sql = sqlWithPending(await hashStateToken(state), 'user-1', { + roles, + }); + const fetchImpl = vi.fn(); + await expect( + completeOauth2( + sql, + { + state, + code: 'code-1', + vendorError: null, + requesterUserId: 'user-1', + }, + { fetchImpl }, + ), + ).resolves.toEqual({ kind: 'error', error: 'forbidden' }); + expect(fetchImpl).not.toHaveBeenCalled(); + expect(createCredentialInTransaction).not.toHaveBeenCalled(); + expect(updateCredentialInTransaction).not.toHaveBeenCalled(); + }, + ); + + it('refuses a Reconnect whose credential is gone before redeeming the code', async () => { + const state = mintStateToken(); + const sql = sqlWithPending(await hashStateToken(state), 'user-1', { + reconnectCredentialId: 'cred-gone', + }); + const fetchImpl = vi.fn(); + await expect( + completeOauth2( + sql, + { state, code: 'code-1', vendorError: null, requesterUserId: 'user-1' }, + { fetchImpl }, + ), + ).resolves.toEqual({ + kind: 'error', + error: 'credential_missing', + organizationId: 'org-1', + }); + expect(findOauth2Grant).toHaveBeenCalledWith(expect.anything(), { + organizationId: 'org-1', + connectorSlug: 'gmail', + credentialId: 'cred-gone', + }); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + it('lets the initiator through to the exchange step', async () => { const state = mintStateToken(); const sql = sqlWithPending(await hashStateToken(state), 'user-1'); - // Past the binding check the flow looks for the vendor app; none is - // configured here, which is the NEXT refusal — proof the check passed. + // Past the binding and access checks the flow looks for the vendor app; + // none is configured here, which is the NEXT refusal — proof they passed. await expect( completeOauth2(sql, { state, diff --git a/services/platform/backend/domains/connectors/oauth.ts b/services/platform/backend/domains/connectors/oauth.ts index 7d216d8c29..93beb351b8 100644 --- a/services/platform/backend/domains/connectors/oauth.ts +++ b/services/platform/backend/domains/connectors/oauth.ts @@ -1,7 +1,12 @@ import type { Sql } from 'postgres'; import { findConnector } from '../../../lib/connectors/catalog.ts'; -import { uniqueCredentialName } from '../../../lib/shared/utils/credential-name.ts'; +import { defineAbilityFor } from '../../../lib/permissions/ability.ts'; +import type { ConsentIntent } from '../../../lib/shared/connector-consent.ts'; +import { + MembershipError, + requireOrganizationMember, +} from '../../auth/membership.ts'; import { generatePkcePair } from '../../core/enterprise_sso/pkce.ts'; import { buildAuthorizeUrl } from '../../core/http_connectors/authorize_url.ts'; import { @@ -24,13 +29,16 @@ import { import { CREDENTIAL_NAME_MAX, createCredentialInTransaction, + findOauth2Grant, listCredentials, - updateCredential, + lockCredentialPair, + updateCredentialInTransaction, } from '../connector_credentials/service.ts'; import { applyMicrosoftTenant, resolveConnectorOauthApp, } from './oauth-apps.ts'; +import { planOauth2Grant } from './oauth-grant-plan.ts'; /** * The OAuth2 authorization-code flow for connectors on Postgres — the 0.4 @@ -49,7 +57,9 @@ import { * What changes is the substrate: the pending authorization is a row in * `app.connector_oauth_states`, and single-use is a `DELETE … RETURNING` — * one statement, so two replayed callbacks cannot both observe it (the 0.4 - * property, kept by a different mechanism). The Slack workspace route is a + * property, kept by a different mechanism). The row also carries what the + * consent is FOR — an Add, or the one credential a Reconnect renews — so the + * callback stores it there and nowhere else. The Slack workspace route is a * primary key on `team_id`, so "one workspace, one organization" is an * invariant the database holds rather than a read-two-and-refuse check. */ @@ -94,6 +104,9 @@ export interface PendingAuthorization { connectorSlug: string; codeVerifier: string; redirectUri: string; + /** The credential a Reconnect renews; null for an Add, which stores a NEW + * credential. Checked at the start door, re-checked at the callback. */ + reconnectCredentialId: string | null; } /** Record the authorization the browser is about to be redirected into. */ @@ -113,11 +126,11 @@ export async function createPendingAuthorization( await sql` INSERT INTO app.connector_oauth_states ( state_hash, org_id, user_id, connector_slug, code_verifier, - redirect_uri, created_at_ms, expires_at_ms + redirect_uri, reconnect_credential_id, created_at_ms, expires_at_ms ) VALUES ( ${args.stateHash}, ${args.organizationId}, ${args.userId}, ${args.connectorSlug}, ${args.codeVerifier}, ${args.redirectUri}, - ${now}, ${now + OAUTH_STATE_TTL_MS} + ${args.reconnectCredentialId}, ${now}, ${now + OAUTH_STATE_TTL_MS} ) `; } @@ -143,6 +156,7 @@ async function consumePendingAuthorization( connectorSlug: string; codeVerifier: string; redirectUri: string; + reconnectCredentialId: string | null; expiresAt: number; }[] >` @@ -152,6 +166,7 @@ async function consumePendingAuthorization( connector_slug AS "connectorSlug", code_verifier AS "codeVerifier", redirect_uri AS "redirectUri", + reconnect_credential_id AS "reconnectCredentialId", expires_at_ms::float8 AS "expiresAt" `; const row = rows[0]; @@ -166,9 +181,41 @@ async function consumePendingAuthorization( connectorSlug: row.connectorSlug, codeVerifier: row.codeVerifier, redirectUri: row.redirectUri, + reconnectCredentialId: row.reconnectCredentialId, }; } +/** A pending row's intent, as the grant store reads it. */ +function intentOf(reconnectCredentialId: string | null): ConsentIntent { + return reconnectCredentialId === null + ? { kind: 'add' } + : { kind: 'reconnect', credentialId: reconnectCredentialId }; +} + +/** + * Whether `userId` may add or renew connector credentials in the + * organization: an active member whose role carries the developer + * capability — the gate the credential routes write behind. Asked at BOTH + * ends of a consent, because a membership can end or a role change while the + * vendor is asking for consent, and the callback writes as that person. + */ +export async function connectorWriteAccess( + sql: Sql, + organizationId: string, + userId: string, +): Promise<'allowed' | 'not_member' | 'role_forbidden'> { + let role: string; + try { + role = (await requireOrganizationMember(sql, organizationId, userId)).role; + } catch (error) { + if (error instanceof MembershipError) return 'not_member'; + throw error; + } + return defineAbilityFor(role).cannot('read', 'developerSettings') + ? 'role_forbidden' + : 'allowed'; +} + /** The organization a Slack workspace is connected to, or null. */ export async function resolveTeamRoute( sql: Sql, @@ -181,6 +228,19 @@ export async function resolveTeamRoute( return rows[0] ?? null; } +/** The workspaces routed to one of this organization's credentials. */ +async function teamsRoutedTo( + sql: Sql, + organizationId: string, + credentialId: string, +): Promise { + const rows = await sql<{ teamId: string }[]>` + SELECT team_id AS "teamId" FROM app.connector_team_routes + WHERE org_id = ${organizationId} AND credential_id = ${credentialId} + `; + return rows.map((row) => row.teamId); +} + /** * Point a workspace at this organization's credential. Refuses when another * organization already holds it — the upsert only matches its own org row, so @@ -212,36 +272,43 @@ export async function claimTeamRoute( return { ok: true }; } -/** Room a workspace-named label leaves for the ` N` a collision appends. */ -const NAME_COUNTER_ROOM = 6; - export interface Oauth2GrantArgs { organizationId: string; connectorSlug: string; userId: string; /** The connector's catalog display name — the first credential's label. */ displayName: string; + /** What the consent was started FOR — from the consumed state row. */ + intent: ConsentIntent; tokens: Oauth2Tokens; } +export type StoreGrantOutcome = + | { ok: true; credentialId: string; renewed: boolean } + | { + ok: false; + reason: 'credential_missing' | 'account_mismatch' | 'workspace_claimed'; + }; + /** - * Where a completed consent lands. + * Store a completed consent where its intent says (`planOauth2Grant`): an Add + * becomes a NEW credential under a label no sibling holds, a Reconnect renews + * exactly the credential it named, and a Slack workspace already connected + * here renews its own credential — never the connector's default in place of + * any of them. * - * A workspace this organization already connected — the team route names its - * credential — is a RECONNECT: that credential takes the fresh grant and is - * active again, so the settings card's Reconnect action (and a second consent - * for the same workspace) renews what is there instead of failing on the - * label it already holds. A connector with no workspace notion reconnects - * the same way — the pair's one oauth2 credential (its default, when several - * exist) is the grant being renewed. Everything else is a NEW connection: a - * first one, or a second Slack workspace — stored under a label no sibling - * holds (the connector's display name for the first, the workspace name or a - * counter after that). + * ONE transaction, serialized per (organization, connector): the sibling + * list, the Reconnect target (row-locked), the team route and the write are + * one consistent decision, so two consents completing at once number past + * each other instead of colliding on a label or the default, and a target + * deleted meanwhile is refused rather than written. A new or re-routed + * workspace claims its route in the same transaction: the route's key decides + * a claim race and the loser keeps nothing. */ export async function storeOauth2Grant( sql: Sql, args: Oauth2GrantArgs, -): Promise<{ credentialId: string; renewed: boolean }> { +): Promise { const { tokens } = args; const secret = { accessToken: tokens.accessToken, @@ -251,81 +318,117 @@ export async function storeOauth2Grant( ...(tokens.expiresAt !== undefined ? { expiresAt: tokens.expiresAt } : {}), scopes: tokens.scopes, }; - const siblings = await listCredentials( - sql, - args.organizationId, - args.connectorSlug, - ); - const grants = siblings.filter((row) => row.authMethod === 'oauth2'); - - let renewId: string | null = null; - if (tokens.teamId !== undefined) { - const route = await resolveTeamRoute(sql, tokens.teamId); - if ( - route !== null && - route.organizationId === args.organizationId && - grants.some((row) => row.id === route.credentialId) - ) { - renewId = route.credentialId; - } - } else if (grants.length > 0) { - const oldest = [...grants].sort((a, b) => a.createdAt - b.createdAt)[0]; - renewId = grants.find((row) => row.isDefault)?.id ?? oldest?.id ?? null; - } - - if (renewId !== null) { - await updateCredential(sql, { - organizationId: args.organizationId, - credentialId: renewId, - secret, - status: 'active', - statusDetail: null, - actor: { userId: args.userId }, - }); - console.info( - `[connectors:oauth2] "${args.connectorSlug}" grant renewed for organization ${args.organizationId}`, - ); - return { credentialId: renewId, renewed: true }; - } + const team = + tokens.teamId === undefined + ? undefined + : { + id: tokens.teamId, + ...(tokens.teamName !== undefined ? { name: tokens.teamName } : {}), + }; - const workspace = tokens.teamName?.trim() ?? ''; - const base = - grants.length === 0 || workspace.length === 0 - ? args.displayName - : `${args.displayName} (${workspace})`.slice( - 0, - CREDENTIAL_NAME_MAX - NAME_COUNTER_ROOM, - ); - // Store the credential and claim the workspace in ONE transaction. Two - // organizations can pass the pre-check for the same workspace at once; - // the route's key decides the winner, and the loser must keep nothing — - // a committed credential for a workspace routed elsewhere would be a - // live foreign token stored (and default) for this organization. - const name = uniqueCredentialName( - siblings.map((row) => row.name), - base, - ); - let created!: { credentialId: string }; - await sql.begin(async (tx) => { - created = await createCredentialInTransaction(tx, { - organizationId: args.organizationId, - connectorSlug: args.connectorSlug, - authMethod: 'oauth2', - name, - createdBy: args.userId, - actor: { userId: args.userId }, - secret, - }); - if (tokens.teamId !== undefined) { - const claim = await claimTeamRoute(tx, { - teamId: tokens.teamId, + try { + return await sql.begin(async (tx): Promise => { + await lockCredentialPair(tx, args.organizationId, args.connectorSlug); + const lockGrant = (credentialId: string) => + findOauth2Grant(tx, { + organizationId: args.organizationId, + connectorSlug: args.connectorSlug, + credentialId, + forUpdate: true, + }); + // Row-lock what a renewal may write BEFORE reading the siblings: a + // delete that committed first is missing from every read below, and + // one that comes later waits for this transaction. + const target = + args.intent.kind === 'reconnect' + ? await lockGrant(args.intent.credentialId) + : null; + let route = + team === undefined ? null : await resolveTeamRoute(tx, team.id); + if ( + args.intent.kind === 'add' && + route !== null && + route.organizationId === args.organizationId && + (await lockGrant(route.credentialId)) === null + ) { + // Its credential went with it (the route cascades) — a new one + // takes the workspace over. + route = null; + } + const targetTeams = + target === null || team === undefined + ? [] + : await teamsRoutedTo(tx, args.organizationId, target.id); + const siblings = await listCredentials( + tx, + args.organizationId, + args.connectorSlug, + ); + + const plan = planOauth2Grant({ organizationId: args.organizationId, - credentialId: created.credentialId, + intent: args.intent, + displayName: args.displayName, + nameMax: CREDENTIAL_NAME_MAX, + siblings, + target, + ...(team !== undefined ? { team } : {}), + route, + targetTeams, }); - if (!claim.ok) throw new WorkspaceClaimedError(); + if (plan.kind === 'refuse') { + console.warn( + `[connectors:oauth2] "${args.connectorSlug}" consent refused for organization ${args.organizationId}: ${plan.reason} (${args.intent.kind})`, + ); + return { ok: false, reason: plan.reason }; + } + + let credentialId: string; + if (plan.kind === 'renew') { + credentialId = plan.credentialId; + await updateCredentialInTransaction(tx, { + organizationId: args.organizationId, + credentialId, + secret, + ...(plan.reactivate + ? { status: 'active' as const, statusDetail: null } + : {}), + actor: { userId: args.userId }, + }); + } else { + credentialId = ( + await createCredentialInTransaction(tx, { + organizationId: args.organizationId, + connectorSlug: args.connectorSlug, + authMethod: 'oauth2', + name: plan.name, + createdBy: args.userId, + actor: { userId: args.userId }, + secret, + }) + ).credentialId; + } + if (plan.claimTeamId !== undefined) { + const claim = await claimTeamRoute(tx, { + teamId: plan.claimTeamId, + organizationId: args.organizationId, + credentialId, + }); + if (!claim.ok) throw new WorkspaceClaimedError(); + } + console.info( + `[connectors:oauth2] "${args.connectorSlug}" grant ${plan.kind === 'renew' ? 'renewed' : 'stored as a new credential'} for organization ${args.organizationId} (${args.intent.kind})`, + ); + return { ok: true, credentialId, renewed: plan.kind === 'renew' }; + }); + } catch (error) { + // A lost claim rolls the whole write back: a committed credential for a + // workspace routed elsewhere would be a live foreign token stored here. + if (error instanceof WorkspaceClaimedError) { + return { ok: false, reason: 'workspace_claimed' }; } - }); - return { credentialId: created.credentialId, renewed: false }; + throw error; + } } export type StartOutcome = @@ -339,12 +442,20 @@ export type ConnectorFlowError = | 'vendor_unreachable' | 'invalid_state' | 'workspace_claimed' - | 'storage_failed'; + | 'storage_failed' + | 'credential_missing' + | 'account_mismatch' + | 'forbidden'; /** * Mint the pending authorization and build the vendor consent URL. The caller * has already established WHO is asking and that they may add credentials to - * this organization — this half owns only the OAuth mechanics. + * this organization — this half owns the OAuth mechanics and the intent. + * + * No `reconnectCredentialId` is an Add: the consent stores a new credential. + * With one, it must name an OAuth grant of THIS organization and connector — + * checked here, before anything is minted or the browser leaves, and again + * when the consent comes back. The id then rides the server-side row only. */ export async function startOauth2( sql: Sql, @@ -352,6 +463,8 @@ export async function startOauth2( connectorSlug: string; organizationId: string; userId: string; + /** The credential a Reconnect renews; absent for an Add. */ + reconnectCredentialId?: string; /** The configured site origin the browser is on — the callback must land * on the domain holding the session that started the flow. */ publicOrigin?: string | null; @@ -372,6 +485,21 @@ export async function startOauth2( const endpoints = readOauth2Endpoints(args.connectorSlug); if (!endpoints) return { kind: 'error', error: 'unsupported_connector' }; + const reconnectCredentialId = args.reconnectCredentialId ?? null; + if ( + reconnectCredentialId !== null && + (await findOauth2Grant(sql, { + organizationId: args.organizationId, + connectorSlug: args.connectorSlug, + credentialId: reconnectCredentialId, + })) === null + ) { + console.warn( + `[connectors:oauth2] refused to reconnect a credential that is not an OAuth grant of "${args.connectorSlug}" in organization ${args.organizationId}`, + ); + return { kind: 'error', error: 'credential_missing' }; + } + const app = await resolveConnectorOauthApp( sql, args.organizationId, @@ -394,6 +522,7 @@ export async function startOauth2( connectorSlug: args.connectorSlug, codeVerifier: pkce.verifier, redirectUri, + reconnectCredentialId, }); try { @@ -439,14 +568,18 @@ export type CallbackOutcome = /** * The vendor's front-channel return. Everything trusted comes from the - * consumed state row; the request supplies only the authorization code, which - * is worthless without the PKCE verifier held server-side. + * consumed state row — the organization, the connector and the INTENT (Add, + * or Reconnect of one named credential); the request supplies only the + * authorization code, which is worthless without the PKCE verifier held + * server-side, so no query parameter can re-target the write. * * The state binds the INITIATOR; `requesterUserId` is who is completing — * the session on the browser the vendor redirected back to. The two must be * the same person: a consent link forwarded to someone else would otherwise * store THEIR vendor grant under the initiator's organization. The state is * consumed before the comparison, so a mismatched completion still burns it. + * That person must STILL be allowed to write credentials there, and a + * Reconnect's credential must still exist, before the code is redeemed. */ export async function completeOauth2( sql: Sql, @@ -485,6 +618,7 @@ export async function completeOauth2( } const { organizationId, userId, connectorSlug, codeVerifier, redirectUri } = pending; + const intent = intentOf(pending.reconnectCredentialId); if (args.requesterUserId === null || args.requesterUserId !== userId) { // Same page as a forged state: the completer learns nothing about whose @@ -497,6 +631,16 @@ export async function completeOauth2( return { kind: 'error', error: 'invalid_state' }; } + // The start door's gate, asked again: the member may have left, or lost + // the role that writes credentials, while the vendor asked for consent. + const access = await connectorWriteAccess(sql, organizationId, userId); + if (access !== 'allowed') { + console.warn( + `[connectors:oauth2] refused a "${connectorSlug}" callback: the initiator may no longer write credentials in organization ${organizationId} (${access})`, + ); + return { kind: 'error', error: 'forbidden' }; + } + // A user who declines consent comes back with `error`, not `code`. if (args.vendorError !== null || args.code === null || args.code === '') { console.info( @@ -509,6 +653,21 @@ export async function completeOauth2( if (!endpoints) { return { kind: 'error', error: 'unsupported_connector', organizationId }; } + // Checked before the exchange too, so a Reconnect whose credential was + // deleted meanwhile never redeems its code. The store re-reads it locked. + if ( + intent.kind === 'reconnect' && + (await findOauth2Grant(sql, { + organizationId, + connectorSlug, + credentialId: intent.credentialId, + })) === null + ) { + console.warn( + `[connectors:oauth2] "${connectorSlug}" reconnect target is gone in organization ${organizationId}; nothing exchanged`, + ); + return { kind: 'error', error: 'credential_missing', organizationId }; + } const app = await resolveConnectorOauthApp( sql, organizationId, @@ -561,22 +720,21 @@ export async function completeOauth2( } } + let stored: StoreGrantOutcome; try { - // A renewal for a workspace (or connector) already connected here, or a - // new credential under a label no sibling holds — never a collision on - // the connector's display name. A NEW credential and its workspace claim + // An Add is a new credential under a label no sibling holds; a Reconnect + // renews exactly the credential it named; a Slack workspace already + // connected here renews its own. The write and any workspace claim // commit together inside storeOauth2Grant, or not at all. - await storeOauth2Grant(sql, { + stored = await storeOauth2Grant(sql, { organizationId, connectorSlug, userId, displayName: endpoints.displayName, + intent, tokens, }); } catch (error) { - if (error instanceof WorkspaceClaimedError) { - return { kind: 'error', error: 'workspace_claimed', organizationId }; - } // The message may embed the arguments, which include the access token — // log the SHAPE of the failure, never the error itself. console.error( @@ -586,6 +744,9 @@ export async function completeOauth2( ); return { kind: 'error', error: 'storage_failed', organizationId }; } + if (!stored.ok) { + return { kind: 'error', error: stored.reason, organizationId }; + } // Back to the domain the flow STARTED on — recovered from the redirect URI // the state row carries, so a multi-domain deployment returns the browser diff --git a/services/platform/backend/integration-check.ts b/services/platform/backend/integration-check.ts index d5ec6edd5e..f0f75941ad 100644 --- a/services/platform/backend/integration-check.ts +++ b/services/platform/backend/integration-check.ts @@ -68,6 +68,7 @@ import { checkTriggerStreakLockOrder } from './domains/automations/trigger-lock- import { checkTriggerPauseAfterFailures } from './domains/automations/trigger-pause.integration.ts'; import { appendMessageRow } from './domains/chat/store.ts'; import { checkTaskRunConnectorCaller } from './domains/connectors/bridge-caller.integration.ts'; +import { checkConnectorOauthIntent } from './domains/connectors/oauth-intent.integration.ts'; import { setMailTransportForTesting } from './domains/connectors/service.ts'; import { checkConversationApi } from './domains/conversations/api-sync.integration.ts'; import { checkErasureReviewHandoverRaces } from './domains/erasure/review-handover.integration.ts'; @@ -23548,6 +23549,8 @@ async function checkConnectorOauth( connectorSlug: 'slack', codeVerifier: 'itest-verifier-value-000000000000000000000', redirectUri: `${base}/api/connectors/oauth2/callback`, + // An Add: these probes exercise the workspace route, not a Reconnect. + reconnectCredentialId: null, }); // Point the catalog at a fixture whose slack `tokenUrl` is the fake // vendor — `TALE_CONFIG_SYSTEM_DIR` is the catalog's own root override, @@ -23686,6 +23689,7 @@ async function checkConnectorOauth( connectorSlug: 'slack', codeVerifier: 'itest-verifier-value-222222222222222222222', redirectUri: `${base}/api/connectors/oauth2/callback`, + reconnectCredentialId: null, }); const reconnected = await oauth.completeOauth2( sql, @@ -23733,6 +23737,7 @@ async function checkConnectorOauth( connectorSlug: 'slack', codeVerifier: 'itest-verifier-value-333333333333333333333', redirectUri: `${base}/api/connectors/oauth2/callback`, + reconnectCredentialId: null, }); const secondConnected = await oauth.completeOauth2( sql, @@ -23773,8 +23778,18 @@ async function checkConnectorOauth( // holds this org's Slack credential (one credential per connector name), // so only a fresh organization walks the store-then-claim path — and the // credential it must not keep would have been its FIRST, i.e. its default. + // The initiator is a developer there: the callback re-checks the + // membership and role the start door checked. vendorTeam = { id: 'T-ITEST-RACE' }; const raceOrgId = 'itest-race-org'; + await sql` + INSERT INTO "organization" ("id", "name", "slug", "createdAt") + VALUES (${raceOrgId}, 'Itest race org', ${raceOrgId}, now()) + `; + await sql` + INSERT INTO "member" ("id", "organizationId", "userId", "role", "createdAt") + VALUES (gen_random_uuid(), ${raceOrgId}, ${userId}, 'developer', now()) + `; const raceState = 'itest-oauth-state-race'; await oauth.createPendingAuthorization(sql, { stateHash: await hashStateToken(raceState), @@ -23783,6 +23798,7 @@ async function checkConnectorOauth( connectorSlug: 'slack', codeVerifier: 'itest-verifier-value-222222222222222222222', redirectUri: `${base}/api/connectors/oauth2/callback`, + reconnectCredentialId: null, }); const credentialService = await import('./domains/connector_credentials/service.ts'); @@ -23856,6 +23872,9 @@ async function checkConnectorOauth( raceRoute[0]?.orgId === 'some-other-org', `outcome=${raced.kind}/${raced.kind === 'error' ? raced.error : '-'} (want workspace_claimed), queuedBehindHolder=${queuedBehindHolder}, loserCredentials=${raceCredentials[0]?.count} (want 0) default=${raceCredentials[0]?.isDefault}, routeOwner=${raceRoute[0]?.orgId}`, ); + // The suite user belongs to the suite organization alone again. + await sql`DELETE FROM "member" WHERE "organizationId" = ${raceOrgId}`; + await sql`DELETE FROM "organization" WHERE "id" = ${raceOrgId}`; // ---- an expired grant is refreshed on resolve -------------------------- // The happy-path credential's token is made stale in place (the same @@ -23996,6 +24015,7 @@ async function checkConnectorOauth( connectorSlug: 'slack', codeVerifier: 'itest-verifier-value-111111111111111111111', redirectUri: `${base}/api/connectors/oauth2/callback`, + reconnectCredentialId: null, }); const refused = await oauth.completeOauth2( sql, @@ -55540,6 +55560,10 @@ async function main(): Promise { () => checkConnectorCredentials(sql, baseUrl, authCtx), ], ['checkConnectorOauth', () => checkConnectorOauth(sql, baseUrl, authCtx)], + [ + 'checkConnectorOauthIntent', + () => checkConnectorOauthIntent(sql, baseUrl, record), + ], ['checkSlackInbound', () => checkSlackInbound(sql, baseUrl, authCtx)], ['checkRecoverySweeps', () => checkRecoverySweeps(sql, authCtx)], ['checkRagStatusHintScope', () => checkRagStatusHintScope(sql, record)], diff --git a/services/platform/lib/shared/connector-consent.ts b/services/platform/lib/shared/connector-consent.ts new file mode 100644 index 0000000000..c2891dda0b --- /dev/null +++ b/services/platform/lib/shared/connector-consent.ts @@ -0,0 +1,22 @@ +/** + * What a connector OAuth consent is FOR, from the click that starts it to the + * callback that stores it: + * + * `add` Add credential > > Connect: store a NEW + * credential, whatever the organization already holds. + * `reconnect` a credential row's Reconnect: renew exactly `credentialId`, + * keeping its name, default flag and references. + * + * The start door reads the intent from one query parameter — absent is an + * Add, so a link that predates the parameter can never overwrite a + * credential — and the pending authorization carries it server-side; the + * callback request never names it. The page that writes the parameter and the + * door that reads it share this module, so the two cannot drift apart into a + * Reconnect that silently lands as an Add. Layer A — no imports. + */ +export type ConsentIntent = + | { kind: 'add' } + | { kind: 'reconnect'; credentialId: string }; + +/** The start door's query parameter naming the credential a Reconnect renews. */ +export const RECONNECT_CREDENTIAL_PARAM = 'credentialId'; From 9150c3cc9f1ae640a4cadf0292ca9fc42248e4aa Mon Sep 17 00:00:00 2001 From: yannickmonney <102406702+yannickmonney@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:58:55 +0000 Subject: [PATCH 2/7] fix(platform): name the credential a row's Reconnect renews Connect and Reconnect sent the browser to the same start URL, so nothing told the callback which credential a consent was for (#3711). goToAuthorization now takes an explicit intent: Add credential > Connect starts an Add that names no credential, and a row's Reconnect names that row's id. The parameter name is shared with the start door (lib/shared/connector-consent.ts), so the page and the door cannot drift into a Reconnect that silently lands as an Add. --- .../components/connectors-settings.test.tsx | 40 +++++++++++++++++- .../connectors/connector-oauth.test.ts | 42 +++++++++++++++++++ .../settings/connectors/connector-oauth.ts | 25 ++++++++--- .../connectors/credential-adapter.tsx | 13 ++++-- 4 files changed, 109 insertions(+), 11 deletions(-) create mode 100644 services/platform/app/features/settings/connectors/connector-oauth.test.ts diff --git a/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx b/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx index 80e166ee55..1ca6722fc1 100644 --- a/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx +++ b/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx @@ -433,7 +433,11 @@ describe('ConnectorsSettings', () => { dialog.queryByRole('textbox', { name: /^Name/ }), ).not.toBeInTheDocument(); await user.click(dialog.getByRole('button', { name: 'Connect' })); - expect(goToAuthorization).toHaveBeenCalledWith('org-1', 'slack'); + // An explicit Add: the callback stores a NEW credential, never the + // default in its place (#3711). + expect(goToAuthorization).toHaveBeenCalledWith('org-1', 'slack', { + kind: 'add', + }); expect(createCredential).not.toHaveBeenCalled(); }); @@ -650,6 +654,40 @@ describe('ConnectorsSettings', () => { ).not.toBeInTheDocument(); }); + it('reconnects exactly the row whose menu was used, not the default', async () => { + fixtures.connectors = [slackConnector]; + fixtures.credentials = [ + credential({ + id: 'cred-default', + name: 'Workspace grant', + connectorSlug: 'slack', + authMethod: 'oauth2', + isDefault: true, + }), + credential({ + id: 'cred-sales', + name: 'Sales workspace', + connectorSlug: 'slack', + authMethod: 'oauth2', + status: 'needs-reauth', + }), + ]; + const { user } = render(); + await user.click( + screen.getByRole('button', { name: 'Actions for Sales workspace' }), + ); + await user.click( + within(await screen.findByRole('menu')).getByRole('menuitem', { + name: 'Reconnect', + }), + ); + expect(goToAuthorization).toHaveBeenCalledTimes(1); + expect(goToAuthorization).toHaveBeenCalledWith('org-1', 'slack', { + kind: 'reconnect', + credentialId: 'cred-sales', + }); + }); + it('deletes only after an explicit confirm', async () => { const { user } = render(); await user.click( diff --git a/services/platform/app/features/settings/connectors/connector-oauth.test.ts b/services/platform/app/features/settings/connectors/connector-oauth.test.ts new file mode 100644 index 0000000000..ad3ae0adc7 --- /dev/null +++ b/services/platform/app/features/settings/connectors/connector-oauth.test.ts @@ -0,0 +1,42 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { authorizationUrl } from './connector-oauth'; + +/** + * The start URL says what a consent is FOR (#3711): an Add names no + * credential, so the callback stores a new one; a Reconnect names the + * credential it renews, and the server writes to exactly that one. + */ +describe('authorizationUrl', () => { + beforeEach(() => { + window.__ENV__ = { SITE_URL: 'https://tale.example', BASE_PATH: '/tale' }; + }); + afterEach(() => { + delete window.__ENV__; + }); + + it('starts an Add without naming any credential', () => { + const url = new URL(authorizationUrl('org-1', 'gmail', { kind: 'add' })); + expect(`${url.origin}${url.pathname}`).toBe( + 'https://tale.example/tale/api/connectors/oauth2/start', + ); + expect(Object.fromEntries(url.searchParams)).toEqual({ + connector: 'gmail', + organizationId: 'org-1', + }); + }); + + it('starts a Reconnect naming the credential it renews', () => { + const url = new URL( + authorizationUrl('org-1', 'gmail', { + kind: 'reconnect', + credentialId: 'cred-sales', + }), + ); + expect(Object.fromEntries(url.searchParams)).toEqual({ + connector: 'gmail', + organizationId: 'org-1', + credentialId: 'cred-sales', + }); + }); +}); diff --git a/services/platform/app/features/settings/connectors/connector-oauth.ts b/services/platform/app/features/settings/connectors/connector-oauth.ts index b9cedefba4..fbf60ff830 100644 --- a/services/platform/app/features/settings/connectors/connector-oauth.ts +++ b/services/platform/app/features/settings/connectors/connector-oauth.ts @@ -1,4 +1,8 @@ import { getEnv } from '@/lib/env'; +import { + RECONNECT_CREDENTIAL_PARAM, + type ConsentIntent, +} from '@/lib/shared/connector-consent'; /** * The consent hand-off for connectors that authenticate through OAuth. @@ -7,24 +11,30 @@ import { getEnv } from '@/lib/env'; * route re-checks that the signed-in member may add credentials, mints the * state token and PKCE pair, and redirects to the vendor; the callback * exchanges the code and stores the credential. So there is nothing to submit - * from here and nothing to name — the page just hands the browser over, which - * is also why re-consenting an existing credential uses the very same URL as a - * first connection. + * from here and nothing to name — the page just hands the browser over, and + * says what the consent is FOR. An Add stores a new credential; a Reconnect + * names the credential it renews, which the server checks, keeps on the + * pending authorization, and writes to exactly — never to the connector's + * default instead. * * A full-page navigation rather than a popup: the state lives server-side, * there is no opener to talk to, and nothing for a blocked popup to swallow. */ -/** The deployment's OAuth start URL for one connector. */ -function authorizationUrl( +/** The deployment's OAuth start URL for one connector and intent. */ +export function authorizationUrl( organizationId: string, connectorSlug: string, + intent: ConsentIntent, ): string { const siteUrl = getEnv('SITE_URL'); const basePath = getEnv('BASE_PATH'); const url = new URL(`${siteUrl}${basePath}/api/connectors/oauth2/start`); url.searchParams.set('connector', connectorSlug); url.searchParams.set('organizationId', organizationId); + if (intent.kind === 'reconnect') { + url.searchParams.set(RECONNECT_CREDENTIAL_PARAM, intent.credentialId); + } return url.toString(); } @@ -32,6 +42,9 @@ function authorizationUrl( export function goToAuthorization( organizationId: string, connectorSlug: string, + intent: ConsentIntent, ): void { - globalThis.location.assign(authorizationUrl(organizationId, connectorSlug)); + globalThis.location.assign( + authorizationUrl(organizationId, connectorSlug, intent), + ); } diff --git a/services/platform/app/features/settings/connectors/credential-adapter.tsx b/services/platform/app/features/settings/connectors/credential-adapter.tsx index de6c04333c..c25770e31b 100644 --- a/services/platform/app/features/settings/connectors/credential-adapter.tsx +++ b/services/platform/app/features/settings/connectors/credential-adapter.tsx @@ -262,7 +262,9 @@ function ConnectorConsent({ @@ -326,10 +328,13 @@ export const connectorCredentialAdapter: CredentialAdapter< key: 'reconnect', label: t('connectors.credential.reconnect'), icon: RefreshCw, - // Re-consent is the same hand-off as a first connection; the callback - // refreshes the grant this credential already holds. + // Re-consent names THIS credential: the callback renews exactly it — + // name, default and references kept — or saves nothing. onClick: () => - goToAuthorization(organizationId, credential.connectorSlug), + goToAuthorization(organizationId, credential.connectorSlug, { + kind: 'reconnect', + credentialId: credential.id, + }), visible: credential.authMethod === 'oauth2', disabled: busy, }, From 76c2c3d76fd6ecce472c44840509a912d826484d Mon Sep 17 00:00:00 2001 From: yannickmonney <102406702+yannickmonney@users.noreply.github.com> Date: Mon, 28 Sep 2026 15:10:31 +0000 Subject: [PATCH 3/7] docs(platform): say which credential an OAuth Add or Reconnect writes The connector guides promised that Add credential connects another account and that Reconnect keeps the credential's name and references, while the product renewed the default grant for both (#3711). EN, DE and FR now say what each does: every Connect adds a new credential (named after the connector and numbered, renamed through Edit credential), Slack keeps one credential per workspace, Reconnect renews exactly the row it was chosen on and leaves a disabled credential disabled, and a removed credential, a lost role or another Slack workspace saves nothing. The connectors manual suite asserts the rows by their masked previews, explains how to run the consent boxes against a loopback fake vendor, and gains CONN-F19/F20 and CONN-B7-B10; the automation, pins and error-code registers name the new coverage and pages. --- docs/de/platform/admin/connectors.md | 10 ++- docs/de/platform/connectors/overview.md | 2 +- docs/en/platform/admin/connectors.md | 10 ++- docs/en/platform/connectors/overview.md | 2 +- docs/fr/platform/admin/connectors.md | 10 ++- docs/fr/platform/connectors/overview.md | 2 +- services/platform/tests/manual/readme.md | 4 +- .../tests/manual/reference/automation.md | 4 +- .../tests/manual/reference/error-codes.md | 3 + .../platform/tests/manual/reference/pins.md | 1 + .../tests/manual/suites/connectors.md | 72 ++++++++++++++++--- 11 files changed, 94 insertions(+), 26 deletions(-) diff --git a/docs/de/platform/admin/connectors.md b/docs/de/platform/admin/connectors.md index 121c01c948..5eb598c9e6 100644 --- a/docs/de/platform/admin/connectors.md +++ b/docs/de/platform/admin/connectors.md @@ -8,10 +8,12 @@ Hinterlege Connector-Zugangsdaten, damit Tale Dienste wie Postfächer, Dateiabla ## Ein Konto verbinden 1. Wähle **Zugangsdaten hinzufügen** und den Connector. Bereits konfigurierte Connectors stehen zuerst und können weitere Zugangsdaten erhalten. -2. Prüfe das Feld **Name**. Es enthält bereits den Namen des Connectors. Heißen andere Zugangsdaten dieses Connectors schon so, hängt Tale eine Zahl an: `GitHub`, dann `GitHub 2`. Ein Name wie `Support-Postfach` oder `EU-Shop` ist beim Erstellen von Automatisierungen leichter zu erkennen. OAuth-Verbindungen verwenden dieses Feld nicht. -3. Fülle die angebotene Authentifizierungsmethode aus. Bei OAuth wählst du **Verbinden** und erteilst den Zugriff beim Anbieter. +2. Prüfe das Feld **Name**. Es enthält bereits den Namen des Connectors. Heißen andere Zugangsdaten dieses Connectors schon so, hängt Tale eine Zahl an: `GitHub`, dann `GitHub 2`. Ein Name wie `Support-Postfach` oder `EU-Shop` ist beim Erstellen von Automatisierungen leichter zu erkennen. Eine OAuth-Verbindung hat kein Namensfeld. Tale benennt sie nach derselben Regel, sobald du den Zugriff erteilt hast (ein zweiter Slack-Workspace erhält den Namen des Workspace), und mit **Zugangsdaten bearbeiten** kannst du sie umbenennen. +3. Fülle die angebotene Authentifizierungsmethode aus. Bei OAuth wählst du **Verbinden** und erteilst den Zugriff beim Anbieter. Jedes **Verbinden** legt neue Zugangsdaten für das freigegebene Konto an und ersetzt nie bestehende. Melde dich beim Anbieter deshalb mit dem Konto an, das du hinzufügen willst. 4. Schließe das Formular ab und prüfe den neuen Eintrag mit Connector, Konto oder Instanz und Status. +Slack verbindet pro Workspace genau einen Satz Zugangsdaten. Gibst du einen bereits verbundenen Workspace erneut frei, erneuert Tale dessen Zugangsdaten, statt weitere anzulegen. + Der Connector bestimmt die Felder. Verwende die tatsächlichen Zugangsdaten des Dienstkontos, keinen Tale-API-Schlüssel. | Methode | Benötigte Angaben | @@ -55,7 +57,9 @@ Bei OneDrive/SharePoint kann **Entra-ID-App aus SSO übernehmen** eine bestehend ## Eine Verbindung reparieren -**Neu verbinden nötig** bedeutet, dass die gespeicherte OAuth-Berechtigung nicht mehr erneuert werden kann. Wähle **Neu verbinden** und gib das Konto erneut frei. Name und Verweise bleiben erhalten. Bewusst deaktivierte Zugangsdaten brauchen stattdessen **Aktivieren**. +**Neu verbinden nötig** bedeutet, dass die gespeicherte OAuth-Berechtigung nicht mehr erneuert werden kann. Wähle im Menü dieser Zeile **Neu verbinden** und gib dasselbe Konto erneut frei. Tale erneuert genau diese Zugangsdaten: Name, Standard und Verweise bleiben erhalten, alle anderen Zugangsdaten bleiben unverändert. Bewusst deaktivierte Zugangsdaten aktiviert **Neu verbinden** nicht wieder; dafür gibt es **Aktivieren**. + +Werden die Zugangsdaten entfernt, bevor die Freigabe abgeschlossen ist, oder erlaubt dir deine Rolle das Verwalten von Zugangsdaten nicht mehr, speichert Tale nichts und nennt den Grund. Gib bei Slack den Workspace frei, den die Zugangsdaten bereits verbinden. Einen anderen Workspace lehnt Tale ab; verbinde ihn stattdessen über **Zugangsdaten hinzufügen**. Kann die Verbindung nicht starten, prüfe die OAuth-App. Lehnt der Anbieter die Rückkehr zu Tale ab, vergleiche die registrierte Weiterleitungsadresse mit der exakt in Tale gezeigten Adresse. Scheitert nach der Verbindung eine Aktion, prüfe die Kontorechte und den benötigten Berechtigungsumfang. diff --git a/docs/de/platform/connectors/overview.md b/docs/de/platform/connectors/overview.md index add4ddc16f..4c38cac39c 100644 --- a/docs/de/platform/connectors/overview.md +++ b/docs/de/platform/connectors/overview.md @@ -41,7 +41,7 @@ Wähle **Zugangsdaten hinzufügen**, suche den Dienst und öffne seine Karte. Be -Das Feld **Name** enthält zunächst den Namen des Connectors. Fügst du für denselben Dienst mehrere Konten hinzu, ersetze ihn durch einen zweckbezogenen Namen, etwa `Support-Postfach` oder `Release-Bot`. Verwende Zugangsdaten des externen Diensts, keinen Tale-API-Schlüssel. Schließe bei OAuth die Zustimmung beim Provider ab und prüfe das zurückgemeldete Konto. Kann der Vorgang nicht starten, muss gegebenenfalls ein Administrator zuerst die OAuth-App einrichten. +Das Feld **Name** enthält zunächst den Namen des Connectors. Fügst du für denselben Dienst mehrere Konten hinzu, ersetze ihn durch einen zweckbezogenen Namen, etwa `Support-Postfach` oder `Release-Bot`. Verwende Zugangsdaten des externen Diensts, keinen Tale-API-Schlüssel. Melde dich bei OAuth mit dem Konto beim Provider an, das du hinzufügen willst, und schließe die Zustimmung ab. Jede Verbindung legt neue Zugangsdaten an, benannt nach dem Connector und durchnummeriert (`Gmail`, dann `Gmail 2`); Slack führt pro Workspace genau einen Satz. Benenne neue Zugangsdaten um, damit die Konten unterscheidbar bleiben. Kann der Vorgang nicht starten, muss gegebenenfalls ein Administrator zuerst die OAuth-App einrichten. Confluence und Shopify brauchen pro Eintrag eine **Instanz-URL**. Verwende den Ursprung der Atlassian-Site oder die `myshopify.com`-Adresse des Shops, keine beliebige Unterseite oder Kundendomain. [Connector-Zugangsdaten](/de/platform/admin/connectors) erklärt Felder, erneute Autorisierung und Schlüsselaustausch. diff --git a/docs/en/platform/admin/connectors.md b/docs/en/platform/admin/connectors.md index 88128dea7f..5624a1c729 100644 --- a/docs/en/platform/admin/connectors.md +++ b/docs/en/platform/admin/connectors.md @@ -8,10 +8,12 @@ Add connector credentials so Tale can use services such as a mailbox, file store ## Add an account 1. Select **Add credential**, then the connector. Already configured connectors appear first and can hold additional credentials. -2. Check the **Name**. It starts as the connector's name, with a number added when another credential for that connector already uses it: `GitHub`, then `GitHub 2`. A name such as `Support inbox` or `EU store` is easier for an automation author to recognize. OAuth connections do not use this field. -3. Complete the authentication method offered by that connector. For OAuth, select **Connect** and complete the vendor's consent flow. +2. Check the **Name**. It starts as the connector's name, with a number added when another credential for that connector already uses it: `GitHub`, then `GitHub 2`. A name such as `Support inbox` or `EU store` is easier for an automation author to recognize. An OAuth connection has no name field: Tale names it the same way when consent completes (a second Slack workspace takes the workspace's name), and **Edit credential** renames it. +3. Complete the authentication method offered by that connector. For OAuth, select **Connect** and complete the vendor's consent flow. Each **Connect** adds a new credential for the account you authorize and never replaces an existing one, so sign in to the vendor as the account you want to add. 4. Complete the form and check the resulting row, including its connector, account or instance, and status. +Slack connects one credential per workspace. Authorizing a workspace that is already connected renews that workspace's credential instead of adding a second one. + The connector determines which fields appear. Use the account's actual credentials, not a Tale API key. | Method | Required information | @@ -55,7 +57,9 @@ For OneDrive/SharePoint, **Use Entra ID SSO app** can copy an existing SSO regis ## Reconnect or diagnose a failure -**Reconnect needed** means stored OAuth authorization can no longer refresh. Choose **Reconnect** and authorize the account again. This keeps the credential's name and references. A deliberately disabled credential instead needs **Enable**. +**Reconnect needed** means stored OAuth authorization can no longer refresh. Choose **Reconnect** in that row's menu and authorize the same account again. Tale renews exactly that credential: its name, default choice and references stay, and no other credential changes. Reconnect does not re-enable a deliberately disabled credential; **Enable** returns it to service. + +If the credential is removed before consent completes, or your role no longer allows you to manage credentials, Tale saves nothing and shows the reason. For Slack, authorize the workspace the credential already connects. Tale refuses a different workspace; connect that one with **Add credential**. If the connection cannot start, check whether the OAuth app is configured. If the vendor rejects the return to Tale, compare the registered redirect URI with the exact URI shown by Tale. If an action fails after connecting, check the account's permissions and the required scope for that action. diff --git a/docs/en/platform/connectors/overview.md b/docs/en/platform/connectors/overview.md index d6eabb6018..18ece05f68 100644 --- a/docs/en/platform/connectors/overview.md +++ b/docs/en/platform/connectors/overview.md @@ -41,7 +41,7 @@ Select **Add credential**, search for the service and choose its card. Connector -The **Name** field starts with the connector’s name. When you add several accounts for the same service, change it to one that identifies the purpose, such as `Support inbox` or `Release bot`. Use the external service’s credentials, not a Tale API key. For OAuth, complete the provider consent flow and check the returned account. If consent cannot start, an administrator may need to configure its OAuth app first. +The **Name** field starts with the connector’s name. When you add several accounts for the same service, change it to one that identifies the purpose, such as `Support inbox` or `Release bot`. Use the external service’s credentials, not a Tale API key. For OAuth, sign in to the provider as the account you want to add and complete its consent. Each connection adds a new credential named after the connector and numbered (`Gmail`, then `Gmail 2`); Slack keeps one per workspace. Rename a new credential so the accounts stay distinguishable. If consent cannot start, an administrator may need to configure its OAuth app first. Confluence and Shopify require an **Instance URL** per credential. Use the Atlassian site origin or the store’s `myshopify.com` origin, rather than an unrelated page or customer-facing domain. [Connector credentials](/platform/admin/connectors) covers setup fields, reconnection and rotation. diff --git a/docs/fr/platform/admin/connectors.md b/docs/fr/platform/admin/connectors.md index 5ea1d3e99c..965517b9c4 100644 --- a/docs/fr/platform/admin/connectors.md +++ b/docs/fr/platform/admin/connectors.md @@ -8,10 +8,12 @@ Ajoute des identifiants de connecteur pour que Tale utilise une messagerie, un e ## Connecter un compte 1. Sélectionne **Ajouter des identifiants**, puis le connecteur. Les connecteurs déjà configurés apparaissent en premier et peuvent recevoir d’autres identifiants. -2. Vérifie le champ **Nom**. Il est prérempli avec le nom du connecteur, suivi d’un numéro si d’autres identifiants de ce connecteur portent déjà ce nom : `GitHub`, puis `GitHub 2`. Un nom comme `Boîte support` ou `Boutique UE` est plus facile à reconnaître pour la personne qui prépare l’automatisation. Les connexions OAuth n’utilisent pas ce champ. -3. Complète la méthode d’authentification proposée. Pour OAuth, sélectionne **Connecter** et autorise l’accès chez le fournisseur. +2. Vérifie le champ **Nom**. Il est prérempli avec le nom du connecteur, suivi d’un numéro si d’autres identifiants de ce connecteur portent déjà ce nom : `GitHub`, puis `GitHub 2`. Un nom comme `Boîte support` ou `Boutique UE` est plus facile à reconnaître pour la personne qui prépare l’automatisation. Une connexion OAuth n’a pas de champ de nom : Tale la nomme de la même façon une fois l’accès autorisé (un deuxième espace Slack prend le nom de l’espace), et **Modifier les identifiants** permet de la renommer. +3. Complète la méthode d’authentification proposée. Pour OAuth, sélectionne **Connecter** et autorise l’accès chez le fournisseur. Chaque **Connecter** ajoute de nouveaux identifiants pour le compte autorisé, sans jamais remplacer ceux qui existent. Connecte-toi donc chez le fournisseur avec le compte que tu veux ajouter. 4. Termine le formulaire, puis vérifie la ligne créée : connecteur, compte ou instance, et statut. +Slack associe un seul jeu d’identifiants à chaque espace Slack. Si tu autorises à nouveau un espace déjà connecté, Tale renouvelle ses identifiants au lieu d’en ajouter d’autres. + Le connecteur détermine les champs. Utilise les identifiants du compte externe, pas une clé API Tale. | Méthode | Informations nécessaires | @@ -55,7 +57,9 @@ Pour OneDrive/SharePoint, **Utiliser l'app SSO Entra ID** peut copier une inscri ## Rétablir une connexion -**Reconnexion requise** signifie que l’autorisation OAuth enregistrée ne peut plus être renouvelée. Sélectionne **Reconnecter** et autorise à nouveau le compte. Le nom et les références restent les mêmes. Des identifiants volontairement désactivés demandent plutôt **Activer**. +**Reconnexion requise** signifie que l’autorisation OAuth enregistrée ne peut plus être renouvelée. Sélectionne **Reconnecter** dans le menu de cette ligne et autorise à nouveau le même compte. Tale renouvelle exactement ces identifiants : leur nom, le choix par défaut et les références restent les mêmes, et aucun autre identifiant ne change. **Reconnecter** ne réactive pas des identifiants volontairement désactivés ; **Activer** les remet en service. + +Si les identifiants sont supprimés avant la fin de l’autorisation, ou si ton rôle ne te permet plus de gérer les identifiants, Tale n’enregistre rien et en indique la raison. Pour Slack, autorise l’espace que ces identifiants connectent déjà. Tale refuse un autre espace ; connecte-le plutôt avec **Ajouter des identifiants**. Si la connexion ne démarre pas, vérifie l’application OAuth. Si le fournisseur refuse le retour vers Tale, compare son URI de redirection enregistrée à celle que Tale affiche. Si une action échoue après la connexion, vérifie les droits du compte et les permissions requises pour cette action. diff --git a/docs/fr/platform/connectors/overview.md b/docs/fr/platform/connectors/overview.md index 8adbada706..bf8a73441a 100644 --- a/docs/fr/platform/connectors/overview.md +++ b/docs/fr/platform/connectors/overview.md @@ -41,7 +41,7 @@ Choisis **Ajouter des identifiants**, recherche le service et ouvre sa carte. Le -Le champ **Nom** est prérempli avec le nom du connecteur. Si tu ajoutes plusieurs comptes pour le même service, remplace-le par un nom qui indique l’usage, par exemple `Boîte support` ou `Bot de publication`. Utilise ceux du service externe, pas une clé API Tale. Pour OAuth, termine le consentement chez le fournisseur et vérifie le compte retourné. Si le parcours ne démarre pas, un administrateur doit peut-être configurer l’app OAuth d’abord. +Le champ **Nom** est prérempli avec le nom du connecteur. Si tu ajoutes plusieurs comptes pour le même service, remplace-le par un nom qui indique l’usage, par exemple `Boîte support` ou `Bot de publication`. Utilise ceux du service externe, pas une clé API Tale. Pour OAuth, connecte-toi chez le fournisseur avec le compte à ajouter et termine le consentement. Chaque connexion ajoute de nouveaux identifiants, nommés d’après le connecteur puis numérotés (`Gmail`, puis `Gmail 2`) ; Slack en garde un seul jeu par espace. Renomme les nouveaux identifiants pour distinguer les comptes. Si le parcours ne démarre pas, un administrateur doit peut-être configurer l’app OAuth d’abord. Confluence et Shopify demandent une **URL de l'instance** pour chaque compte. Utilise l’origine du site Atlassian ou l’adresse `myshopify.com` de la boutique, pas une page quelconque ni le domaine destiné aux clients. [Identifiants des connectors](/fr/platform/admin/connectors) explique les champs, la reconnexion et le renouvellement des secrets. diff --git a/services/platform/tests/manual/readme.md b/services/platform/tests/manual/readme.md index 46b8b73b79..69577e2243 100644 --- a/services/platform/tests/manual/readme.md +++ b/services/platform/tests/manual/readme.md @@ -29,7 +29,7 @@ tale-project standard ([`AGENTS.md`](../../../../AGENTS.md) "Manual tests"), and ## The suites -881 boxes across 21 suites. Every suite declares the ID prefix its +887 boxes across 21 suites. Every suite declares the ID prefix its boxes carry, in its header blockquote; a box ID is unique across this whole directory and greppable as one token. @@ -40,7 +40,7 @@ directory and greppable as one token. | [auth](suites/auth.md) | `AUTH-` | login, SSO, 2FA, passkeys, password policy, first-run setup, RBAC | 50 | | [automations](suites/automations.md) | `AUTO-` | draft→deploy→version automations: list, builder, upload, trigger, runs, bindings | 72 | | [chat](suites/chat.md) | `CHAT-` | messages, attachments, tools + approvals, arena, share, reasoning, the chat header and rows | 86 | -| [connectors](suites/connectors.md) | `CONN-` | credential table + catalog picker; mailbox (IMAP/SMTP), OAuth, MCP endpoint | 30 | +| [connectors](suites/connectors.md) | `CONN-` | credential table + catalog picker; mailbox (IMAP/SMTP), OAuth, MCP endpoint | 36 | | [conversations](suites/conversations.md) | `CONV-` | the shared Inbox: statuses, priority, search, mailbox sync | 55 | | [data-residency](suites/data-residency.md) | `DATA-` | BYO knowledge database + object storage, embedding settings | 24 | | [governance](suites/governance.md) | `GOV-` | content models, guardrails, policies, legal hold, DSAR, logs, trash | 55 | diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 5949b6028c..046adfbc6c 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -238,7 +238,9 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [connectors](../suites/connectors.md) | `CONN-F7`, `CONN-B1` (required-config gating) | 🔶 component | `app/features/settings/connectors/config-fields.test.tsx` | | [connectors](../suites/connectors.md) | `CONN-F17` | 🔶 component | `app/features/settings/connectors/components/mcp-endpoint-section.test.tsx` | | [connectors](../suites/connectors.md) | `CONN-F11`, `CONN-F12`, `CONN-F18`, `CONN-B2`, `CONN-B3`, `CONN-B6` | ⛔ manual-only | — (persistence reloads, live consent round trip, redirects, server refusals) | -| [connectors](../suites/connectors.md) | `CONN-F15`, `CONN-F16` (full round trip) | ⛔ manual-only | — (need a real vendor consent, mode B) | +| [connectors](../suites/connectors.md) | `CONN-F15`, `CONN-F16` (full round trip) | ⛔ manual-only | — (need a real vendor consent, mode B, or a loopback fake vendor) | +| [connectors](../suites/connectors.md) | `CONN-F15`, `CONN-F16`, `CONN-F19`, `CONN-F20`, `CONN-B7`–`CONN-B10` (the backend half, #3711): a consent lands where its intent says — an Add stores a NEW credential under a name no sibling holds and never renews the default; a Reconnect renews exactly the credential its row named (id, name, default flag, mail-sync cursor and audit actor kept; `needs-reauth` cleared, `disabled` kept) or saves nothing when that credential is gone, even when the delete races the store; the start door keeps a target only when it is this organization's OAuth grant of that connector and the callback never reads one from its request; the initiator's membership and developer role are re-checked at the callback before the code is redeemed; two Adds completing at once number past each other with one default; a pending row minted before migration `0130` completes as an Add; Slack keeps one credential per workspace and refuses a Reconnect into another | ✅ automated | `backend/domains/connectors/oauth-grant-plan.test.ts` (the decision table), `backend/domains/connectors/oauth.test.ts`, `backend/domains/connectors/oauth-routes.test.ts`, `backend/integration-check.ts` (`checkConnectorOauthIntent` in `backend/domains/connectors/oauth-intent.integration.ts`, run by `backend:integration`) | +| [connectors](../suites/connectors.md) | `CONN-F15`, `CONN-F16`, `CONN-F20` (the hand-off): **Connect** starts an Add naming no credential, a row's **Reconnect** names that row — the default's sibling included | 🔶 component | `app/features/settings/connectors/connector-oauth.test.ts`, `app/features/settings/connectors/components/connectors-settings.test.tsx` | | [conversations](../suites/conversations.md) | `CONV-G1`–`CONV-G3`, `CONV-F1`–`CONV-F10`, `CONV-B1`–`CONV-B4`, `CONV-F27`, `CONV-F28`, `CONV-F30` | ⛔ manual-only | — (the `email-automation` spec, which automated the gate, redirect, channel filter, and reading pane, was retired in #2857 and has no successor; `home-panel.test.tsx` only proves the Inbox view is absent without an inbox) | | [conversations](../suites/conversations.md) / [responsive](../suites/responsive.md) | `CONV-F29`, `RESP-F11` (the conversation's half): the header's identity mark is the contact's initials, the subject with a title fallback, the contact's name, the relative time, the email and the source (mailbox · address or the API source) in that order, each separator grouped with its item, the actions menu; the phone's back control shows only over an open conversation or compose and leads to the Home list | 🔶 component | `app/features/conversations/components/conversation-header.test.tsx`, `app/features/conversations/components/inbox-mobile-back-button.test.tsx`; the composer frame stays manual, the header at real widths is `RESP-F16`'s row | | [conversations](../suites/conversations.md) | `CONV-F11` | 🔶 partial | `backend/domains/conversations/api-sync.integration.ts` owns HTTP/Postgres source imports, attachments, replies, undo, replay, isolation and deletion; `use-inbox-availability.test.ts` owns the API-only gate. Visual two-app flow and keyboard behavior remain manual. | diff --git a/services/platform/tests/manual/reference/error-codes.md b/services/platform/tests/manual/reference/error-codes.md index 0cf3af1a88..8170c2e7be 100644 --- a/services/platform/tests/manual/reference/error-codes.md +++ b/services/platform/tests/manual/reference/error-codes.md @@ -32,6 +32,9 @@ provokes it and the recovery the surface offers. | Folder rename in a synced tree refused (`documents.folder.renameSyncManaged`, backend `FOLDER_SYNC_MANAGED` 409) | The row menu offers no **Rename** for a folder at, inside or above a synced folder. To reach the refusal, open **Rename** on a parent folder, start syncing a folder below it from another tab, then submit. The dialog keeps the name and names the rule on the field; nothing is renamed. | | Mention directory unavailable (`common.errors.generic` toast, backend `MENTION_DIRECTORY_UNAVAILABLE` 503) | Post a task comment, create a task, or save a task description whose text carries an `@` token while one leg of the mention directory cannot be read (the members, the deployed automations or the project's agents). No healthy stack reaches it from the UI; `checkCollabMentions` and `checkTaskDescriptionMentions` in `backend:integration` provoke it by failing the agents leg. Nothing is saved and no one is notified; the composer, the **Create task** dialog and the description editor keep the typed text for a retry. An edit that adds no `@` token reads no directory, so it never answers this. | | Reviewer refused (`tasks.reviewer.editorsOnly` toast, backend `TASK_REVIEWER_NO_EDIT_ACCESS` 400 / `TASK_REVIEWER_INVALID` 400) | The **Reviewer** picker lists only members who can edit the project, so the app reaches it only through a stale list: pick someone who lost edit access (a role changed to Member, removed from the project's team) or left the organization after the list loaded. A hand-built `POST /api/app/tasks/{taskId}` with such a `reviewerUserId` answers the code directly (see PROJ-B9). The toast says who can review; the designation, the subscriptions and every bell stay as they were. | +| Connector Reconnect target gone (server page "This credential cannot be reconnected", 404; flow error `credential_missing`) | Start **Reconnect** on an OAuth row and delete that row from a second tab while the vendor's consent screen is open, then consent (CONN-B7); or open the start door with a `credentialId` that is empty, unknown, another organization's or another connector's (CONN-B8). Nothing is saved and no vendor page opens for a start-door refusal; the page links back to connector settings. | +| Slack Reconnect in another workspace (server page "That is a different workspace", 409; flow error `account_mismatch`) | **Reconnect** a Slack row and consent in a workspace other than the one it connects (CONN-B10). Nothing is saved; a Reconnect in the row's own workspace renews it, and **Add credential** connects the other workspace as its own row. | +| Connector access lost mid-consent (server page "You can no longer connect connectors here", 403; flow error `forbidden`) | A Developer starts **Connect** or **Reconnect**; while the vendor's consent screen is open, an Admin changes their role to Member or removes them; then consent (CONN-B9). The code is never redeemed and nothing is saved. | ## Reachable on the API surface only diff --git a/services/platform/tests/manual/reference/pins.md b/services/platform/tests/manual/reference/pins.md index ff0312e071..d727952160 100644 --- a/services/platform/tests/manual/reference/pins.md +++ b/services/platform/tests/manual/reference/pins.md @@ -49,6 +49,7 @@ time you are tempted to shorten one. | `SET-F2` | `settings.menu..description` is built from the entry key at runtime, which the catalog guard cannot enumerate; `skills` had no description in any locale. `use-settings-menu-groups.test.tsx` resolves every entry. | | `SKILL-F4` | The door keeps a stored icon when the field is omitted and clears it on `null`; "No icon" dropped the field, so the rocket survived every save. The editor sends `icon: null` (`skill-detail-pane.test.tsx`, `library.test.ts`). | | `CONN-F15` | The "no OAuth app" explainer assumed every app is registered in the organization's OAuth apps card; Slack's is deployment-only. The catalog answers `orgConfigurable` and the copy names the operator (`oauth-app-missing.test.ts`). | +| `CONN-F19` / `CONN-F20` / `CONN-B7` | Connect and Reconnect shared one start URL, so the callback could not know which credential a consent was for and renewed the connector's default grant for every connector without a workspace id: a second Gmail/Outlook/Drive/Teams account replaced the first, and Reconnect on another row rewrote the default (#3711). The intent now rides the pending state row (`reconnect_credential_id`, migration `0130`); the boxes compare the rows' masked previews because the table shows the same names either way (`oauth-intent.integration.ts`). | | `KNOW-B5` | `AppError.message` is the serialized payload by design; the folder-delete toast printed it. Both surfaces read `data.message` and name a retained record in words (`document-row-actions.test.tsx`, `project-files-tab.test.tsx`). | | `VID-F5` | The extractor skips a playlist URL silently by design (no chip may spawn a job for it); the paste now toasts the existing "playlists aren't supported" copy once (`video-url.test.ts` `findPlaylistUrls`). | | `A11Y-A2` | Under the injected `` a skip link whose target is missing resolved `#main-content` to the site root and landed anonymous readers of `/docs` on sign-in. The shared `SkipLink` sets the hash on the current document and `/docs` and `/2fa-enroll` carry the target (`skip-link.test.tsx`, `docs.test.tsx`). | diff --git a/services/platform/tests/manual/suites/connectors.md b/services/platform/tests/manual/suites/connectors.md index 13192b99ab..15c7ac0339 100644 --- a/services/platform/tests/manual/suites/connectors.md +++ b/services/platform/tests/manual/suites/connectors.md @@ -1,6 +1,6 @@ # Connectors -> **Prefix** `CONN-` · **Reset** none · **Cost** 30 boxes +> **Prefix** `CONN-` · **Reset** none · **Cost** 36 boxes Exercise the **connector credentials** page under Settings — one flat table of every credential the organization holds for a shipped connector (#2889 @@ -61,14 +61,29 @@ Sign in as an owner/admin — the page requires the `developerSettings` ability > (`settings.credentials.createdToast`) plus a new table row. Stored secrets > are never read back: every secret field starts blank, including in Replace > secret. The first credential of an (org, connector) pair becomes its -> **default** automatically. **CONN-F15/CONN-F16 need mode B** plus a +> **default** automatically. **CONN-F15/CONN-F16, CONN-F19/CONN-F20 and +> CONN-B7/CONN-B9/CONN-B10 need a consent round trip**: mode B plus a > registered OAuth app (`CONNECTOR_OAUTH__CLIENT_ID` / `…_CLIENT_SECRET` -> env vars): consent is a real full-page navigation to the vendor. In mode A, -> assert the hand-off (the browser leaves for -> `…/http_api/api/connectors/oauth2/start?connector=…`) rather than a -> completed grant. On success the callback lands back on +> env vars, or the organization's **OAuth apps** card), or a loopback fake +> vendor (below). Consent is a full-page navigation. In mode A without one, +> assert the hand-off instead: **Connect** leaves for +> `…/http_api/api/connectors/oauth2/start?connector=…&organizationId=…` with +> no `credentialId`, a row's **Reconnect** for the same URL plus +> `&credentialId=`. On success the callback lands back on > `…/settings/connectors?connected=` — the page does **not** read that -> param (no toast); the new row is the proof. +> param (no toast); the rows are the proof. Tell accounts apart by the row's +> masked preview in `GET /api/app/connector-credentials?orgId=…` +> (`maskedPreview`, `updatedAt`). +> +> **A loopback fake vendor** replaces the real one without touching the +> product: copy `configs/platform/system` outside the clone, point only the +> connector's `authorizeUrl`/`tokenUrl` at an `https://127.0.0.1:/…` +> fake that redirects back with a code and answers standard token JSON (a +> throwaway CA trusted through `NODE_EXTRA_CA_CERTS`; the token exchange +> refuses plain `http`), and start the stack with `TALE_CONFIG_SYSTEM_DIR` on +> the copy. Keep every other egress on a dead proxy so no real vendor is +> reachable. A fake that can hold on a consent page is what CONN-B7 and +> CONN-B9 need. ## Functional tests @@ -175,7 +190,10 @@ Sign in as an owner/admin — the page requires the `developerSettings` ability `…/http_api/api/connectors/oauth2/start?connector=slack&organizationId=…`; after consent the browser lands on `…/settings/connectors?connected=slack` and a new row exists: method **OAuth**, named after the connector, default - if first. No toast — the row is the assertion. In **mode A** (no Slack app + if first. No toast — the row is the assertion. Connecting a second + workspace adds a row named after it (**Slack ()**); consenting + again for a workspace already connected renews its row instead of adding + one. In **mode A** (no Slack app registered) Step 2 instead explains that the app is set up by the deployment operator (`settings.connectors.card.oauthAppMissingDeployment`) — it must never point at the OAuth apps card below, which carries no Slack @@ -186,9 +204,10 @@ Sign in as an owner/admin — the page requires the `developerSettings` ability menu → **Reconnect** (`settings.connectors.credential.reconnect`) → The row's detail line explains re-consent (`settings.connectors.credential.needsReauthHint`, or `…needsReauthDetail` - when the server recorded a reason). **Reconnect** leads the menu and - triggers the same hand-off as CONN-F15; the refreshed grant clears the - badge. + when the server recorded a reason). **Reconnect** leads the menu; its + hand-off names this row (`&credentialId=`), and the refreshed grant clears + THIS row's badge — same name, same **Default** state, no row added and no + other row changed. - [ ] `CONN-F17` · **MCP endpoint page** — `/dashboard/{org}/settings/api/mcp` → Section **MCP endpoint** (`settings.mcpEndpoint.title`) with a copyable endpoint URL ending `/api/v1/mcp` (`settings.mcpEndpoint.copyEndpoint`), @@ -201,6 +220,18 @@ Sign in as an owner/admin — the page requires the `developerSettings` ability `/dashboard/{org}/settings/mcp`, then `/dashboard/{org}/settings/mcp-servers` → Each redirects in one hop to `…/settings/connectors` (URL settles there; the table renders). +- [ ] `CONN-F19` · **A second OAuth account** — With **Gmail** connected + once (its row holds mailbox A), **Add credential** → **Gmail** → + **Connect** and consent as mailbox B → A second row **Gmail 2** appears, + not default; the **Gmail** row keeps mailbox A (its `maskedPreview` and + `updatedAt` unchanged). The first account is never replaced. Same for + Outlook, Google Drive and Teams. +- [ ] `CONN-F20` · **Reconnect a non-default row** — With two Gmail rows, + mark the non-default one stale (see CONN-F16) → its menu → **Reconnect** + → consent → That row renews (badge cleared, name and non-default state + kept); the default row is byte-for-byte unchanged. A Reconnect on a + **Disabled** row renews its grant but leaves it **Disabled** — **Enable** + is what returns it. ## Boundary & error tests @@ -235,6 +266,25 @@ Sign in as an owner/admin — the page requires the `developerSettings` ability fixed server-rendered error page — "This connection link has expired" — with a way back to connector settings. No vendor text, no request data, and no script on the page; nothing was stored. +- [ ] `CONN-B7` · **Reconnect target removed mid-consent** — Start + **Reconnect** on a row; while the vendor's consent screen is open, delete + that row from a second tab; then consent → The fixed page "This credential + cannot be reconnected"; nothing was saved and no other row changed — the + grant never lands on the default instead. +- [ ] `CONN-B8` · **Tampered reconnect link** — Open + `…/http_api/api/connectors/oauth2/start?connector=gmail&organizationId=…&credentialId=…` + with the id of a Slack row, of another organization's credential, an + unknown id, or `credentialId=` empty → The same fixed page before any + vendor page; no consent starts. Adding `credentialId=` to a callback URL + changes nothing: the target rides the server-side state only. +- [ ] `CONN-B9` · **Access lost mid-consent** — A Developer starts + **Connect**; while the vendor's consent screen is open, an Admin changes + their role to Member (or removes them); then consent → The fixed page "You + can no longer connect connectors here"; nothing was saved. +- [ ] `CONN-B10` · **Slack Reconnect in another workspace** — On a Slack row + → **Reconnect** → consent in a different workspace than the row's → The + fixed page "That is a different workspace"; nothing was saved. Reconnect + in the row's own workspace renews it. ## Accessibility (WCAG 2.1 AA) From 15007de31e27a989a32d01c56a0a687d7ee902c6 Mon Sep 17 00:00:00 2001 From: yannickmonney <102406702+yannickmonney@users.noreply.github.com> Date: Mon, 28 Sep 2026 15:33:37 +0000 Subject: [PATCH 4/7] chore: rerun checks after a hung Windows CLI test From 8596a69b6493774a671e6db0b43b2804995ccaa8 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Mon, 28 Sep 2026 20:06:53 +0200 Subject: [PATCH 5/7] fix(platform): recheck OAuth access when storing grants --- .../connectors/oauth-intent.integration.ts | 102 ++++++++++++++++++ .../backend/domains/connectors/oauth.test.ts | 10 ++ .../backend/domains/connectors/oauth.ts | 26 ++++- .../tests/manual/reference/automation.md | 2 +- 4 files changed, 136 insertions(+), 4 deletions(-) diff --git a/services/platform/backend/domains/connectors/oauth-intent.integration.ts b/services/platform/backend/domains/connectors/oauth-intent.integration.ts index 0133b024d0..1780ce8cef 100644 --- a/services/platform/backend/domains/connectors/oauth-intent.integration.ts +++ b/services/platform/backend/domains/connectors/oauth-intent.integration.ts @@ -617,6 +617,108 @@ export async function checkConnectorOauthIntent( `starts=${demotedStart.status}/${removedStart.status} (want 302), demoted=${outcomeOf(demoted)}, removed=${outcomeOf(removed)} (want forbidden), exchanges=${vendor.calls.length - callsBeforeDemoted} (want 0), unchanged=${JSON.stringify(afterAccess) === JSON.stringify(beforeDemotion)}`, ); + // Revocation can also finish while the token endpoint is in flight. + // The pre-exchange check already passed; no grant may be saved using it. + for (const revocation of ['demoted', 'removed'] as const) { + await sql` + DELETE FROM "member" + WHERE "organizationId" = ${orgId} AND "userId" = ${developer.userId} + `; + await sql` + INSERT INTO "member" ("id", "organizationId", "userId", "role", "createdAt") + VALUES (gen_random_uuid(), ${orgId}, ${developer.userId}, 'developer', ${new Date()}) + `; + const waitingStart = await start( + 'gmail', + sales.credentialId, + developer.cookie, + ); + const beforeWaiting = await rows('gmail'); + const callsBeforeWaiting = vendor.calls.length; + let releaseExchange: () => void = () => undefined; + vendor.gate = new Promise((resolve) => { + releaseExchange = resolve; + }); + const waiting = complete(waitingStart.state, developer.userId); + const exchanging = await waitUntil( + async () => vendor.calls.length > callsBeforeWaiting, + 10_000, + ); + if (revocation === 'demoted') { + await sql` + UPDATE "member" SET "role" = 'member' + WHERE "organizationId" = ${orgId} AND "userId" = ${developer.userId} + `; + } else { + await sql` + DELETE FROM "member" + WHERE "organizationId" = ${orgId} AND "userId" = ${developer.userId} + `; + } + releaseExchange(); + const settled = await waiting; + vendor.gate = null; + const afterWaiting = await rows('gmail'); + record( + `connector oauth intent: ${revocation} during token exchange stores nothing`, + waitingStart.status === 302 && + exchanging && + outcomeOf(settled) === 'error/forbidden' && + JSON.stringify(afterWaiting) === JSON.stringify(beforeWaiting), + `exchanging=${exchanging}, outcome=${outcomeOf(settled)} (want forbidden), unchanged=${JSON.stringify(afterWaiting) === JSON.stringify(beforeWaiting)}`, + ); + } + + // The revocation can already hold the member row when the callback's + // unlocked pre-check reads the old role. The store must wait and then + // check the committed role, not authorize from that earlier snapshot. + await sql` + INSERT INTO "member" ("id", "organizationId", "userId", "role", "createdAt") + VALUES (gen_random_uuid(), ${orgId}, ${developer.userId}, 'developer', ${new Date()}) + `; + const revokingStart = await start('gmail', undefined, developer.cookie); + const beforeRevoking = await rows('gmail'); + let releaseRevocation: () => void = () => undefined; + const revocationReleased = new Promise((resolve) => { + releaseRevocation = resolve; + }); + let holdRevocation: () => void = () => undefined; + const revocationHeld = new Promise((resolve) => { + holdRevocation = resolve; + }); + const revoking = sql.begin(async (tx) => { + await tx` + UPDATE "member" SET "role" = 'member' + WHERE "organizationId" = ${orgId} AND "userId" = ${developer.userId} + `; + holdRevocation(); + await revocationReleased; + }); + await revocationHeld; + const waitingForRevocation = complete( + revokingStart.state, + developer.userId, + ); + const queuedBehindRevocation = await waitUntil(async () => { + const waiting = await sql<{ count: string }[]>` + SELECT count(*)::text AS count FROM pg_stat_activity + WHERE datname = current_database() AND wait_event_type = 'Lock' + AND query ILIKE '%FOR SHARE%' AND query ILIKE '%"member"%' + `; + return waiting[0]?.count !== '0'; + }, 10_000); + releaseRevocation(); + await revoking; + const revokedWhileWaiting = await waitingForRevocation; + const afterRevoking = await rows('gmail'); + record( + 'connector oauth intent: a store queued behind a membership revocation checks the committed role', + queuedBehindRevocation && + outcomeOf(revokedWhileWaiting) === 'error/forbidden' && + JSON.stringify(afterRevoking) === JSON.stringify(beforeRevoking), + `queued=${queuedBehindRevocation}, outcome=${outcomeOf(revokedWhileWaiting)} (want forbidden), unchanged=${JSON.stringify(afterRevoking) === JSON.stringify(beforeRevoking)}`, + ); + // ---- 9. a pending row the previous image minted ---------------------- // Written with the old column list — no reconnect_credential_id. It // must read as an Add: a new credential, the default untouched. diff --git a/services/platform/backend/domains/connectors/oauth.test.ts b/services/platform/backend/domains/connectors/oauth.test.ts index 47fcd06a0b..768064fa8d 100644 --- a/services/platform/backend/domains/connectors/oauth.test.ts +++ b/services/platform/backend/domains/connectors/oauth.test.ts @@ -60,6 +60,16 @@ function sqlWithRoutes(routes: Record) { ...values: unknown[] ): Promise => { const text = strings.join('?'); + if (text.includes('FROM "member"')) { + return Promise.resolve([ + { + id: 'm-1', + organizationId: values[0], + userId: values[1], + role: 'developer', + }, + ]); + } if (text.includes('INSERT INTO app.connector_team_routes')) { const teamId = String(values[0]); const organizationId = String(values[1]); diff --git a/services/platform/backend/domains/connectors/oauth.ts b/services/platform/backend/domains/connectors/oauth.ts index 93beb351b8..bc1bb19930 100644 --- a/services/platform/backend/domains/connectors/oauth.ts +++ b/services/platform/backend/domains/connectors/oauth.ts @@ -1,4 +1,4 @@ -import type { Sql } from 'postgres'; +import type { Sql, TransactionSql } from 'postgres'; import { findConnector } from '../../../lib/connectors/catalog.ts'; import { defineAbilityFor } from '../../../lib/permissions/ability.ts'; @@ -200,7 +200,7 @@ function intentOf(reconnectCredentialId: string | null): ConsentIntent { * vendor is asking for consent, and the callback writes as that person. */ export async function connectorWriteAccess( - sql: Sql, + sql: Sql | TransactionSql, organizationId: string, userId: string, ): Promise<'allowed' | 'not_member' | 'role_forbidden'> { @@ -287,7 +287,11 @@ export type StoreGrantOutcome = | { ok: true; credentialId: string; renewed: boolean } | { ok: false; - reason: 'credential_missing' | 'account_mismatch' | 'workspace_claimed'; + reason: + | 'credential_missing' + | 'account_mismatch' + | 'workspace_claimed' + | 'forbidden'; }; /** @@ -329,6 +333,22 @@ export async function storeOauth2Grant( try { return await sql.begin(async (tx): Promise => { await lockCredentialPair(tx, args.organizationId, args.connectorSlug); + // The token exchange can outlive the callback's access check. Lock the + // current membership before checking it again, so a demotion/removal + // either wins first and refuses this write, or waits for its commit. + // A fresh read after the lock also sees a revocation that was uncommitted + // when this statement began and made it wait. + await tx` + SELECT "id" FROM "member" + WHERE "organizationId" = ${args.organizationId} AND "userId" = ${args.userId} + FOR SHARE + `; + if ( + (await connectorWriteAccess(tx, args.organizationId, args.userId)) !== + 'allowed' + ) { + return { ok: false, reason: 'forbidden' }; + } const lockGrant = (credentialId: string) => findOauth2Grant(tx, { organizationId: args.organizationId, diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 046adfbc6c..3445bf5498 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -239,7 +239,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [connectors](../suites/connectors.md) | `CONN-F17` | 🔶 component | `app/features/settings/connectors/components/mcp-endpoint-section.test.tsx` | | [connectors](../suites/connectors.md) | `CONN-F11`, `CONN-F12`, `CONN-F18`, `CONN-B2`, `CONN-B3`, `CONN-B6` | ⛔ manual-only | — (persistence reloads, live consent round trip, redirects, server refusals) | | [connectors](../suites/connectors.md) | `CONN-F15`, `CONN-F16` (full round trip) | ⛔ manual-only | — (need a real vendor consent, mode B, or a loopback fake vendor) | -| [connectors](../suites/connectors.md) | `CONN-F15`, `CONN-F16`, `CONN-F19`, `CONN-F20`, `CONN-B7`–`CONN-B10` (the backend half, #3711): a consent lands where its intent says — an Add stores a NEW credential under a name no sibling holds and never renews the default; a Reconnect renews exactly the credential its row named (id, name, default flag, mail-sync cursor and audit actor kept; `needs-reauth` cleared, `disabled` kept) or saves nothing when that credential is gone, even when the delete races the store; the start door keeps a target only when it is this organization's OAuth grant of that connector and the callback never reads one from its request; the initiator's membership and developer role are re-checked at the callback before the code is redeemed; two Adds completing at once number past each other with one default; a pending row minted before migration `0130` completes as an Add; Slack keeps one credential per workspace and refuses a Reconnect into another | ✅ automated | `backend/domains/connectors/oauth-grant-plan.test.ts` (the decision table), `backend/domains/connectors/oauth.test.ts`, `backend/domains/connectors/oauth-routes.test.ts`, `backend/integration-check.ts` (`checkConnectorOauthIntent` in `backend/domains/connectors/oauth-intent.integration.ts`, run by `backend:integration`) | +| [connectors](../suites/connectors.md) | `CONN-F15`, `CONN-F16`, `CONN-F19`, `CONN-F20`, `CONN-B7`–`CONN-B10` (the backend half, #3711): a consent lands where its intent says — an Add stores a NEW credential under a name no sibling holds and never renews the default; a Reconnect renews exactly the credential its row named (id, name, default flag, mail-sync cursor and audit actor kept; `needs-reauth` cleared, `disabled` kept) or saves nothing when that credential is gone, even when the delete races the store; the start door keeps a target only when it is this organization's OAuth grant of that connector and the callback never reads one from its request; the initiator's membership and developer role are re-checked at the callback before the code is redeemed; two Adds completing at once number past each other with one default; a pending row minted before migration `0130` completes as an Add; Slack keeps one credential per workspace and refuses a Reconnect into another; membership revocation during the token exchange or already holding the member row refuses the final grant transaction | ✅ automated | `backend/domains/connectors/oauth-grant-plan.test.ts` (the decision table), `backend/domains/connectors/oauth.test.ts`, `backend/domains/connectors/oauth-routes.test.ts`, `backend/integration-check.ts` (`checkConnectorOauthIntent` in `backend/domains/connectors/oauth-intent.integration.ts`, run by `backend:integration`) | | [connectors](../suites/connectors.md) | `CONN-F15`, `CONN-F16`, `CONN-F20` (the hand-off): **Connect** starts an Add naming no credential, a row's **Reconnect** names that row — the default's sibling included | 🔶 component | `app/features/settings/connectors/connector-oauth.test.ts`, `app/features/settings/connectors/components/connectors-settings.test.tsx` | | [conversations](../suites/conversations.md) | `CONV-G1`–`CONV-G3`, `CONV-F1`–`CONV-F10`, `CONV-B1`–`CONV-B4`, `CONV-F27`, `CONV-F28`, `CONV-F30` | ⛔ manual-only | — (the `email-automation` spec, which automated the gate, redirect, channel filter, and reading pane, was retired in #2857 and has no successor; `home-panel.test.tsx` only proves the Inbox view is absent without an inbox) | | [conversations](../suites/conversations.md) / [responsive](../suites/responsive.md) | `CONV-F29`, `RESP-F11` (the conversation's half): the header's identity mark is the contact's initials, the subject with a title fallback, the contact's name, the relative time, the email and the source (mailbox · address or the API source) in that order, each separator grouped with its item, the actions menu; the phone's back control shows only over an open conversation or compose and leads to the Home list | 🔶 component | `app/features/conversations/components/conversation-header.test.tsx`, `app/features/conversations/components/inbox-mobile-back-button.test.tsx`; the composer frame stays manual, the header at real widths is `RESP-F16`'s row | From 0954872080acaed6b9f42aaf0641831ab29f4089 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Mon, 28 Sep 2026 20:15:30 +0200 Subject: [PATCH 6/7] fix(platform): localize OAuth reconnect error pages --- .../core/http_connectors/error_page.ts | 83 +++++++++++++++- .../domains/connectors/oauth-routes.test.ts | 94 +++++++++++++++++++ .../domains/connectors/oauth-routes.ts | 5 + .../tests/manual/reference/automation.md | 1 + 4 files changed, 180 insertions(+), 3 deletions(-) diff --git a/services/platform/backend/core/http_connectors/error_page.ts b/services/platform/backend/core/http_connectors/error_page.ts index 686827e1d8..4354ebb042 100644 --- a/services/platform/backend/core/http_connectors/error_page.ts +++ b/services/platform/backend/core/http_connectors/error_page.ts @@ -13,6 +13,13 @@ * surface by anything upstream of it. */ +import { parseAcceptLanguage } from '@tale/ui/i18n/accept-language'; +import { + baseLocaleOf, + SUPPORTED_LOCALES, + type SupportedLocale, +} from '@tale/ui/i18n/locales'; + import { basePath } from '../lib/helpers/public_origin.ts'; export type ConnectorErrorKind = @@ -107,6 +114,70 @@ const ERROR_COPY: Record = { }, }; +/** Only the newly introduced intent errors opt into localized server copy. + * Older callback kinds retain their existing English path. */ +const LOCALIZED_COPY: Partial< + Record< + ConnectorErrorKind, + Record> + > +> = { + credential_missing: { + en: ERROR_COPY.credential_missing, + de: { + title: 'Diese Zugangsdaten können nicht neu verbunden werden', + detail: + 'Sie wurden entfernt oder gehören nicht zu einer OAuth-Verbindung dieses Connectors. Deshalb wurde nichts gespeichert, und andere Zugangsdaten bleiben unverändert. Prüfe deine Connector-Einstellungen und füge das Konto erneut hinzu, wenn du es noch brauchst.', + }, + fr: { + title: 'Ces identifiants ne peuvent pas être reconnectés', + detail: + 'Ils ont été supprimés ou ne correspondent pas à une connexion OAuth de ce connecteur. Rien n’a donc été enregistré et aucun autre identifiant n’a changé. Vérifie les paramètres de tes connecteurs et ajoute à nouveau le compte si tu en as encore besoin.', + }, + }, + account_mismatch: { + en: ERROR_COPY.account_mismatch, + de: { + title: 'Das ist ein anderer Workspace', + detail: + 'Du hast einen anderen Workspace als den freigegeben, den diese Zugangsdaten verbinden. Deshalb wurde nichts gespeichert. Wähle erneut Neu verbinden und gib denselben Workspace frei. Über Zugangsdaten hinzufügen kannst du stattdessen den anderen verbinden.', + }, + fr: { + title: 'Il s’agit d’un autre espace de travail', + detail: + 'Tu as autorisé un autre espace de travail que celui associé à ces identifiants. Rien n’a donc été enregistré. Sélectionne à nouveau Reconnecter et choisis le même espace, ou utilise Ajouter des identifiants pour connecter l’autre.', + }, + }, + forbidden: { + en: ERROR_COPY.forbidden, + de: { + title: 'Du kannst hier keine Connectors mehr verbinden', + detail: + 'Dein Zugriff auf diese Organisation hat sich während des Verbindungsvorgangs geändert. Deshalb wurde nichts gespeichert. Inhaber, Admins und Entwickler können Connectors verbinden. Wende dich an einen Admin der Organisation.', + }, + fr: { + title: 'Tu ne peux plus connecter de connecteurs ici', + detail: + 'Ton accès à cette organisation a changé pendant la connexion. Rien n’a donc été enregistré. Les Propriétaires, Admins et Développeurs peuvent connecter des connecteurs. Adresse-toi à un admin de l’organisation.', + }, + }, +}; + +const BACK_LINK: Record = { + en: 'Back to connector settings', + de: 'Zurück zu den Connector-Einstellungen', + fr: 'Retour aux paramètres des connecteurs', +}; + +function errorLocale(acceptLanguage: string): SupportedLocale { + const preferred = parseAcceptLanguage(acceptLanguage).find((candidate) => + SUPPORTED_LOCALES.some( + (supported) => candidate.toLowerCase().split('-')[0] === supported, + ), + ); + return baseLocaleOf(preferred?.toLowerCase()); +} + function escapeHtml(value: string): string { return value .replaceAll('&', '&') @@ -125,11 +196,14 @@ function escapeHtml(value: string): string { export function renderConnectorErrorPage( kind: ConnectorErrorKind, backUrl?: string | null, + acceptLanguage = '', ): Response { - const copy = ERROR_COPY[kind]; - const backLink = `\n

${backUrl ? 'Back to connector settings' : 'Tale'}

`; + const translated = LOCALIZED_COPY[kind]; + const locale = translated === undefined ? 'en' : errorLocale(acceptLanguage); + const copy = { ...ERROR_COPY[kind], ...translated?.[locale] }; + const backLink = `\n

${backUrl ? escapeHtml(BACK_LINK[locale]) : 'Tale'}

`; const html = ` - + @@ -145,6 +219,9 @@ export function renderConnectorErrorPage( status: copy.status, headers: { 'Content-Type': 'text/html; charset=utf-8', + ...(translated !== undefined + ? { 'Content-Language': locale, Vary: 'Accept-Language' } + : {}), // The URL of a failed callback still carries the vendor's `code`/`state` // in the query string; caching it anywhere would persist them. 'Cache-Control': 'no-store', diff --git a/services/platform/backend/domains/connectors/oauth-routes.test.ts b/services/platform/backend/domains/connectors/oauth-routes.test.ts index ceefb38c26..d913e3ab38 100644 --- a/services/platform/backend/domains/connectors/oauth-routes.test.ts +++ b/services/platform/backend/domains/connectors/oauth-routes.test.ts @@ -16,6 +16,7 @@ vi.mock('./oauth.ts', () => ({ startOauth2, })); +import { renderConnectorErrorPage } from '../../core/http_connectors/error_page.ts'; import { createConnectorOauthRoutes } from './oauth-routes.ts'; function app(session: SessionBundle | null) { @@ -186,3 +187,96 @@ describe('the consent intent', () => { }, ); }); + +describe('localized consent intent errors', () => { + afterEach(() => vi.unstubAllEnvs()); + it.each([ + ['credential_missing', 'en', 'This credential cannot be reconnected', 404], + [ + 'credential_missing', + 'de', + 'Diese Zugangsdaten können nicht neu verbunden werden', + 404, + ], + [ + 'credential_missing', + 'fr', + 'Ces identifiants ne peuvent pas être reconnectés', + 404, + ], + ['account_mismatch', 'en', 'That is a different workspace', 409], + ['account_mismatch', 'de', 'Das ist ein anderer Workspace', 409], + ['account_mismatch', 'fr', 'Il s’agit d’un autre espace de travail', 409], + ['forbidden', 'en', 'You can no longer connect connectors here', 403], + ['forbidden', 'de', 'Du kannst hier keine Connectors mehr verbinden', 403], + ['forbidden', 'fr', 'Tu ne peux plus connecter de connecteurs ici', 403], + ] as const)('renders %s in %s', async (kind, locale, title, status) => { + const response = renderConnectorErrorPage( + kind, + '/dashboard/org-1/settings/connectors', + locale, + ); + const html = await response.text(); + expect(response.status).toBe(status); + expect(html).toContain(``); + expect(html).toContain(`

${title}

`); + expect(html).toContain( + { + en: 'Back to connector settings', + de: 'Zurück zu den Connector-Einstellungen', + fr: 'Retour aux paramètres des connecteurs', + }[locale], + ); + expect(response.headers.get('cache-control')).toBe('no-store'); + expect(response.headers.get('content-security-policy')).toContain( + "default-src 'none'", + ); + }); + it.each([ + ['de-CH,de;q=0.9,en;q=0.8', 'de'], + ['fr;q=0.2,de;q=0.8', 'de'], + ['ja-JP,de-DE;q=0.8,en;q=0.7', 'de'], + ['FR-fr,en;q=0.5', 'fr'], + ['ja-JP,es;q=0.5', 'en'], + ['', 'en'], + ])('resolves header %s to %s', async (header, locale) => { + const response = renderConnectorErrorPage('forbidden', null, header); + expect(await response.text()).toContain(``); + }); + it('escapes the back link and does not reflect a language header', async () => { + const response = renderConnectorErrorPage( + 'account_mismatch', + '/settings?x="', + ); + const html = await response.text(); + expect(html).toContain(''); + expect(html).toContain('href="/settings?x="<script>&"'); + expect(html).not.toContain('