Repository navigation
Description
P1 · Reproduced locally at d351611bdd942ffeed758147ccaf57e70877125a (origin/main, 2026-09-28) in Chromium against the real backend and PostgreSQL.
For every OAuth connector without a workspace id — Gmail, Microsoft Outlook, Google Drive, Microsoft Teams — a completed consent is always written onto the connector's default (else oldest) OAuth credential. Two ordinary paths therefore change a credential the user did not choose, and silently swap the account behind it:
- Adding another account. Add credential → Gmail (step 2 reads "New credential for Gmail.") → Connect → consent as a second mailbox. No row is added. The existing "Gmail" credential now holds the second mailbox's grant and the first mailbox's grant is gone.
- Reconnect on a non-default row. Row "Gmail sales" → Reconnect → consent. "Gmail sales" is left untouched, still on its old grant. The default "Gmail" is overwritten with the new consent instead.
Reproduction
- Settings → Connectors → OAuth apps → Gmail → Configure, and save a client ID and secret.
- Add credential → Gmail → Connect; consent as mailbox A. The row "Gmail" appears with the Default badge.
- Add credential → Gmail → Connect again; consent as mailbox B.
- Look at the table and at the credential (
GET /api/app/connector-credentials): there is still one Gmail row, with the same id. Its secret changed and its masked preview now belongs to mailbox B. - Give the organization a second, non-default Gmail OAuth credential "Gmail sales". It can come from
POST /api/app/connector-credentialswithauthMethod: "oauth2", an import, or two consents that race. Then use its row menu → Reconnect and consent.
Expected: Step 3 adds a credential, for example "Gmail 2", and leaves "Gmail" on mailbox A. That is what the dialog ("New credential for Gmail.") and the connector guide ("Connectors with existing credentials appear first, but you can add another account for the same service") promise. Step 5 renews the credential whose row was used: the admin guide says Reconnect "keeps the credential's name and references". If one OAuth account per connector is the intended product rule, the flow must say so and refuse or confirm the replacement. It must never swap the account silently.
Actual: See the frozen output below. There is no toast in either path. The browser lands on …/settings/connectors?connected=gmail and the table shows the same single Gmail row.
User impact
Every workflow, mailbox sync or agent read that uses the default Gmail/Outlook/Drive/Teams credential starts acting on another account without any visible change: a different mailbox is read, mail is sent from it, and a different Drive is imported. The original account's grant is discarded with no trace in the UI. Reconnect cannot repair a non-default OAuth credential; each attempt re-points the default instead.
Cause
storeOauth2Grantruns for every completed consent (called at oauth.ts:569).- Only Slack returns a
teamId. For every other connector, if any OAuth grant exists, it renewsgrants.find(isDefault) ?? oldest(oauth.ts:271–273).
- Only Slack returns a
- The start door carries no intent: both "Connect" (credential-adapter.tsx:265) and "Reconnect" (credential-adapter.tsx:326–332) call
goToAuthorization(organizationId, slug)(connector-oauth.ts:32). The callback therefore cannot know whether the user asked for a new credential or which one to renew. - The unit test oauth.test.ts:205 ("reconnects a connector without a workspace notion through its default grant") locks the behaviour in.
Executable local proof and controls
probes/proof-oauth-grant.cjs (below) runs against a fresh synthetic organization. Frozen output from the run at d351611bd:
setup: fresh org mqzqSgzN7GSxDQnyG6Wdnm4dbTu5m4iR; org Gmail OAuth app (synthetic) -> 200
step 1 (Add credential > Gmail > Connect, consent as ACCA): step2 says "New credential for Gmail."; landed settings/connectors?connected=gmail; gmail rows = [{"id":"a88a760c","name":"Gmail","preview":"ACCA…02","isDefault":true,"updatedAt":1790599403327}]
CONTROL first consent creates one Gmail credential holding account ACCA
step 2 (Add credential > Gmail > Connect, consent as ACCB): step2 says "New credential for Gmail."; landed settings/connectors?connected=gmail; gmail rows = [{"id":"a88a760c","name":"Gmail","preview":"ACCB…04","isDefault":true,"updatedAt":1790599415635}]
CONFIRMED adding a second Gmail account created no credential: existing "Gmail" (a88a760c) was re-pointed from ACCA to ACCB
fixture: "Gmail sales" (oauth2, non-default) -> 201; gmail rows = [{"id":"a88a760c","name":"Gmail","preview":"ACCB…04","isDefault":true,"updatedAt":1790599415635},{"id":"85cf1650","name":"Gmail sales","preview":"ACCS…00","isDefault":false,"updatedAt":1790599421616}]
step 3 (row "Gmail sales" > Reconnect, consent as ACCS): gmail rows = [{"id":"a88a760c","name":"Gmail","preview":"ACCS…06","isDefault":true,"updatedAt":1790599427834},{"id":"85cf1650","name":"Gmail sales","preview":"ACCS…00","isDefault":false,"updatedAt":1790599421616}]
CONFIRMED Reconnect on "Gmail sales" left it untouched and stored ACCS on the default "Gmail" instead
control (Slack, deployment app from synthetic env): consents WSA1, WSB2, WSA1 -> [{"name":"Slack","preview":"WSA1…12","isDefault":true},{"name":"Slack (Workspace WSB2)","preview":"WSB2…10","isDefault":false}]
CONTROL workspace-routed Slack keeps one credential per workspace and renews only the matching one
Controls:
- The first consent creates exactly one credential holding account ACCA (
CONTROLline). - Slack is routed by workspace (
team.id). A second workspace becomes its own row, "Slack (Workspace WSB2)". A repeat consent for WSA1 renews only the WSA1 row (CONTROLline). The defect is specific to the default-grant fallback. - A vendor refusal (
invalid_grantfrom the fake token endpoint) ends on the fixed "The provider declined the connection … nothing was saved" page, and the stored credentials are byte-for-byte unchanged (exploration probep2-failures.cjs).
Mocked boundary
Only the OAuth vendor is mocked.
- Catalog copy.
TALE_CONFIG_SYSTEM_DIRpoints at a copy ofconfigs/platform/system. In it, exactly theauthorizeUrlandtokenUrlof gmail, google-drive, outlook, teams and slack are replaced byhttps://127.0.0.1:4443/<slug>/{authorize,token}. That is a local HTTPS fake, trusted by the backend throughNODE_EXTRA_CA_CERTSand a throwaway local CA. - Fake vendor behaviour. It consents at once as the account id chosen through
GET /control?account=<id>. It answers standard token JSON whoseaccess_tokenstarts with that id, so the credential's own masked preview (first 4 + last 2 characters) names the account that consented. - Synthetic apps. The org Gmail OAuth app is a synthetic client id/secret saved through the real
PUT /api/app/connector-oauth-apps/gmail. Slack uses syntheticCONNECTOR_OAUTH_SLACK_CLIENT_ID/SECRETenvironment references. - Real: the SPA, the start door (state + PKCE), the callback, the token-exchange code, and credential encryption and storage in PostgreSQL.
- No Google, Microsoft or Slack endpoint was contacted, and no mail was read or sent.
Local stack (loopback only): a detached worktree of d351611bd with bun install --frozen-lockfile; a fresh PostgreSQL 16.13 + pg_search 0.22.6 + pgvector 0.8.1 cluster bootstrapped like the tale-db image plus services/db/init-scripts; the backend from services/platform (node --experimental-transform-types --import ./backend/node-loader.mjs backend/main.ts, TALE_ROLE=all, PORT=3005, SITE_URL=http://localhost:3000, an empty TALE_CONFIG_DIR, TALE_CONFIG_BUILTIN_DIR=configs/platform/custom, TALE_DEV_SEED_USER=1, TALE_ALLOW_OPEN_SIGN_UP=true, locally generated ENCRYPTION_SECRET_HEX/BETTER_AUTH_SECRET); the SPA via TALE_BACKEND_URL=http://127.0.0.1:3005 bunx --bun vite --port 3000; Chromium 141 driven by the worktree's playwright-core 1.58.2. The backend ran with NODE_USE_ENV_PROXY=1 HTTPS_PROXY=HTTP_PROXY=http://127.0.0.1:9 NO_PROXY=127.0.0.1,localhost,::1, so every non-loopback fetch failed at a dead proxy: no real provider, mailbox or external service was reachable. Each proof mints its own synthetic organization through POST /api/auth/sign-up/email + POST /api/auth/organization/create.
Deduplication
- Searched the bodies of all 1,035 issues in every state for reconnect, renew/renewal, grant, second/another account,
storeOauth2Grantand default grant: no match. - bug(platform): disconnected equipped connectors cannot be removed from a project agent #3656 (removing disconnected equipped connectors from agents), bug(platform): Add credential Back bypasses pending-save guard and loses the rejected request draft #3674 (Back during a pending save), bug(platform): credential-list refresh silently discards an unrelated open credential draft #3667 (table remount) and bug(platform): failed custom-provider credential edit still changes the provider URL and name #3662/bug(platform): stale custom-provider editor overwrites newer settings by reading the latest hash at Save #3663 (custom-provider editor) have different roots.
- Not in
.agents/repo.md's debt ledgers or intests/manual/reference/not-a-finding.md. - Found by the TALE-78 local audit (connector configuration, scope and recovery).
probes/lib.cjs (shared helpers)
// Shared helpers for the TALE-78 local audit probes. Everything targets the local stack only:
// SPA http://localhost:3000 (proxying /api to the backend on :3005), fake vendor https://127.0.0.1:4443.
const { chromium } = require('/agent/.runtime/home/scratch/tale78/tale/node_modules/playwright-core');
const fs = require('node:fs');
const BASE = 'http://localhost:3000';
const ORIGIN = { origin: BASE };
const PW = 'TaleAudit!Passw0rd';
const USERS = {
owner: { email: 'dev@tale.test', password: 'TaleDev!Passw0rd' },
};
async function launch() {
return chromium.launch({ executablePath: '/opt/ms-playwright/chromium-1194/chrome-linux/chrome', headless: true });
}
async function newContext(browser, opts = {}) {
const context = await browser.newContext({ baseURL: BASE, ignoreHTTPSErrors: true, serviceWorkers: 'block', viewport: opts.viewport ?? { width: 1280, height: 900 }, locale: 'en-US' });
return context;
}
async function signIn(context, who) {
const u = typeof who === 'string' ? (USERS[who] ?? { email: who, password: PW }) : who;
const r = await context.request.post('/api/auth/sign-in/email', { data: { email: u.email, password: u.password }, headers: ORIGIN });
if (!r.ok()) throw new Error(`sign-in ${u.email} -> ${r.status()} ${await r.text()}`);
return r.json();
}
async function api(context, method, path, data) {
const r = await context.request.fetch(path, { method, data, headers: ORIGIN });
let body = null;
const text = await r.text();
try { body = JSON.parse(text); } catch { body = text; }
return { status: r.status(), body };
}
function watch(page, sink) {
page.on('console', (m) => { if (['error', 'warning'].includes(m.type())) sink.push(`[console.${m.type()}] ${m.text().slice(0, 300)}`); });
page.on('pageerror', (e) => sink.push(`[pageerror] ${String(e).slice(0, 300)}`));
page.on('response', (r) => { if (r.status() >= 400 && r.url().includes('/api/')) sink.push(`[http ${r.status()}] ${r.request().method()} ${r.url().replace(BASE, '')}`); });
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
module.exports = { launch, newContext, signIn, api, watch, sleep, BASE, ORIGIN, PW, USERS, fs };
// ---- fresh synthetic organizations for self-contained proofs ------------------------------------
async function freshOrg(browser, label) {
const stamp = `${label}-${Date.now().toString(36)}`;
const email = `proof-${stamp}@tale.test`;
const ctx = await newContext(browser);
const su = await api(ctx, 'POST', '/api/auth/sign-up/email', { email, password: PW, name: `Proof ${label}` });
if (su.status !== 200) throw new Error(`sign-up ${email}: ${su.status} ${JSON.stringify(su.body)}`);
const org = await api(ctx, 'POST', '/api/auth/organization/create', { name: `Proof ${stamp}`, slug: `proof-${stamp}` });
if (org.status !== 200) throw new Error(`org create: ${org.status} ${JSON.stringify(org.body)}`);
await api(ctx, 'POST', '/api/auth/organization/set-active', { organizationId: org.body.id });
return { ctx, orgId: org.body.id, email, stamp };
}
async function addMember(browser, owner, role) {
const email = `proof-${owner.stamp}-${role}@tale.test`;
const ctx = await newContext(browser);
const su = await api(ctx, 'POST', '/api/auth/sign-up/email', { email, password: PW, name: `Proof ${role}` });
const add = await api(owner.ctx, 'POST', `/api/app/members?orgId=${owner.orgId}`, { userId: su.body.user.id, role });
if (add.status !== 200) throw new Error(`add member ${role}: ${add.status} ${JSON.stringify(add.body)}`);
return { ctx, email, memberId: add.body.memberId };
}
const creds = async (ctx, orgId) => (await api(ctx, 'GET', `/api/app/connector-credentials?orgId=${orgId}`)).body.credentials;
const vendorControl = (q) => fetch(`https://127.0.0.1:4443/control?${q}`).then((r) => r.json());
const toasts = async (page) => (await page.locator('[role="region"] li').allInnerTexts()).map((s) => s.replace(/\s*\n+\s*/g, ' ').trim()).filter(Boolean);
const focusedDesc = (page) => page.evaluate(() => { const e = document.activeElement; if (!e || e === document.body) return 'BODY'; return `${e.tagName.toLowerCase()} "${(e.getAttribute('aria-label') || e.innerText || '').trim().split('\n')[0].slice(0, 50)}"`; });
Object.assign(module.exports, { freshOrg, addMember, creds, vendorControl, toasts, focusedDesc });probes/proof-oauth-grant.cjs
// PROOF: an OAuth consent for a connector without a workspace id (Gmail) is always stored on the
// connector's DEFAULT grant — a second account via "Add credential" and a Reconnect on another row both
// overwrite the default instead of creating/renewing the row the user acted on.
// Mocked boundary: the vendor (authorize + token endpoints) is the local fake at https://127.0.0.1:4443
// (catalog copy with only those two URLs changed). Everything else is the real SPA, backend and Postgres.
const L = require('./lib.cjs');
const gmailRows = (list) => list.filter((c) => c.connectorSlug === 'gmail').map((c) => ({ id: c.id.slice(0, 8), name: c.name, preview: c.maskedPreview, isDefault: c.isDefault, updatedAt: c.updatedAt }));
async function connectViaAdd(page, orgId, vendorName) {
await page.goto(`/dashboard/${orgId}/settings/connectors`);
await page.getByRole('button', { name: 'Add credential' }).first().click();
const dlg = page.getByRole('dialog');
await dlg.getByRole('button', { name: new RegExp(`^${vendorName}`) }).first().click();
const step2 = (await dlg.innerText()).split('\n').find((l) => l.startsWith('New credential')) ?? '?';
const back = page.waitForURL(/connected=|oauth2\/callback/, { timeout: 30000 });
await dlg.getByRole('button', { name: 'Connect' }).click();
await back;
await page.waitForTimeout(1500);
return { step2, landed: page.url().replace(/.*\/settings\//, 'settings/') };
}
(async () => {
const browser = await L.launch();
const owner = await L.freshOrg(browser, 'oauth');
const o = owner.orgId;
const app = await L.api(owner.ctx, 'PUT', `/api/app/connector-oauth-apps/gmail?orgId=${o}`, { clientId: 'synthetic-gmail-client.apps.local', clientSecret: 'synthetic-gmail-secret' });
console.log(`setup: fresh org ${o}; org Gmail OAuth app (synthetic) -> ${app.status}`);
const page = await owner.ctx.newPage();
// Consent 1 — account ACCA — the first Gmail credential.
await L.vendorControl('account=ACCA');
let r = await connectViaAdd(page, o, 'Gmail');
const after1 = gmailRows(await L.creds(owner.ctx, o));
console.log(`step 1 (Add credential > Gmail > Connect, consent as ACCA): step2 says "${r.step2}"; landed ${r.landed}; gmail rows = ${JSON.stringify(after1)}`);
console.log(after1.length === 1 && after1[0].preview.startsWith('ACCA') ? 'CONTROL first consent creates one Gmail credential holding account ACCA' : 'UNEXPECTED first consent');
// Consent 2 — account ACCB through "Add credential" again ("New credential for Gmail.").
await L.vendorControl('account=ACCB');
r = await connectViaAdd(page, o, 'Gmail');
const after2 = gmailRows(await L.creds(owner.ctx, o));
console.log(`step 2 (Add credential > Gmail > Connect, consent as ACCB): step2 says "${r.step2}"; landed ${r.landed}; gmail rows = ${JSON.stringify(after2)}`);
if (after2.length === 1 && after2[0].id === after1[0].id && after2[0].preview.startsWith('ACCB')) console.log(`CONFIRMED adding a second Gmail account created no credential: existing "${after2[0].name}" (${after2[0].id}) was re-pointed from ACCA to ACCB`);
else console.log('NOT REPRODUCED step 2');
// Fixture: a second, non-default Gmail grant (as an import, the API or a concurrent consent can leave).
const seeded = await L.api(owner.ctx, 'POST', `/api/app/connector-credentials?orgId=${o}`, { connectorSlug: 'gmail', authMethod: 'oauth2', name: 'Gmail sales', secret: { accessToken: 'ACCS-seeded-000000', refreshToken: 'rt.gmail.ACCS.0', scopes: ['fake.scope'] } });
const before3 = gmailRows(await L.creds(owner.ctx, o));
console.log(`fixture: "Gmail sales" (oauth2, non-default) -> ${seeded.status}; gmail rows = ${JSON.stringify(before3)}`);
// Consent 3 — Reconnect on the "Gmail sales" row, consenting as ACCS.
await L.vendorControl('account=ACCS');
await page.goto(`/dashboard/${o}/settings/connectors`);
await page.getByRole('button', { name: 'Actions for Gmail sales' }).click();
const back = page.waitForURL(/connected=|oauth2\/callback/, { timeout: 30000 });
await page.getByRole('menuitem', { name: 'Reconnect' }).click();
await back; await page.waitForTimeout(1500);
const after3 = gmailRows(await L.creds(owner.ctx, o));
console.log(`step 3 (row "Gmail sales" > Reconnect, consent as ACCS): gmail rows = ${JSON.stringify(after3)}`);
const sales3 = after3.find((c) => c.name === 'Gmail sales'); const sales0 = before3.find((c) => c.name === 'Gmail sales');
const def3 = after3.find((c) => c.isDefault);
if (sales3.preview === sales0.preview && sales3.updatedAt === sales0.updatedAt && def3.preview.startsWith('ACCS')) console.log(`CONFIRMED Reconnect on "Gmail sales" left it untouched and stored ACCS on the default "${def3.name}" instead`);
else console.log('NOT REPRODUCED step 3');
// Control — Slack routes by workspace (team.id): a second workspace is a new row, a re-consent renews its own row.
for (const acct of ['WSA1', 'WSB2', 'WSA1']) { await L.vendorControl(`account=${acct}`); await connectViaAdd(page, o, 'Slack'); }
const slack = (await L.creds(owner.ctx, o)).filter((c) => c.connectorSlug === 'slack').map((c) => ({ name: c.name, preview: c.maskedPreview, isDefault: c.isDefault }));
console.log(`control (Slack, deployment app from synthetic env): consents WSA1, WSB2, WSA1 -> ${JSON.stringify(slack)}`);
console.log(slack.length === 2 && slack.some((c) => c.name.includes('WSB2')) ? 'CONTROL workspace-routed Slack keeps one credential per workspace and renews only the matching one' : 'CONTROL FAILED');
await browser.close();
})().catch((e) => { console.error(e); process.exit(1); });
Activity