diff --git a/docs/contributing/organization-deletion-containment.md b/docs/contributing/organization-deletion-containment.md index b63b7d75ef8..bcd56ab9db0 100644 --- a/docs/contributing/organization-deletion-containment.md +++ b/docs/contributing/organization-deletion-containment.md @@ -6,10 +6,13 @@ description: Why direct organization deletion is unavailable, which routes are c # Organization deletion containment (#6827) Self-service `DELETE /api/organizations/:orgId` and administrative force-delete -`DELETE /api/admin/accounts/:orgId` are temporarily unavailable. This is a -containment slice, not closure of #6827 or a safe organization deletion service. +`DELETE /api/admin/accounts/:orgId` are temporarily unavailable, and so is +organization merge, which deleted an organization as its final step. These are +containment slices, not closure of #6827 or a safe organization deletion service. -Requests reaching either handler receive HTTP **503** with the stable body: +Requests reaching either delete handler receive HTTP **503** with the stable body +below. Organization merge is contained too, with its own code and behind +administrative authentication — see the merge section further down. ```json { @@ -30,6 +33,10 @@ subscription status, confirmation text, `force` parameter, or linked canonical sibling. Unknown IDs receive the same response. Repeated calls perform no work; there is no operation ID or retry schedule because no operation was accepted. +Everything in this section describes the two DELETE routes. The contained merge +route runs *after* `requireGlobalAdmin`, so none of the anonymous-reachability +properties below apply to it. + Global parsing, CSRF protection and ordinary request metrics remain in place. A parser or CSRF rejection may precede the 503, and the global JSON body parser still accepts its usual limit for these paths before the route is matched — both @@ -119,29 +126,122 @@ the schema. What the demonstration established about the parent tree: Any future lifecycle design must inventory this edge rather than assume the foreign-key graph cleans it up. -## Deletion writers this containment does NOT cover - -This slice contains two routes, not the capability. Organization deletion is -still reachable today through organization merge, which has the same split-state -shape this document describes as removed: - -- `POST /api/admin/cleanup/merge` (`server/src/routes/admin/cleanup.ts`), and -- the Addie `merge_organizations` admin tool - (`server/src/addie/mcp/admin-tools.ts`), which dispatches the same work from - natural language with no typed-name confirmation. - -Both call `mergeOrganizations` (`server/src/db/org-merge-db.ts`), which deletes -the secondary organization's local row inside the transaction, commits, and only -then attempts `workos.organizations.deleteOrganization`, downgrading a provider -failure to a warning while still reporting success. That is the same live -provider organization with deleted local state, plus a durable audit row -asserting the merge. The Addie path attempts the provider delete twice — once -inside `mergeOrganizations` and again at step 4 of the tool handler — and -interleaves WorkOS membership creation in the primary organization between the -local commit and that second attempt, so its unknown-outcome surface is strictly -larger than the HTTP merge route's. Both entry points are admin-gated. All of -this predates the containment and is out of its scope; closing it needs its own -reviewed change and is tracked separately under #6827. +## Organization merge: contained by the follow-up + +Organization merge was the remaining organization-deletion writer. It is now +contained too, on the same terms and with the same stable shape. + +Merge deleted the secondary organization: `mergeOrganizations` +(`server/src/db/org-merge-db.ts`) removed the local organization row inside its +transaction, committed, and only then attempted +`workos.organizations.deleteOrganization`, downgrading a provider failure to a +warning while still reporting success. The Addie path attempted the provider +delete twice — once inside `mergeOrganizations` and again at step 4 of the tool +handler — and interleaved WorkOS membership creation in the primary organization +between the local commit and that second attempt, so its unknown-outcome surface +was strictly larger than the HTTP route's. + +Both entry points now refuse before any merge-specific effect: + +- `POST /api/admin/cleanup/merge` (`server/src/routes/admin/cleanup.ts`) returns + HTTP **503** with the stable body below. Administrative gating is deliberately + **unchanged** — `requireGlobalAdmin` still authenticates and authorizes, unlike + the contained deletion routes, because nothing here needs to run before + authentication. The refusal precedes body validation and every merge-specific + effect. +- The Addie `merge_organizations` tool refuses execution before it reads provider + memberships, and no longer acquires a WorkOS client at all on that path — the + client is now constructed inside the read-only preview branch rather than at + handler entry. The refusal names the stable code, points at preview, and tells + the model not to improvise a manual database or WorkOS workaround. + +```json +{ + "error": "organization_merge_unavailable", + "message": "Organization merge is temporarily unavailable." +} +``` + +`mergeOrganizations` itself refuses at the shared service boundary, throwing +`OrganizationMergeUnavailableError` with the same stable code before `getPool()`, +before `pool.connect()` and before `BEGIN`. That is defense in depth: an +overlooked caller, a new caller, or a script that bypasses both entry points +still cannot execute the sequence. The previous implementation was removed rather +than left unreachable behind the guard, because that sequence *is* the hazard — +re-enabling merge has to be a new reviewed implementation meeting the acceptance +requirements below, not the deletion of a guard. + +After this follow-up there are **no production call sites of +`workos.organizations.deleteOrganization` left in `server/src`**, so no server +route, tool or service calls the provider's organization-delete operation. The +claim is about SDK call sites; it is not a general statement about every request +this server can construct. + +### Operator bypasses closed alongside the route and tool + +A containment that only covers routes and services is one an operator can walk +around. Two checked-in surfaces handed them the prohibited operation: + +- `scripts/incidents/2026-05-cleanup-duplicate-prospect-stubs.ts` deleted + duplicate organization rows with direct SQL, and its own header reasoned from + the absence of an admin delete endpoint that a script was the sanctioned + route. Its destructive path is removed: it no longer imports a database + client, issues no writes, and `--execute` hard-refuses before any other + statement runs. The read-only analysis and report are preserved. +- The `unique-org-per-email-domain` invariant emitted a ready-to-paste raw SQL + delete with the organization ID already filled in, and pointed at a merge + endpoint that does not exist. Its `remediation_hint` now routes to read-only + `preview-merge` inspection plus escalation, and names both containment codes. + +`server/tests/unit/organization-delete-statement-guard.test.ts` is the static +guard for this: it scans the JavaScript, TypeScript and SQL files under +`server/src`, `server/scripts` and `scripts` for a raw organization delete and +fails on anything outside a small allowlist that records +why each remaining occurrence is not operator-reachable. Re-introducing a bypass +now requires a deliberate, reviewed edit to that allowlist. + +### Remaining honest limitations + +- **Merge preview stays available and is genuinely read-only.** + `previewMerge` and `GET /api/admin/cleanup/preview-merge` issue only SELECT and + COUNT statements. Preview still projects what a merge *would* move, including + that the secondary organization would be deleted from WorkOS. The tool's + WorkOS section uses conditional wording; the existing Stripe and data-movement + warnings are unchanged. The tool output states that execution will refuse. +- **Three code paths still contain a raw organization delete, none of them a + deletion service** — all three are recorded in the static guard's allowlist. + `OrganizationDatabase.deleteOrganization` + (`server/src/db/organization-db.ts`) has no callers and predates this work. + Prospect creation (`server/src/services/prospect.ts`) removes the row it + inserted moments earlier in the same call when the domain link conflicts; it + never removes a pre-existing organization, but it does leave the WorkOS + organization it had just created behind. That orphan is a pre-existing + creation-rollback gap, not an organization-deletion path, and is out of scope. + `server/scripts/setup-sandbox.ts` seeds and tears down a local sandbox; it is + bounded to `org_aao_sandbox_*` IDs and refuses to run unless + `STRIPE_SECRET_KEY` is `sk_test_*`, so it never touches production data. It is + documented and allowlisted rather than changed. +- **The `merge_organizations` tool's declared description and usage hints are + unchanged.** They still read "Destructive, cannot be undone" and "Preview + first, then execute with `preview=false`", which is now misleading. Changing + them is a one-line edit, but `scripts/addie-tool-surface-budget.json` pins a + reviewed profile-contract hash over every declared tool profile — it hashes + the whole profile set, including each profile's wire-schema digest, so a + one-word description edit invalidates it — and re-blessing that hash is its own + review decision rather than something to fold into a containment commit. The + runtime refusal is the authoritative guard in the meantime: an execution + attempt refuses without effect. Follow-up: update both strings, regenerate with + `npm run build:addie-tools`, and re-bless the contract hash under its own + review. +- **Admin UI copy still offers merge.** The merge controls in + `admin-data-cleanup.html`, `admin-domain-health.html` and + `admin-account-detail.html` surface the unavailable message correctly (each + throws on a non-OK response and renders `message`), but the surrounding copy + still promises a merge. Same known follow-up as the deletion modal below. +- **Not in scope here:** member merge and member migration, domain reassignment, + and every read-only inspection surface. User and identity merge + (`server/src/db/user-merge-db.ts`) is separately contained under + `identity_mutation_disabled`. None of them deletes an organization. ## Operator handling while deletion is unavailable @@ -182,6 +282,8 @@ flag, migration alone, best-effort rollback, or an in-memory lock is insufficien | Independent qualification | Mounted cookie/JWT/API-key, selector, linked A/B and exact role tests; real disposable PostgreSQL failures/races; provider timeout/late completion tests; restart/replay tests; mandatory audit tests; independent review bound to the exact candidate tree; required repository checks. Controlled doubles alone do not prove live provider semantics. | No lifecycle journal, migration, deletion worker, compensation or reconciliation -implementation is introduced by this containment. Historic authority repair and -other #6827 surfaces remain separate work. Enabling deletion requires a new -reviewed change after the complete lifecycle contract is accepted. +implementation is introduced by this containment, and none is introduced by the +merge follow-up. Historic authority repair and other #6827 surfaces remain +separate work. Enabling organization deletion — whether directly or through +merge — requires a new reviewed change after the complete lifecycle contract +above is accepted. diff --git a/scripts/incidents/2026-05-cleanup-duplicate-prospect-stubs.ts b/scripts/incidents/2026-05-cleanup-duplicate-prospect-stubs.ts index 2e9501ed11a..7dcbadd5ec0 100644 --- a/scripts/incidents/2026-05-cleanup-duplicate-prospect-stubs.ts +++ b/scripts/incidents/2026-05-cleanup-duplicate-prospect-stubs.ts @@ -1,6 +1,7 @@ /** - * Cleanup duplicate prospect-stub org rows surfaced by the - * `unique-org-per-email-domain` invariant. + * Report duplicate prospect-stub org rows surfaced by the + * `unique-org-per-email-domain` invariant. Reporting only — see the #6827 note + * below; this script used to delete them and no longer does. * * Background — May 2026 audit: the April-20 prospect import re-ran without * dedup, creating a second `prospect`/0-member row for ~60 companies that @@ -8,34 +9,58 @@ * (no stripe_customer_id, no agreement, no announcement, no subscription) * but clutters admin search and breaks domain-keyed automation. * - * Strategy: - * 1. Run the invariant via the admin API to get the duplicate list. - * 2. For each pair, ONLY delete the duplicate when it's *fully empty*: + * #6827: THIS SCRIPT NO LONGER DELETES ANYTHING. It is read-only analysis. + * + * It previously deleted duplicate organization rows with direct SQL, reasoning + * from the absence of an admin delete endpoint that a script was the sanctioned + * route. That is exactly backwards. Organization deletion and organization merge + * are contained under #6827 because removing an organization locally while its + * WorkOS organization survives is the split provider/local state the containment + * exists to prevent — and a script bypasses the containment, the audit trail and + * the reconciliation contract all at once. An operator bypass is still a bypass. + * + * What it does now: + * 1. Runs the invariant via the admin API to get the duplicate list. + * 2. Classifies each pair and reports which duplicates are fully empty stubs * - 0 organization_memberships * - stripe_customer_id IS NULL * - subscription_status IS NULL or 'none' - * i.e., a true stub. Anything richer (members, Stripe link) needs - * a manual merge call, not a delete — surface it and skip. - * 3. Delete via direct SQL; there's no admin DELETE-org endpoint by - * design (org deletion is destructive enough that it doesn't have - * a normal admin surface). + * versus which carry members or Stripe state. + * 3. Stops. It opens no database connection and issues no writes. `--execute` + * hard-refuses before any connection is made. * - * Defaults to --dry-run. Pass --execute to actually run the deletes. - * - * Usage: + * Usage (read-only; no DATABASE_URL needed or used): * ADMIN_BASE_URL=https://agenticadvertising.org \ * ADMIN_API_KEY=... \ - * DATABASE_URL=postgres://... \ * npx tsx scripts/incidents/2026-05-cleanup-duplicate-prospect-stubs.ts * - * # ...then with --execute once the dry-run output looks sane. + * Hand the report to the engineering owner of #6827. Do not delete or edit the + * rows by hand. */ -import { Client } from 'pg'; +// #6827 containment, before anything else runs: refuse the destructive mode +// outright. This precedes every network call and every database connection — +// the script no longer even imports a database client — so there is no path +// from this flag to a mutation. +if (process.argv.includes('--execute')) { + console.error( + 'organization_deletion_unavailable: --execute is refused.\n' + + '\n' + + 'This script used to delete duplicate organization rows with direct SQL.\n' + + 'Organization deletion and organization merge are contained under #6827\n' + + 'because deleting an organization locally while its WorkOS organization\n' + + 'survives is the split provider/local state the containment prevents.\n' + + 'A script bypass is still a bypass, so the destructive path was removed.\n' + + '\n' + + 'Run without --execute for the read-only report, then escalate to the\n' + + 'engineering owner of #6827. Do not delete or edit the rows by hand.\n' + + 'See docs/contributing/organization-deletion-containment.md.', + ); + process.exit(1); +} const ADMIN_BASE_URL = process.env.ADMIN_BASE_URL?.replace(/\/+$/, ''); const ADMIN_API_KEY = process.env.ADMIN_API_KEY; -const DATABASE_URL = process.env.DATABASE_URL; if (!ADMIN_BASE_URL) { console.error('ADMIN_BASE_URL not set (e.g. https://agenticadvertising.org)'); @@ -45,13 +70,6 @@ if (!ADMIN_API_KEY) { console.error('ADMIN_API_KEY not set'); process.exit(1); } -if (!DATABASE_URL) { - console.error('DATABASE_URL not set — required for direct SQL deletes'); - process.exit(1); -} - -const execute = process.argv.includes('--execute'); -const dryRun = !execute; interface Violation { invariant: string; @@ -93,7 +111,7 @@ async function adminGet(path: string): Promise { } async function main(): Promise { - console.log(`Mode: ${dryRun ? 'DRY RUN' : 'EXECUTE'}`); + console.log('Mode: READ-ONLY REPORT (#6827 containment; no execute mode exists)'); console.log(`Admin: ${ADMIN_BASE_URL}\n`); console.log('Running unique-org-per-email-domain invariant...'); @@ -107,13 +125,15 @@ async function main(): Promise { console.log(`Found ${violations.length} duplicate org row(s).\n`); if (violations.length === 0) return; - // Partition into deletable (truly empty) vs. needs-manual-merge. - const deletable: Violation[] = []; - const needsMerge: Violation[] = []; + // Partition into truly-empty stubs vs. duplicates carrying state. Neither + // bucket is actionable here: organization merge and deletion are both + // contained (#6827), so both are reported and escalated, not resolved. + const emptyStubs: Violation[] = []; + const nonEmptyDuplicates: Violation[] = []; for (const v of violations) { const dup = v.details?.duplicate; if (!dup) { - needsMerge.push(v); + nonEmptyDuplicates.push(v); continue; } const isEmpty = @@ -121,18 +141,18 @@ async function main(): Promise { !dup.has_stripe_customer && !dup.has_active_subscription; if (isEmpty) { - deletable.push(v); + emptyStubs.push(v); } else { - needsMerge.push(v); + nonEmptyDuplicates.push(v); } } - console.log(` Truly empty stubs (safe to delete): ${deletable.length}`); - console.log(` Non-empty duplicates (need manual merge): ${needsMerge.length}\n`); + console.log(` Truly empty stubs (report only): ${emptyStubs.length}`); + console.log(` Non-empty duplicates (escalate, do not consolidate): ${nonEmptyDuplicates.length}\n`); - if (needsMerge.length > 0) { - console.log('=== Needs manual merge (NOT touched by this script) ==='); - for (const v of needsMerge) { + if (nonEmptyDuplicates.length > 0) { + console.log('=== Non-empty duplicates (escalate to the #6827 owner) ==='); + for (const v of nonEmptyDuplicates) { const d = v.details?.duplicate; const k = v.details?.keeper; console.log( @@ -144,101 +164,28 @@ async function main(): Promise { console.log(); } - if (deletable.length === 0) { - console.log('No empty stubs to delete.'); + if (emptyStubs.length === 0) { + console.log('No empty stubs found.'); return; } - console.log('=== Deletable empty stubs ==='); - for (const v of deletable) { + console.log('=== Empty stubs (reportable only — consolidation is contained) ==='); + for (const v of emptyStubs) { const d = v.details?.duplicate; const k = v.details?.keeper; console.log( - ` DELETE ${d?.workos_organization_id} "${d?.name}" ` + + ` ${d?.workos_organization_id} "${d?.name}" ` + `(domain=${v.details?.email_domain}, keeper=${k?.workos_organization_id})`, ); } console.log(); - if (dryRun) { - console.log('Dry run — no deletes issued. Pass --execute to delete.'); - return; - } - - // Direct SQL delete. Uses a transaction with safety re-checks: even - // though the invariant said the row is empty NOW, between the read and - // the delete a member could have joined or Stripe could have linked. - // Re-verify inside the txn before deleting so a mid-flight write isn't - // silently dropped. - const client = new Client({ connectionString: DATABASE_URL }); - await client.connect(); - let deleted = 0; - let skipped = 0; - let failed = 0; - try { - for (const v of deletable) { - const orgId = v.details?.duplicate?.workos_organization_id; - if (!orgId) { - skipped++; - continue; - } - try { - await client.query('BEGIN'); - const verifyResult = await client.query<{ - mc: number; - stripe_customer_id: string | null; - subscription_status: string | null; - }>( - `SELECT - (SELECT COUNT(*)::int FROM organization_memberships om - WHERE om.workos_organization_id = o.workos_organization_id) AS mc, - o.stripe_customer_id, o.subscription_status - FROM organizations o - WHERE o.workos_organization_id = $1 - FOR UPDATE`, - [orgId], - ); - const r = verifyResult.rows[0]; - if (!r) { - console.log(` ~ ${orgId}: no longer exists, skipping`); - await client.query('ROLLBACK'); - skipped++; - continue; - } - const stillEmpty = - r.mc === 0 && - r.stripe_customer_id === null && - (r.subscription_status === null || r.subscription_status === 'none'); - if (!stillEmpty) { - console.log( - ` ~ ${orgId}: not empty anymore (mc=${r.mc}, ` + - `stripe=${r.stripe_customer_id}, sub=${r.subscription_status}) — skipping`, - ); - await client.query('ROLLBACK'); - skipped++; - continue; - } - await client.query( - 'DELETE FROM organizations WHERE workos_organization_id = $1', - [orgId], - ); - await client.query('COMMIT'); - console.log(` ✓ ${orgId} deleted`); - deleted++; - } catch (err) { - await client.query('ROLLBACK').catch(() => {}); - console.log( - ` ✗ ${orgId} failed: ${err instanceof Error ? err.message : String(err)}`, - ); - failed++; - } - } - } finally { - await client.end(); - } - console.log( - `\nDeleted ${deleted}, skipped ${skipped}, failed ${failed}, total ${deletable.length}.`, + 'Read-only report only — no deletes are issued and no database connection\n' + + 'is opened. Organization deletion and organization merge are contained\n' + + 'under #6827 (organization_deletion_unavailable / organization_merge_unavailable).\n' + + 'Hand this list to the engineering owner of #6827; do not delete or edit the\n' + + 'rows by hand, and do not re-add a direct SQL path here.', ); } diff --git a/server/src/addie/config-version.ts b/server/src/addie/config-version.ts index 4cbb8f4fe8b..b6e7ee9efb2 100644 --- a/server/src/addie/config-version.ts +++ b/server/src/addie/config-version.ts @@ -30,7 +30,7 @@ import { loadRules, loadResponseStyle } from './rules/index.js'; * Format: YYYY.MM.N where N is incremented for multiple changes in a month * Example: 2025.01.1, 2025.01.2, 2025.02.1 */ -export const CODE_VERSION = '2026.09.59'; +export const CODE_VERSION = '2026.09.60'; // Types export interface ConfigVersion { diff --git a/server/src/addie/mcp/admin-tools.ts b/server/src/addie/mcp/admin-tools.ts index 88350210244..6a0ec89e95d 100644 --- a/server/src/addie/mcp/admin-tools.ts +++ b/server/src/addie/mcp/admin-tools.ts @@ -114,11 +114,11 @@ import { type MembershipInvite, } from "../../db/membership-invites-db.js"; import { sendMembershipInviteEmail } from "../../notifications/email.js"; +import { previewMerge } from "../../db/org-merge-db.js"; import { - mergeOrganizations, - previewMerge, - type StripeCustomerResolution, -} from "../../db/org-merge-db.js"; + ORGANIZATION_MERGE_UNAVAILABLE_ERROR, + ORGANIZATION_MERGE_UNAVAILABLE_MESSAGE, +} from "../../db/org-merge-containment.js"; import { getWorkos } from "../../auth/workos-client.js"; import { invalidateSlackAdminStatusCache, @@ -7194,14 +7194,12 @@ Use add_committee_leader to assign a leader.`; // Merge organizations handlers.set("merge_organizations", async (input) => { - const workos = getWorkos(); - const primaryOrgId = input.primary_org_id as string; const secondaryOrgId = input.secondary_org_id as string; const preview = input.preview !== false; // Default to preview mode for safety - const stripeCustomerResolution = input.stripe_customer_resolution as - | StripeCustomerResolution - | undefined; + // stripe_customer_resolution is still accepted by the tool schema but is + // only meaningful to merge execution, which is contained (#6827). Preview + // reports the conflict; nothing resolves it. if (!primaryOrgId || !secondaryOrgId) { return "❌ Both primary_org_id and secondary_org_id are required."; @@ -7213,7 +7211,11 @@ Use add_committee_leader to assign a leader.`; try { if (preview) { - // Preview mode - show what would be merged + // Preview mode - show what would be merged. + // #6827: the WorkOS client is acquired here, inside the read-only + // branch, and not at handler entry. The contained execution path must + // not so much as construct or initialize a provider client. + const workos = getWorkos(); const previewResult = await previewMerge(primaryOrgId, secondaryOrgId); // Also check WorkOS memberships @@ -7259,11 +7261,11 @@ Use add_committee_leader to assign a leader.`; if (workosCheckFailed) { response += `⚠️ Could not check WorkOS memberships\n`; } else if (workosUserCount > 0) { - response += `- ${workosUserCount} user(s) will be added to the primary org in WorkOS\n`; - response += `- Secondary org will be deleted from WorkOS\n`; + response += `- ${workosUserCount} user(s) would be added to the primary org in WorkOS\n`; + response += `- Secondary org would be deleted from WorkOS\n`; } else { response += `- No new users to migrate in WorkOS\n`; - response += `- Secondary org will be deleted from WorkOS\n`; + response += `- Secondary org would be deleted from WorkOS\n`; } // Stripe customer conflict section @@ -7296,227 +7298,44 @@ Use add_committee_leader to assign a leader.`; } response += `\n---\n`; - if (stripeConflict.requires_resolution) { - response += `_This is a preview. To execute the merge, call merge_organizations with preview=false and stripe_customer_resolution set._`; - } else { - response += `_This is a preview. To execute the merge, call merge_organizations again with preview=false._`; - } + // #6827: preview is read-only and stays available, but it must not + // instruct anyone to run the contained execution path. + response += `_This is a read-only preview. Merge execution is temporarily unavailable (\`${ORGANIZATION_MERGE_UNAVAILABLE_ERROR}\`, #6827), so calling with preview=false will refuse without moving data or deleting anything._`; return response; } else { - // Execute the merge - logger.info( + // #6827: merge EXECUTION is contained. Refuse before step 1's WorkOS + // membership reads, before the database transaction, before the + // provider membership writes and before the two provider organization + // deletes this handler used to perform. mergeOrganizations refuses + // again at the shared service boundary, so this early return is the + // honest message rather than the only guard. + logger.warn( { primaryOrgId, secondaryOrgId, - mergedBy: memberContext?.workos_user?.workos_user_id, + requestedBy: memberContext?.workos_user?.workos_user_id, }, - "Admin executing org merge via Addie", - ); - - // Step 1: Get users from secondary org in WorkOS before merge - let workosUsersToMigrate: string[] = []; - let workosErrors: string[] = []; - let secondaryRoles = new Map(); - - try { - // Get all memberships from the secondary org in WorkOS - const memberships = - await workos.userManagement.listOrganizationMemberships({ - organizationId: secondaryOrgId, - limit: 100, - }); - - // Warn if there are more than 100 members (pagination not implemented) - if (memberships.listMetadata?.after) { - workosErrors.push( - "Secondary org has more than 100 members - only first 100 will be migrated. Manual WorkOS cleanup may be needed.", - ); - } - - // Check which users are NOT already in the primary org - const primaryMemberships = - await workos.userManagement.listOrganizationMemberships({ - organizationId: primaryOrgId, - limit: 100, - }); - const primaryUserIds = new Set( - primaryMemberships.data.map((m) => m.userId), - ); - - const usersToMigrate = memberships.data.filter( - (m) => m.status === "active" && !primaryUserIds.has(m.userId), - ); - workosUsersToMigrate = usersToMigrate.map((m) => m.userId); - // Preserve roles from secondary org so owners/admins keep their role - secondaryRoles = new Map( - usersToMigrate.map((m) => [m.userId, m.role?.slug || "member"]), - ); - - logger.info( - { count: workosUsersToMigrate.length, secondaryOrgId }, - "Found WorkOS users to migrate", - ); - } catch (err) { - logger.warn( - { error: err, secondaryOrgId }, - "Failed to fetch WorkOS memberships (will continue with DB merge)", - ); - workosErrors.push( - "Could not fetch WorkOS memberships - manual WorkOS cleanup may be needed", - ); - } - - // Step 2: Execute the database merge - const mergedBy = - memberContext?.workos_user?.workos_user_id || "addie-admin"; - const result = await mergeOrganizations( - primaryOrgId, - secondaryOrgId, - mergedBy, - workos, - stripeCustomerResolution ? { stripeCustomerResolution } : undefined, - ); - - // Step 3: Add users to primary org in WorkOS - let workosAdded = 0; - let workosSkipped = 0; - - for (const userId of workosUsersToMigrate) { - try { - const roleSlug = secondaryRoles.get(userId) || "member"; - await workos.userManagement.createOrganizationMembership({ - userId, - organizationId: primaryOrgId, - roleSlug, - }); - workosAdded++; - logger.debug( - { userId, primaryOrgId }, - "Added user to primary org in WorkOS", - ); - } catch (err: any) { - // User might already be in org (race condition) or other error - if (err?.code === "organization_membership_already_exists") { - workosSkipped++; - } else { - logger.warn( - { error: err, userId }, - "Failed to add user to primary org in WorkOS", - ); - workosErrors.push(`Failed to add user ${userId} to WorkOS org`); - } - } - } - - // Step 4: Delete the secondary org from WorkOS - let workosOrgDeleted = false; - try { - await workos.organizations.deleteOrganization(secondaryOrgId); - workosOrgDeleted = true; - logger.info({ secondaryOrgId }, "Deleted secondary org from WorkOS"); - } catch (err) { - logger.warn( - { error: err, secondaryOrgId }, - "Failed to delete secondary org from WorkOS", - ); - workosErrors.push( - `Failed to delete secondary org from WorkOS (ID: ${secondaryOrgId}) - manual cleanup required`, - ); - } - - let response = `## Merge Complete ✅\n\n`; - response += `Successfully merged **${result.secondary_org_id}** into **${result.primary_org_id}**.\n\n`; - - response += `### Data Moved\n`; - const totalMoved = result.tables_merged.reduce( - (sum, t) => sum + t.rows_moved, - 0, + "Refused contained organization merge execution via Addie", ); - const totalSkipped = result.tables_merged.reduce( - (sum, t) => sum + (t.rows_skipped_duplicate ?? 0), - 0, - ); - - for (const table of result.tables_merged) { - const skipped = table.rows_skipped_duplicate ?? 0; - if (table.rows_moved > 0 || skipped > 0) { - response += `- **${table.table_name}**: ${table.rows_moved} moved`; - if (skipped > 0) { - response += ` (${skipped} skipped as duplicates)`; - } - response += `\n`; - } - } - - response += `\n**Total:** ${totalMoved} rows moved, ${totalSkipped} duplicates skipped\n`; - - // WorkOS sync results - if ( - workosUsersToMigrate.length > 0 || - workosOrgDeleted || - workosErrors.length > 0 - ) { - response += `\n### WorkOS Sync\n`; - if (workosAdded > 0) { - response += `- ✅ Added ${workosAdded} user(s) to primary org in WorkOS\n`; - } - if (workosSkipped > 0) { - response += `- ⏭️ Skipped ${workosSkipped} user(s) (already in primary org)\n`; - } - if (workosOrgDeleted) { - response += `- 🗑️ Deleted secondary org from WorkOS\n`; - } - } - - // Stripe customer action - if ( - result.stripe_customer_action && - result.stripe_customer_action !== "none" - ) { - response += `\n### Stripe\n`; - switch (result.stripe_customer_action) { - case "kept_primary": - response += `- ✅ Kept primary org's Stripe customer\n`; - break; - case "moved_from_secondary": - response += `- 🔄 Moved Stripe customer from secondary to primary org\n`; - break; - case "conflict_unresolved": - response += `- ⚠️ Both Stripe customers were unlinked - manual linking required\n`; - break; - } - } - - if (result.prospect_notes_merged) { - response += `\n📝 Prospect notes were merged.\n`; - } - - if (result.enrichment_data_preserved) { - response += `📊 Enrichment data was preserved from the secondary organization.\n`; - } - - // Combine all warnings - const allWarnings = [...result.warnings, ...workosErrors]; - if (allWarnings.length > 0) { - response += `\n### Warnings\n`; - for (const warning of allWarnings) { - response += `⚠️ ${warning}\n`; - } - } - response += `\nThe secondary organization has been deleted.`; + let response = `❌ ${ORGANIZATION_MERGE_UNAVAILABLE_MESSAGE} (\`${ORGANIZATION_MERGE_UNAVAILABLE_ERROR}\`, #6827)\n\n`; + response += `Merging deletes the secondary organization, and that lifecycle is unavailable until it has a durable operation journal and an exact reconciliation contract (#6827). No data was moved, no organization was deleted and nothing was left half-applied.\n\n`; + response += `Preview still works: call \`merge_organizations\` with \`preview=true\` to see what a merge would move.\n\n`; + response += `Do not substitute a manual database edit, a direct WorkOS deletion or any other workaround — each reproduces the split provider/local state this containment exists to prevent. Escalate duplicate-organization cleanup to the engineering owner of #6827 instead.`; return response; } } catch (error) { + // Only the read-only preview branch can throw now; the contained + // execution branch returns its refusal without calling anything. logger.error( { error, primaryOrgId, secondaryOrgId }, - "Error merging organizations", + "Error previewing organization merge", ); const errorMessage = error instanceof Error ? error.message : "Unknown error"; - return `❌ Failed to merge organizations: ${errorMessage}`; + return `❌ Failed to preview the organization merge: ${errorMessage}`; } }); diff --git a/server/src/audit/integrity/invariants/unique-org-per-email-domain.ts b/server/src/audit/integrity/invariants/unique-org-per-email-domain.ts index bb9bfd30a8e..42cb0748c47 100644 --- a/server/src/audit/integrity/invariants/unique-org-per-email-domain.ts +++ b/server/src/audit/integrity/invariants/unique-org-per-email-domain.ts @@ -168,14 +168,22 @@ export const uniqueOrgPerEmailDomainInvariant: Invariant = { }, }, remediation_hint: - // The merge endpoint (POST /api/admin/accounts/:source/merge-into/:target) - // moves memberships and stripe state to `keeper`, then deletes the - // empty row. Use that for stub-vs-real cases. For stub-vs-stub, - // direct DELETE is fine after confirming both rows are empty. - `If duplicate has 0 members AND no Stripe customer, DELETE FROM organizations ` + - `WHERE workos_organization_id = '${dup.workos_organization_id}'. Otherwise use ` + - `POST /api/admin/accounts/${dup.workos_organization_id}/merge-into/${keeper.workos_organization_id} ` + - `(if implemented) to consolidate.`, + // #6827: this hint used to emit a ready-to-paste raw SQL delete + // against the organizations table, and pointed at a merge + // endpoint that does not exist. Both organization deletion + // and organization merge are contained precisely because removing + // an organization locally while its WorkOS organization survives + // is the split state #6827 tracks. Do not hand an operator the + // statement the containment exists to prevent: report the pair and + // route it to the owning engineer instead. + `Duplicate email_domain. Inspect the pair read-only with ` + + `GET /api/admin/cleanup/preview-merge?primary=${keeper.workos_organization_id}` + + `&secondary=${dup.workos_organization_id}. Consolidation is not available: ` + + `organization deletion and organization merge are contained under #6827 ` + + `(organization_deletion_unavailable / organization_merge_unavailable). ` + + `Do not delete the row directly or edit it in psql — that reproduces the ` + + `split provider/local state the containment prevents. Escalate to the ` + + `engineering owner of #6827 with this violation attached.`, }); } } diff --git a/server/src/db/org-merge-containment.ts b/server/src/db/org-merge-containment.ts new file mode 100644 index 00000000000..c7c8efbc5ea --- /dev/null +++ b/server/src/db/org-merge-containment.ts @@ -0,0 +1,57 @@ +/** + * Organization merge containment (#6827) + * + * Organization merge deletes the secondary organization. It removes the local + * organization row inside its transaction, commits, and only then asks WorkOS + * to delete the provider organization, downgrading a provider failure to a + * warning while still reporting success. The Addie path additionally attempts + * the provider delete twice with WorkOS membership writes interleaved between + * the local commit and the second attempt. + * + * That is the same split provider/local state the organization deletion + * containment closed, so merge execution is unavailable on the same terms and + * for the same reason. See docs/contributing/organization-deletion-containment.md + * for the lifecycle contract a future implementation must satisfy. + * + * This module is the single source of truth for the refusal so the HTTP route, + * the Addie tool and the shared service boundary cannot drift apart. It holds + * no state, reads nothing and performs no I/O. + * + * It is deliberately separate from org-merge-db.ts rather than folded into it: + * tests/addie/admin-tools.test.ts replaces org-merge-db.js with an explicit + * factory mock exposing only mergeOrganizations and previewMerge, so importing + * these constants into admin-tools.ts from there would fail that suite with + * "No export is defined on the mock". + */ + +/** Stable machine-readable code, mirroring `organization_deletion_unavailable`. */ +export const ORGANIZATION_MERGE_UNAVAILABLE_ERROR = 'organization_merge_unavailable'; + +/** Stable human-readable message, mirroring the deletion containment wording. */ +export const ORGANIZATION_MERGE_UNAVAILABLE_MESSAGE = + 'Organization merge is temporarily unavailable.'; + +/** + * Thrown by the shared merge service boundary. Callers that cannot return an + * HTTP body (the Addie tool, scripts, any future caller) get a typed error + * carrying the same stable code as the route response. + */ +export class OrganizationMergeUnavailableError extends Error { + readonly code = ORGANIZATION_MERGE_UNAVAILABLE_ERROR; + + constructor() { + super(ORGANIZATION_MERGE_UNAVAILABLE_MESSAGE); + this.name = 'OrganizationMergeUnavailableError'; + } +} + +/** + * The body the contained HTTP surface returns. The Addie tool returns markdown + * carrying the same code and message, not this object. + */ +export function organizationMergeUnavailableBody() { + return { + error: ORGANIZATION_MERGE_UNAVAILABLE_ERROR, + message: ORGANIZATION_MERGE_UNAVAILABLE_MESSAGE, + } as const; +} diff --git a/server/src/db/org-merge-db.ts b/server/src/db/org-merge-db.ts index 58f99a366e8..18b9716de5b 100644 --- a/server/src/db/org-merge-db.ts +++ b/server/src/db/org-merge-db.ts @@ -1,19 +1,21 @@ /** * Organization Merge Database Operations * - * Provides functionality to merge two organizations, moving all related data - * from a secondary organization to a primary organization. + * Read-only merge inspection. Merging two organizations — moving all related + * data from a secondary organization to a primary one, for duplicate cleanup or + * company consolidation — is not currently performed here. * - * This is used when: - * - Duplicate organizations are discovered - * - Companies acquire/merge with each other - * - Organizations need to be consolidated + * #6827: `mergeOrganizations` is CONTAINED and executes nothing. Merge deletes + * the secondary organization, and that lifecycle has no durable journal or + * reconciliation contract, so the function refuses at the shared service + * boundary. `previewMerge` below is read-only (SELECT/COUNT only) and remains + * available. */ import { getPool } from './client.js'; import { createLogger } from '../logger.js'; -import { encrypt, decrypt } from './encryption.js'; -import { WorkOS } from '@workos-inc/node'; +import { OrganizationMergeUnavailableError } from './org-merge-containment.js'; +import type { WorkOS } from '@workos-inc/node'; const logger = createLogger('org-merge-db'); @@ -38,951 +40,53 @@ export interface MergeSummary { export type StripeCustomerResolution = 'keep_primary' | 'use_secondary' | 'keep_both_unlinked'; /** - * Merge two organizations, moving all data from secondary to primary + * CONTAINED (#6827). Always throws `OrganizationMergeUnavailableError` and + * never merges, never deletes an organization and never calls a provider. * - * @param primaryOrgId - The organization to keep (merge into) - * @param secondaryOrgId - The organization to remove (merge from) - * @param mergedBy - WorkOS user ID of person initiating the merge - * @param workos - WorkOS client instance for deleting the secondary org - * @param options.stripeCustomerResolution - How to handle stripe_customer_id conflict - * @returns Summary of the merge operation + * Existing callers keep type-checking and the re-enable change does not have to + * rediscover the contract. `_workos` and `_options` are accepted and ignored, + * and `_workos` is optional so a caller is never pushed into constructing a + * provider client for a call that always throws. Expect the re-enable change to + * make it required again — widening it here is a property of the containment, + * not of the eventual merge contract. + * + * @param primaryOrgId - The organization that would be kept (logged only) + * @param secondaryOrgId - The organization that would be removed (logged only) + * @param mergedBy - WorkOS user ID of the person initiating the merge (logged only) + * @throws OrganizationMergeUnavailableError always; the `never` return type + * states that no MergeSummary is ever produced. */ export async function mergeOrganizations( primaryOrgId: string, secondaryOrgId: string, mergedBy: string, - workos: WorkOS, - options?: { + _workos?: WorkOS, + _options?: { stripeCustomerResolution?: StripeCustomerResolution; } -): Promise { - const pool = getPool(); - const client = await pool.connect(); - - const summary: MergeSummary = { - primary_org_id: primaryOrgId, - secondary_org_id: secondaryOrgId, - merged_by: mergedBy, - merged_at: new Date(), - tables_merged: [], - prospect_notes_merged: false, - enrichment_data_preserved: false, - stripe_customer_action: null, - workos_org_deleted: false, - warnings: [], - }; - - try { - // Start transaction - await client.query('BEGIN'); - - logger.info( - { primaryOrgId, secondaryOrgId, mergedBy }, - 'Starting organization merge' - ); - - // Validate both organizations exist and fetch all needed fields. - // FOR UPDATE prevents concurrent Stripe webhooks or other merges from - // modifying these rows (especially stripe_customer_id) mid-transaction. - const orgsResult = await client.query( - `SELECT workos_organization_id, name, is_personal, prospect_notes, - stripe_customer_id, - enrichment_at, enrichment_industry, enrichment_sub_industry, - enrichment_employee_count, enrichment_revenue, enrichment_revenue_range, - enrichment_country, enrichment_city, enrichment_description - FROM organizations - WHERE workos_organization_id = ANY($1) - FOR UPDATE`, - [[primaryOrgId, secondaryOrgId]] - ); - - if (orgsResult.rows.length !== 2) { - throw new Error('Both organizations must exist'); - } - - const primaryOrg = orgsResult.rows.find(r => r.workos_organization_id === primaryOrgId); - const secondaryOrg = orgsResult.rows.find(r => r.workos_organization_id === secondaryOrgId); - - if (!primaryOrg || !secondaryOrg) { - throw new Error('Could not load organization details'); - } - - // Block merging a company INTO a personal workspace (would lose company identity) - // But allow: personal INTO company, personal INTO personal - if (primaryOrg.is_personal && !secondaryOrg.is_personal) { - throw new Error('Cannot merge a company organization into a personal workspace. The company would lose its identity. Instead, merge the personal workspace into the company.'); - } - - logger.info( - { primary: primaryOrg.name, secondary: secondaryOrg.name }, - 'Merging organizations' - ); - - // ===================================================== - // 0. Handle Stripe customer ID - // ===================================================== - const primaryHasStripe = !!primaryOrg.stripe_customer_id; - const secondaryHasStripe = !!secondaryOrg.stripe_customer_id; - - if (primaryHasStripe && secondaryHasStripe) { - // Both orgs have Stripe customers - require explicit resolution - const resolution = options?.stripeCustomerResolution; - if (!resolution) { - throw new Error( - `Both organizations have Stripe customers (primary: ${primaryOrg.stripe_customer_id}, secondary: ${secondaryOrg.stripe_customer_id}). ` + - `Provide stripeCustomerResolution option: 'keep_primary', 'use_secondary', or 'keep_both_unlinked'` - ); - } - - if (resolution === 'keep_primary') { - // Keep primary's customer, unlink secondary's (will be deleted with the org) - summary.stripe_customer_action = 'kept_primary'; - summary.warnings.push( - `Secondary org's Stripe customer ${secondaryOrg.stripe_customer_id} will be orphaned - may need manual cleanup in Stripe` - ); - logger.info( - { primaryCustomer: primaryOrg.stripe_customer_id, orphanedCustomer: secondaryOrg.stripe_customer_id }, - 'Keeping primary Stripe customer, secondary customer will be orphaned' - ); - } else if (resolution === 'use_secondary') { - // Replace primary's customer with secondary's - // Clear secondary first to avoid unique constraint violation - await client.query( - `UPDATE organizations SET stripe_customer_id = NULL WHERE workos_organization_id = $1`, - [secondaryOrgId] - ); - await client.query( - `UPDATE organizations SET stripe_customer_id = $1 WHERE workos_organization_id = $2`, - [secondaryOrg.stripe_customer_id, primaryOrgId] - ); - summary.stripe_customer_action = 'moved_from_secondary'; - summary.warnings.push( - `Primary org's previous Stripe customer ${primaryOrg.stripe_customer_id} was replaced - may need manual cleanup in Stripe` - ); - logger.info( - { newCustomer: secondaryOrg.stripe_customer_id, orphanedCustomer: primaryOrg.stripe_customer_id }, - 'Replaced primary Stripe customer with secondary' - ); - } else if (resolution === 'keep_both_unlinked') { - // Unlink primary's customer, don't transfer secondary's - await client.query( - `UPDATE organizations SET stripe_customer_id = NULL WHERE workos_organization_id = $1`, - [primaryOrgId] - ); - summary.stripe_customer_action = 'conflict_unresolved'; - summary.warnings.push( - `Both Stripe customers (${primaryOrg.stripe_customer_id}, ${secondaryOrg.stripe_customer_id}) were unlinked - manual linking required` - ); - logger.info( - { orphanedCustomers: [primaryOrg.stripe_customer_id, secondaryOrg.stripe_customer_id] }, - 'Both Stripe customers unlinked, manual resolution required' - ); - } - } else if (secondaryHasStripe && !primaryHasStripe) { - // Only secondary has Stripe - move it to primary - // Clear secondary first to avoid unique constraint violation - await client.query( - `UPDATE organizations SET stripe_customer_id = NULL WHERE workos_organization_id = $1`, - [secondaryOrgId] - ); - await client.query( - `UPDATE organizations SET stripe_customer_id = $1 WHERE workos_organization_id = $2`, - [secondaryOrg.stripe_customer_id, primaryOrgId] - ); - summary.stripe_customer_action = 'moved_from_secondary'; - logger.info( - { stripeCustomerId: secondaryOrg.stripe_customer_id }, - 'Moved Stripe customer from secondary to primary org' - ); - } else if (primaryHasStripe) { - // Only primary has Stripe - keep it - summary.stripe_customer_action = 'kept_primary'; - } else { - // Neither has Stripe - summary.stripe_customer_action = 'none'; - } - - // ===================================================== - // 1. Merge organization_memberships - // ===================================================== - const membershipsResult = await client.query( - `INSERT INTO organization_memberships ( - workos_user_id, workos_organization_id, workos_membership_id, - email, first_name, last_name, created_at, updated_at, synced_at - ) - SELECT - workos_user_id, $1, workos_membership_id, - email, first_name, last_name, created_at, updated_at, synced_at - FROM organization_memberships - WHERE workos_organization_id = $2 - ON CONFLICT (workos_user_id, workos_organization_id) DO NOTHING - RETURNING workos_user_id`, - [primaryOrgId, secondaryOrgId] - ); - - const skippedMemberships = await client.query( - `SELECT COUNT(*) as count FROM organization_memberships - WHERE workos_organization_id = $1`, - [secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'organization_memberships', - rows_moved: membershipsResult.rows.length, - rows_skipped_duplicate: parseInt(skippedMemberships.rows[0].count, 10) - membershipsResult.rows.length, - }); - - // Delete secondary org memberships - await client.query( - `DELETE FROM organization_memberships WHERE workos_organization_id = $1`, - [secondaryOrgId] - ); - - // Repoint users.primary_organization_id from secondary to primary. Must - // happen BEFORE the secondary org row delete (step 24) — once the FK - // ON DELETE SET NULL fires, the pointer is gone and we lose the merge - // intent. Without this, every user whose primary was the secondary org - // ends up resolving back to a different membership (or no org at all) - // after the merge, even though we just moved their membership to the - // primary above. - const repointResult = await client.query( - `UPDATE users - SET primary_organization_id = $1, updated_at = NOW() - WHERE primary_organization_id = $2 - RETURNING workos_user_id`, - [primaryOrgId, secondaryOrgId] - ); - summary.tables_merged.push({ - table_name: 'users.primary_organization_id', - rows_moved: repointResult.rows.length, - }); - - // ===================================================== - // 2. Merge organization_domains - // ===================================================== - // Count domains before transfer for summary - const totalDomains = await client.query( - `SELECT COUNT(*) as count FROM organization_domains - WHERE workos_organization_id = $1`, - [secondaryOrgId] - ); - - // Transfer domains by updating the organization_id directly - // The UNIQUE(domain) constraint ensures each domain belongs to only one org, - // so we just update the org_id rather than insert/delete - const domainsResult = await client.query( - `UPDATE organization_domains - SET workos_organization_id = $1, - is_primary = false, - updated_at = NOW() - WHERE workos_organization_id = $2 - RETURNING domain`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'organization_domains', - rows_moved: domainsResult.rows.length, - rows_skipped_duplicate: parseInt(totalDomains.rows[0].count, 10) - domainsResult.rows.length, - }); - - // ===================================================== - // 3. Merge organization_join_requests - // ===================================================== - const joinRequestsResult = await client.query( - `UPDATE organization_join_requests - SET workos_organization_id = $1, updated_at = NOW() - WHERE workos_organization_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'organization_join_requests', - rows_moved: joinRequestsResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 4. Merge working_group_memberships - // ===================================================== - const wgMembershipsResult = await client.query( - `INSERT INTO working_group_memberships ( - working_group_id, workos_user_id, user_email, user_name, user_org_name, - workos_organization_id, status, added_by_user_id, joined_at, updated_at - ) - SELECT - working_group_id, workos_user_id, user_email, user_name, user_org_name, - $1, status, added_by_user_id, joined_at, updated_at - FROM working_group_memberships - WHERE workos_organization_id = $2 - ON CONFLICT (working_group_id, workos_user_id) DO NOTHING - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - const totalWgMemberships = await client.query( - `SELECT COUNT(*) as count FROM working_group_memberships - WHERE workos_organization_id = $1`, - [secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'working_group_memberships', - rows_moved: wgMembershipsResult.rows.length, - rows_skipped_duplicate: parseInt(totalWgMemberships.rows[0].count, 10) - wgMembershipsResult.rows.length, - }); - - // Delete secondary org WG memberships - await client.query( - `DELETE FROM working_group_memberships WHERE workos_organization_id = $1`, - [secondaryOrgId] - ); - - // ===================================================== - // 5. Merge member_profiles (if exists) - // ===================================================== - const primaryProfile = await client.query( - `SELECT id FROM member_profiles WHERE workos_organization_id = $1`, - [primaryOrgId] - ); - - if (primaryProfile.rows.length === 0) { - // Primary has no profile, move secondary's if it exists - const profileResult = await client.query( - `UPDATE member_profiles - SET workos_organization_id = $1, updated_at = NOW() - WHERE workos_organization_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'member_profiles', - rows_moved: profileResult.rows.length, - rows_skipped_duplicate: 0, - }); - } else { - // Primary has profile, delete secondary's - const secondaryProfile = await client.query( - `DELETE FROM member_profiles WHERE workos_organization_id = $1 RETURNING id`, - [secondaryOrgId] - ); - - if (secondaryProfile.rows.length > 0) { - summary.warnings.push('Secondary organization had a member profile which was deleted (primary profile kept)'); - } - - summary.tables_merged.push({ - table_name: 'member_profiles', - rows_moved: 0, - rows_skipped_duplicate: secondaryProfile.rows.length, - }); - } - - // ===================================================== - // 6. Merge org_activities - // ===================================================== - const activitiesResult = await client.query( - `UPDATE org_activities - SET organization_id = $1, updated_at = NOW() - WHERE organization_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'org_activities', - rows_moved: activitiesResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 7. Merge org_stakeholders - // ===================================================== - const stakeholdersResult = await client.query( - `INSERT INTO org_stakeholders ( - organization_id, user_id, user_name, user_email, role, notes, - created_at, updated_at - ) - SELECT - $1, user_id, user_name, user_email, role, notes, created_at, updated_at - FROM org_stakeholders - WHERE organization_id = $2 - ON CONFLICT (organization_id, user_id) DO NOTHING - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - const totalStakeholders = await client.query( - `SELECT COUNT(*) as count FROM org_stakeholders WHERE organization_id = $1`, - [secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'org_stakeholders', - rows_moved: stakeholdersResult.rows.length, - rows_skipped_duplicate: parseInt(totalStakeholders.rows[0].count, 10) - stakeholdersResult.rows.length, - }); - - // Delete secondary org stakeholders - await client.query( - `DELETE FROM org_stakeholders WHERE organization_id = $1`, - [secondaryOrgId] - ); - - // ===================================================== - // 8. Merge slack_activity_daily - // ===================================================== - const slackActivityResult = await client.query( - `UPDATE slack_activity_daily - SET organization_id = $1, updated_at = NOW() - WHERE organization_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'slack_activity_daily', - rows_moved: slackActivityResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 9. Merge slack_user_mappings (update org context) - // Note: This doesn't have a direct FK, but we update for consistency - // ===================================================== - // No direct FK to organizations in slack_user_mappings, skip - - // ===================================================== - // 10. Merge email_events - // ===================================================== - const emailEventsResult = await client.query( - `UPDATE email_events - SET workos_organization_id = $1, updated_at = NOW() - WHERE workos_organization_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'email_events', - rows_moved: emailEventsResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 11. Merge email_contacts - // ===================================================== - const emailContactsResult = await client.query( - `UPDATE email_contacts - SET organization_id = $1, updated_at = NOW() - WHERE organization_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'email_contacts', - rows_moved: emailContactsResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 12. Merge addie_threads (update org context in JSON) - // Note: addie_threads doesn't have a direct FK but may reference org in context - // ===================================================== - const addieThreadsResult = await client.query( - `UPDATE addie_threads - SET context = jsonb_set( - COALESCE(context, '{}'::jsonb), - '{organization_id}', - to_jsonb($1::text) - ), - updated_at = NOW() - WHERE context->>'organization_id' = $2 - RETURNING thread_id`, - [primaryOrgId, secondaryOrgId] - ); - - if (addieThreadsResult.rows.length > 0) { - summary.tables_merged.push({ - table_name: 'addie_threads', - rows_moved: addieThreadsResult.rows.length, - rows_skipped_duplicate: 0, - }); - } - - // ===================================================== - // 13. Merge action_items - // ===================================================== - const actionItemsResult = await client.query( - `UPDATE action_items - SET org_id = $1, updated_at = NOW() - WHERE org_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'action_items', - rows_moved: actionItemsResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 14. Merge revenue_events (payment history) - // ===================================================== - const revenueEventsResult = await client.query( - `UPDATE revenue_events - SET workos_organization_id = $1 - WHERE workos_organization_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'revenue_events', - rows_moved: revenueEventsResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 15. Merge subscription_line_items - // ===================================================== - const lineItemsResult = await client.query( - `UPDATE subscription_line_items - SET workos_organization_id = $1, updated_at = NOW() - WHERE workos_organization_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'subscription_line_items', - rows_moved: lineItemsResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 16. Merge event_registrations - // ===================================================== - const eventRegsResult = await client.query( - `UPDATE event_registrations - SET organization_id = $1, updated_at = NOW() - WHERE organization_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'event_registrations', - rows_moved: eventRegsResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 17. Merge event_sponsorships - // ===================================================== - const sponsorshipsResult = await client.query( - `UPDATE event_sponsorships - SET organization_id = $1, updated_at = NOW() - WHERE organization_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'event_sponsorships', - rows_moved: sponsorshipsResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 18. Merge user_agreement_acceptances - // ===================================================== - const agreementsResult = await client.query( - `UPDATE user_agreement_acceptances - SET workos_organization_id = $1 - WHERE workos_organization_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'user_agreement_acceptances', - rows_moved: agreementsResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 19. Merge org_admin_group_dms (Slack admin channels) - // Note: ON DELETE CASCADE handles this, but we track it explicitly - // ===================================================== - const adminDmsResult = await client.query( - `DELETE FROM org_admin_group_dms WHERE workos_organization_id = $1 RETURNING id`, - [secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'org_admin_group_dms', - rows_moved: 0, - rows_skipped_duplicate: adminDmsResult.rows.length, // Deleted, not moved - }); - - if (adminDmsResult.rows.length > 0) { - summary.warnings.push('Secondary org had a Slack admin DM channel which was removed (primary channel kept if exists)'); - } - - // ===================================================== - // 20. Merge registry_audit_log entries - // ===================================================== - const auditLogResult = await client.query( - `UPDATE registry_audit_log - SET workos_organization_id = $1 - WHERE workos_organization_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'registry_audit_log', - rows_moved: auditLogResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 20a. Merge agent_contexts - // UNIQUE(organization_id, agent_url): keep primary's row on - // conflict so its agent_test_history (ON DELETE CASCADE) survives; - // secondary's history is removed when its row is deleted. - // - // Encrypted token columns are AES-256-GCM with a PBKDF2 key derived - // from organization_id (see ./encryption.ts). Reparenting requires - // decrypting with secondary salt and re-encrypting with primary salt, - // otherwise GCM auth-tag verification fails on every subsequent read - // and saved tokens become permanently unusable. - // ===================================================== - const ENCRYPTED_AGENT_CONTEXT_FIELDS = [ - ['auth_token_encrypted', 'auth_token_iv'], - ['oauth_access_token_encrypted', 'oauth_access_token_iv'], - ['oauth_refresh_token_encrypted', 'oauth_refresh_token_iv'], - ['oauth_client_secret_encrypted', 'oauth_client_secret_iv'], - ['oauth_cc_client_secret_encrypted', 'oauth_cc_client_secret_iv'], - ] as const; - - const moveableRows = await client.query( - `SELECT id, - auth_token_encrypted, auth_token_iv, - oauth_access_token_encrypted, oauth_access_token_iv, - oauth_refresh_token_encrypted, oauth_refresh_token_iv, - oauth_client_secret_encrypted, oauth_client_secret_iv, - oauth_cc_client_secret_encrypted, oauth_cc_client_secret_iv - FROM agent_contexts - WHERE organization_id = $1 - AND NOT EXISTS ( - SELECT 1 FROM agent_contexts p - WHERE p.organization_id = $2 AND p.agent_url = agent_contexts.agent_url - )`, - [secondaryOrgId, primaryOrgId] - ); - - let agentContextsReencryptedFields = 0; - for (const row of moveableRows.rows) { - const setClauses: string[] = ['organization_id = $1', 'updated_at = NOW()']; - const values: (string | null)[] = [primaryOrgId]; - let nextIdx = 2; - - for (const [encCol, ivCol] of ENCRYPTED_AGENT_CONTEXT_FIELDS) { - const ciphertext = row[encCol]; - const iv = row[ivCol]; - if (ciphertext && iv) { - const plaintext = decrypt(ciphertext, iv, secondaryOrgId); - const reencrypted = encrypt(plaintext, primaryOrgId); - setClauses.push(`${encCol} = $${nextIdx++}`); - values.push(reencrypted.encrypted); - setClauses.push(`${ivCol} = $${nextIdx++}`); - values.push(reencrypted.iv); - agentContextsReencryptedFields++; - } - } - - values.push(row.id); - await client.query( - `UPDATE agent_contexts SET ${setClauses.join(', ')} WHERE id = $${nextIdx}`, - values - ); - } - - const agentContextsDeleted = await client.query( - `DELETE FROM agent_contexts WHERE organization_id = $1 RETURNING id`, - [secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'agent_contexts', - rows_moved: moveableRows.rows.length, - rows_skipped_duplicate: agentContextsDeleted.rows.length, - }); - - if (agentContextsReencryptedFields > 0) { - logger.info( - { fields: agentContextsReencryptedFields, rows: moveableRows.rows.length }, - 'Re-encrypted agent_contexts token fields under primary org salt' - ); - } - - if (agentContextsDeleted.rows.length > 0) { - summary.warnings.push( - `${agentContextsDeleted.rows.length} duplicate agent_contexts from secondary org were deleted (primary already had the same agent_url) — their test history was removed` - ); - } - - // ===================================================== - // 20b. Merge person_relationships.prospect_org_id - // No unique constraint on prospect_org_id — straight reparent. - // ===================================================== - const personRelResult = await client.query( - `UPDATE person_relationships - SET prospect_org_id = $1, updated_at = NOW() - WHERE prospect_org_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'person_relationships', - rows_moved: personRelResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 20c. Merge certification_goals - // UNIQUE(workos_organization_id, credential_id): keep primary on conflict. - // ===================================================== - const certGoalsMoved = await client.query( - `UPDATE certification_goals - SET workos_organization_id = $1, updated_at = NOW() - WHERE workos_organization_id = $2 - AND NOT EXISTS ( - SELECT 1 FROM certification_goals p - WHERE p.workos_organization_id = $1 - AND p.credential_id = certification_goals.credential_id - ) - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - const certGoalsDeleted = await client.query( - `DELETE FROM certification_goals WHERE workos_organization_id = $1 RETURNING id`, - [secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'certification_goals', - rows_moved: certGoalsMoved.rows.length, - rows_skipped_duplicate: certGoalsDeleted.rows.length, - }); - - // ===================================================== - // 20d. Merge certification_expectations - // UNIQUE(workos_organization_id, email): keep primary on conflict. - // ===================================================== - const certExpMoved = await client.query( - `UPDATE certification_expectations - SET workos_organization_id = $1 - WHERE workos_organization_id = $2 - AND NOT EXISTS ( - SELECT 1 FROM certification_expectations p - WHERE p.workos_organization_id = $1 - AND p.email = certification_expectations.email - ) - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - const certExpDeleted = await client.query( - `DELETE FROM certification_expectations WHERE workos_organization_id = $1 RETURNING id`, - [secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'certification_expectations', - rows_moved: certExpMoved.rows.length, - rows_skipped_duplicate: certExpDeleted.rows.length, - }); - - // ===================================================== - // 20e. Merge user_goal_history.prospect_org_id - // No unique constraint on this column — straight reparent. - // ===================================================== - const goalHistoryResult = await client.query( - `UPDATE user_goal_history - SET prospect_org_id = $1 - WHERE prospect_org_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'user_goal_history', - rows_moved: goalHistoryResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 20f. Merge brands (ownership pointer) - // brands.workos_organization_id is FK→organizations ON DELETE SET NULL - // (migration 474). Without an explicit reparent, the secondary's brand - // rows would survive the DELETE FROM organizations at step 24 but get - // their owner pointer nulled, losing the brand entirely. UNIQUE is on - // `domain` alone, not (org, domain) — a domain can only ever belong - // to one org at a time — so a straight reparent UPDATE never conflicts. - // ===================================================== - const brandsResult = await client.query( - `UPDATE brands - SET workos_organization_id = $1, updated_at = NOW() - WHERE workos_organization_id = $2 - RETURNING id`, - [primaryOrgId, secondaryOrgId] - ); - - summary.tables_merged.push({ - table_name: 'brands', - rows_moved: brandsResult.rows.length, - rows_skipped_duplicate: 0, - }); - - // ===================================================== - // 21. Merge prospect notes - // ===================================================== - if (secondaryOrg.prospect_notes && secondaryOrg.prospect_notes.trim()) { - const timestamp = new Date().toISOString().split('T')[0]; - const mergeNote = `[${timestamp}] MERGED FROM: ${secondaryOrg.name}\n${secondaryOrg.prospect_notes}`; - - await client.query( - `UPDATE organizations - SET prospect_notes = CASE - WHEN prospect_notes IS NULL OR prospect_notes = '' THEN $2 - ELSE prospect_notes || E'\n\n' || $2 - END, - updated_at = NOW() - WHERE workos_organization_id = $1`, - [primaryOrgId, mergeNote] - ); - - summary.prospect_notes_merged = true; - } - - // ===================================================== - // 22. Preserve enrichment data if primary doesn't have it - // ===================================================== - if (secondaryOrg.enrichment_at && !primaryOrg.enrichment_at) { - await client.query( - `UPDATE organizations - SET enrichment_at = $2, - enrichment_industry = $3, - enrichment_sub_industry = $4, - enrichment_employee_count = $5, - enrichment_revenue = $6, - enrichment_revenue_range = $7, - enrichment_country = $8, - enrichment_city = $9, - enrichment_description = $10, - updated_at = NOW() - WHERE workos_organization_id = $1`, - [ - primaryOrgId, - secondaryOrg.enrichment_at, - secondaryOrg.enrichment_industry, - secondaryOrg.enrichment_sub_industry || null, - secondaryOrg.enrichment_employee_count || null, - secondaryOrg.enrichment_revenue || null, - secondaryOrg.enrichment_revenue_range || null, - secondaryOrg.enrichment_country || null, - secondaryOrg.enrichment_city || null, - secondaryOrg.enrichment_description || null, - ] - ); - - summary.enrichment_data_preserved = true; - summary.warnings.push('Enrichment data from secondary organization was copied to primary'); - } - - // ===================================================== - // 23. Log the merge action in audit log - // ===================================================== - await client.query( - `INSERT INTO registry_audit_log ( - workos_organization_id, workos_user_id, action, resource_type, resource_id, details - ) VALUES ($1, $2, 'merge_organization', 'organization', $3, $4)`, - [ - primaryOrgId, - mergedBy, - secondaryOrgId, - JSON.stringify({ - secondary_org_name: secondaryOrg.name, - primary_org_name: primaryOrg.name, - merged_at: summary.merged_at, - tables_affected: summary.tables_merged.map(t => t.table_name), - }), - ] - ); - - // ===================================================== - // 24. Delete the secondary organization from local DB - // ===================================================== - await client.query( - `DELETE FROM organizations WHERE workos_organization_id = $1`, - [secondaryOrgId] - ); - - // Commit transaction - await client.query('COMMIT'); - - // ===================================================== - // 25. Delete the secondary organization from WorkOS - // ===================================================== - // This is done after commit so local changes persist even if WorkOS fails - try { - await workos.organizations.deleteOrganization(secondaryOrgId); - summary.workos_org_deleted = true; - logger.info({ secondaryOrgId }, 'Deleted secondary organization from WorkOS'); - } catch (workosError) { - // Log but don't fail - local merge succeeded - logger.error( - { error: workosError, secondaryOrgId }, - 'Failed to delete secondary organization from WorkOS - manual cleanup may be required' - ); - summary.warnings.push( - 'Failed to delete secondary organization from WorkOS. The organization may need to be manually deleted in WorkOS Dashboard.' - ); - } - - logger.info( - { - primaryOrgId, - secondaryOrgId, - totalMoved: summary.tables_merged.reduce((sum, t) => sum + t.rows_moved, 0), - workosDeleted: summary.workos_org_deleted, - }, - 'Organization merge completed successfully' - ); - - return summary; - } catch (error) { - // Rollback on error - await client.query('ROLLBACK'); - - logger.error( - { error, primaryOrgId, secondaryOrgId }, - 'Organization merge failed, rolled back' - ); - - throw error; - } finally { - client.release(); - } +): Promise { + // #6827 containment, defense in depth. This is the shared boundary every + // merge caller passes through, so the refusal lives here and not only at the + // contained route and the contained Addie tool: an overlooked or new caller + // cannot reach the old sequence. It runs before getPool(), before + // pool.connect() and before BEGIN, so there is no row lock, local write, + // organization deletion, WorkOS membership write, provider organization + // deletion, Stripe operation, audit row, cache invalidation or notification. + // + // The previous implementation is deliberately removed rather than left + // unreachable behind this throw. That sequence IS the hazard — local delete, + // commit, then a best-effort provider delete whose failure became a warning — + // so re-enabling merge must be a new reviewed implementation satisfying the + // lifecycle contract in docs/contributing/organization-deletion-containment.md, + // not the deletion of a guard. Nothing is journalled and nothing is partially + // applied because nothing is attempted. The removed body is readable in git + // history at commit 97652f89 and earlier, as reference only — never as a + // restore target. + logger.warn( + { primaryOrgId, secondaryOrgId, mergedBy }, + 'Refused contained organization merge at the shared service boundary' + ); + throw new OrganizationMergeUnavailableError(); } /** diff --git a/server/src/routes/admin/cleanup.ts b/server/src/routes/admin/cleanup.ts index 18a23156481..3e805d7a514 100644 --- a/server/src/routes/admin/cleanup.ts +++ b/server/src/routes/admin/cleanup.ts @@ -11,9 +11,9 @@ import { isCleanupConfigured, } from "../../services/prospect-cleanup.js"; import { isLushaConfigured } from "../../services/lusha.js"; -import { mergeOrganizations, previewMerge, StripeCustomerResolution } from "../../db/org-merge-db.js"; +import { previewMerge } from "../../db/org-merge-db.js"; +import { organizationMergeUnavailableBody } from "../../db/org-merge-containment.js"; import { getPool } from "../../db/client.js"; -import { getWorkos } from "../../auth/workos-client.js"; const logger = createLogger("admin-cleanup"); @@ -267,96 +267,31 @@ export function setupCleanupRoutes(apiRouter: Router): void { } ); - // POST /api/admin/cleanup/merge - Execute organization merge - apiRouter.post("/cleanup/merge", ...requireGlobalAdmin, async (req, res) => { - // Pull org ids out before the try-block so the 500 catch path can - // log them. Without this, an error thrown inside the try (where the - // destructure used to live) leaves the catch with no idea which - // pair was being merged — admins running curl get a bare "Internal - // server error" with no diagnostic context. - const { primary_org_id, secondary_org_id, stripe_customer_resolution } = req.body; - - if (!primary_org_id || !secondary_org_id) { - return res.status(400).json({ - error: "Missing parameters", - message: "Both 'primary_org_id' and 'secondary_org_id' are required", - }); - } - - try { - - // Validate stripe_customer_resolution if provided - const validResolutions: StripeCustomerResolution[] = ['keep_primary', 'use_secondary', 'keep_both_unlinked']; - if (stripe_customer_resolution && !validResolutions.includes(stripe_customer_resolution)) { - return res.status(400).json({ - error: "Invalid stripe_customer_resolution", - message: `Must be one of: ${validResolutions.join(', ')}`, - }); - } - - const user = (req as any).user; - const userId = user?.id || "unknown"; - - logger.info( - { primary_org_id, secondary_org_id, userId, stripe_customer_resolution }, - "Executing organization merge" - ); - - const result = await mergeOrganizations( - primary_org_id, - secondary_org_id, - userId, - getWorkos(), - stripe_customer_resolution ? { stripeCustomerResolution: stripe_customer_resolution } : undefined - ); - - logger.info( - { - primary_org_id, - secondary_org_id, - tables_merged: result.tables_merged.length, - stripe_customer_action: result.stripe_customer_action, - }, - "Organization merge completed" - ); - - res.json(result); - } catch (error) { - logger.error( - { - err: error, - errMessage: error instanceof Error ? error.message : String(error), - errName: error instanceof Error ? error.name : undefined, - errStack: error instanceof Error ? error.stack : undefined, - errCause: error instanceof Error ? (error as Error & { cause?: unknown }).cause : undefined, - primary_org_id, - secondary_org_id, - }, - "Error executing merge", - ); - - // Return 400 for validation errors (e.g., personal workspace merge attempts, Stripe conflicts) - if (error instanceof Error && ( - error.message.startsWith('Cannot merge personal workspaces') || - error.message.startsWith('Both organizations have Stripe customers') - )) { - return res.status(400).json({ - error: error.message.startsWith('Cannot merge personal workspaces') - ? 'Cannot merge personal workspaces' - : 'Organization merge conflict', - }); - } - - // 500 path: surface the underlying message in `details` so admins - // running merges via curl don't have to dig through Fly logs to - // see whether the merge rolled back or which step failed. (May - // 2026: Media.net-2 cleanup returned a bare "Internal server - // error" with no log entry visible from the caller side, hiding - // the real cause for ~30min.) - res.status(500).json({ - error: "Internal server error", - details: error instanceof Error ? error.message : String(error), - }); - } + // POST /api/admin/cleanup/merge - CONTAINED (#6827) + // + // Merge deletes the secondary organization: local row removed inside the + // transaction, commit, then a best-effort provider delete whose failure was + // downgraded to a warning. Same split provider/local state the deletion + // containment closed, so execution is unavailable on the same terms. + // + // Administrative authority is deliberately UNCHANGED — requireGlobalAdmin + // still authenticates and authorizes, unlike the contained deletion routes, + // because nothing here needs to run before authentication. The refusal is + // returned before the body is validated and before any merge-specific + // database transaction, WorkOS membership write, provider organization + // deletion, Stripe operation, audit row, cache invalidation or notification. + // mergeOrganizations refuses again at the shared service boundary. + // + // GET /cleanup/preview-merge above is untouched: previewMerge is read-only. + apiRouter.post("/cleanup/merge", ...requireGlobalAdmin, (req, res) => { + // This is the only contained merge surface that has an authenticated, + // authorized actor in hand, so it is the one that can record who is still + // trying. That is the demand signal for re-enabling, and the signal worth + // having if an operator then reaches for a manual substitute. + logger.warn( + { userId: (req as { user?: { id?: string } }).user?.id }, + "Refused contained organization merge request", + ); + res.status(503).json(organizationMergeUnavailableBody()); }); } diff --git a/server/tests/integration/org-merge-agent-contexts.test.ts b/server/tests/integration/org-merge-agent-contexts.test.ts index 9ce354cf72a..4a19b088bd4 100644 --- a/server/tests/integration/org-merge-agent-contexts.test.ts +++ b/server/tests/integration/org-merge-agent-contexts.test.ts @@ -1,7 +1,8 @@ import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'; -import { initializeDatabase, closeDatabase, getPool } from '../../src/db/client.js'; +import { initializeDatabase, closeDatabase } from '../../src/db/client.js'; import { runMigrations } from '../../src/db/migrate.js'; import { mergeOrganizations } from '../../src/db/org-merge-db.js'; +import { OrganizationMergeUnavailableError } from '../../src/db/org-merge-containment.js'; import { encrypt, decrypt } from '../../src/db/encryption.js'; import type { Pool } from 'pg'; import type { WorkOS } from '@workos-inc/node'; @@ -10,17 +11,41 @@ const PRIMARY_ORG = 'org_merge_ac_primary'; const SECONDARY_ORG = 'org_merge_ac_secondary'; const MERGED_BY = 'user_merge_ac_admin'; -// Stub WorkOS client — mergeOrganizations only calls organizations.deleteOrganization -// after the local commit, so the stub just needs to no-op. +/** + * agent_contexts credentials under the contained organization merge (#6827). + * + * These fixtures previously proved the credential re-encryption + * mergeOrganizations performed: tokens sealed under the secondary org's salt + * were re-sealed under the primary org's salt as the rows moved, and duplicate + * agent_url rows were dropped instead of violating the unique key. Merge + * execution is now contained, so the same fixtures prove the stronger property + * instead — the contained service refuses, the rows stay on the secondary org + * and no stored credential is re-encrypted, moved or dropped. Restore the + * re-encryption assertions together with a reviewed merge lifecycle. + */ +// Records rather than no-ops: the contained service must never reach it. +const deleteCalls: string[] = []; const workosStub = { organizations: { - deleteOrganization: async (_id: string) => {}, + deleteOrganization: async (id: string) => { deleteCalls.push(id); }, }, } as unknown as WorkOS; -describe('mergeOrganizations — agent_contexts re-encryption', () => { +describe('contained mergeOrganizations — agent_contexts are left sealed in place', () => { let pool: Pool; + async function expectMergeRefused() { + deleteCalls.length = 0; + await expect(mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub)) + .rejects.toThrow(OrganizationMergeUnavailableError); + expect(deleteCalls).toEqual([]); + const secondary = await pool.query<{ count: string }>( + 'SELECT COUNT(*)::text AS count FROM organizations WHERE workos_organization_id = $1', + [SECONDARY_ORG], + ); + expect(secondary.rows[0]?.count).toBe('1'); + } + beforeAll(async () => { pool = initializeDatabase({ connectionString: process.env.DATABASE_URL || 'postgresql://adcp:localdev@localhost:5432/adcp_test', @@ -48,7 +73,7 @@ describe('mergeOrganizations — agent_contexts re-encryption', () => { await pool.query(`DELETE FROM organizations WHERE workos_organization_id IN ($1, $2)`, [PRIMARY_ORG, SECONDARY_ORG]); } - it('re-encrypts auth tokens under the primary org salt so decrypt keeps working', async () => { + it('leaves an auth token sealed under the secondary org salt, on the secondary org', async () => { const TOKEN = 'sk-test-bearer-token-12345'; const sealed = encrypt(TOKEN, SECONDARY_ORG); @@ -58,24 +83,26 @@ describe('mergeOrganizations — agent_contexts re-encryption', () => { [SECONDARY_ORG, sealed.encrypted, sealed.iv] ); - await mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub); + await expectMergeRefused(); - const moved = await pool.query( - `SELECT auth_token_encrypted, auth_token_iv FROM agent_contexts WHERE organization_id = $1`, + // Nothing landed on the primary org. + const atPrimary = await pool.query( + `SELECT 1 FROM agent_contexts WHERE organization_id = $1`, [PRIMARY_ORG] ); - expect(moved.rows).toHaveLength(1); - - // Old salt no longer works (proves we re-encrypted, not just moved bytes). - expect(() => decrypt(moved.rows[0].auth_token_encrypted, moved.rows[0].auth_token_iv, SECONDARY_ORG)) - .toThrow(); + expect(atPrimary.rows).toHaveLength(0); - // New salt round-trips to the original plaintext. - const recovered = decrypt(moved.rows[0].auth_token_encrypted, moved.rows[0].auth_token_iv, PRIMARY_ORG); - expect(recovered).toBe(TOKEN); + const stayed = await pool.query( + `SELECT auth_token_encrypted, auth_token_iv FROM agent_contexts WHERE organization_id = $1`, + [SECONDARY_ORG] + ); + expect(stayed.rows).toHaveLength(1); + // Still sealed under the secondary salt: no re-encryption was attempted. + expect(decrypt(stayed.rows[0].auth_token_encrypted, stayed.rows[0].auth_token_iv, SECONDARY_ORG)).toBe(TOKEN); + expect(() => decrypt(stayed.rows[0].auth_token_encrypted, stayed.rows[0].auth_token_iv, PRIMARY_ORG)).toThrow(); }); - it('re-encrypts every populated OAuth token field, leaves NULLs alone', async () => { + it('leaves every populated OAuth token field sealed under the secondary salt', async () => { const ACCESS = 'access-abc'; const REFRESH = 'refresh-def'; const access = encrypt(ACCESS, SECONDARY_ORG); @@ -90,25 +117,26 @@ describe('mergeOrganizations — agent_contexts re-encryption', () => { [SECONDARY_ORG, access.encrypted, access.iv, refresh.encrypted, refresh.iv] ); - await mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub); + await expectMergeRefused(); - const moved = await pool.query( + const stayed = await pool.query( `SELECT oauth_access_token_encrypted, oauth_access_token_iv, oauth_refresh_token_encrypted, oauth_refresh_token_iv, oauth_client_secret_encrypted, oauth_client_secret_iv FROM agent_contexts WHERE organization_id = $1`, - [PRIMARY_ORG] + [SECONDARY_ORG] ); - expect(moved.rows).toHaveLength(1); - const row = moved.rows[0]; + expect(stayed.rows).toHaveLength(1); + const row = stayed.rows[0]; - expect(decrypt(row.oauth_access_token_encrypted, row.oauth_access_token_iv, PRIMARY_ORG)).toBe(ACCESS); - expect(decrypt(row.oauth_refresh_token_encrypted, row.oauth_refresh_token_iv, PRIMARY_ORG)).toBe(REFRESH); + expect(decrypt(row.oauth_access_token_encrypted, row.oauth_access_token_iv, SECONDARY_ORG)).toBe(ACCESS); + expect(decrypt(row.oauth_refresh_token_encrypted, row.oauth_refresh_token_iv, SECONDARY_ORG)).toBe(REFRESH); + // NULL columns are still NULL: nothing was written at all. expect(row.oauth_client_secret_encrypted).toBeNull(); expect(row.oauth_client_secret_iv).toBeNull(); }); - it('drops duplicate agent_url rows from secondary instead of conflicting on the unique key', async () => { + it('keeps both duplicate agent_url rows, so no row is dropped as a merge duplicate', async () => { const URL = 'https://dup.example/mcp'; const primaryToken = encrypt('primary-token', PRIMARY_ORG); const secondaryToken = encrypt('secondary-token', SECONDARY_ORG); @@ -120,18 +148,19 @@ describe('mergeOrganizations — agent_contexts re-encryption', () => { [PRIMARY_ORG, SECONDARY_ORG, URL, primaryToken.encrypted, primaryToken.iv, secondaryToken.encrypted, secondaryToken.iv] ); - const summary = await mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub); + await expectMergeRefused(); const remaining = await pool.query( - `SELECT auth_token_encrypted, auth_token_iv FROM agent_contexts WHERE agent_url = $1`, + `SELECT organization_id, auth_token_encrypted, auth_token_iv + FROM agent_contexts WHERE agent_url = $1 ORDER BY organization_id`, [URL] ); - expect(remaining.rows).toHaveLength(1); - // Primary's row was kept (its token was never re-encrypted). - expect(decrypt(remaining.rows[0].auth_token_encrypted, remaining.rows[0].auth_token_iv, PRIMARY_ORG)) - .toBe('primary-token'); - - const acSummary = summary.tables_merged.find(t => t.table_name === 'agent_contexts'); - expect(acSummary?.rows_skipped_duplicate).toBe(1); + // Both rows survive on their own organizations; the duplicate-drop the + // merge used to perform is unreachable, so no credential is discarded. + expect(remaining.rows).toHaveLength(2); + const primaryRow = remaining.rows.find(r => r.organization_id === PRIMARY_ORG); + const secondaryRow = remaining.rows.find(r => r.organization_id === SECONDARY_ORG); + expect(decrypt(primaryRow.auth_token_encrypted, primaryRow.auth_token_iv, PRIMARY_ORG)).toBe('primary-token'); + expect(decrypt(secondaryRow.auth_token_encrypted, secondaryRow.auth_token_iv, SECONDARY_ORG)).toBe('secondary-token'); }); }); diff --git a/server/tests/integration/org-merge-brands-repoint.test.ts b/server/tests/integration/org-merge-brands-repoint.test.ts index ec4e0199f7d..02fab866c11 100644 --- a/server/tests/integration/org-merge-brands-repoint.test.ts +++ b/server/tests/integration/org-merge-brands-repoint.test.ts @@ -1,17 +1,22 @@ /** - * Integration test for the brands.workos_organization_id repoint added in - * mergeOrganizations. + * brands.workos_organization_id under the contained organization merge (#6827). * - * Without the repoint, the FK ON DELETE SET NULL on brands (migration 474) - * fires when the secondary org row is deleted at the end of the merge, - * leaving the secondary's brand rows owner-less. With the repoint inside - * the merge transaction, the brand rows land at the primary org first and - * the FK never fires for them. + * These fixtures previously proved the repoint mergeOrganizations performed: + * secondary-owned brand rows landed at the primary org inside the merge + * transaction, so the FK ON DELETE SET NULL (migration 474) never fired for + * them. Merge execution is now contained, so the same fixtures prove the + * stronger property instead — the contained service refuses and no brand row, + * owner pointer or organization row moves at all. Restore the repoint + * assertions together with a reviewed merge lifecycle. + * + * The direct-delete case below never used merge and is unchanged: it still + * covers the FK SET NULL plus orphan trigger on its own. */ import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'; -import { initializeDatabase, closeDatabase, getPool } from '../../src/db/client.js'; +import { initializeDatabase, closeDatabase } from '../../src/db/client.js'; import { runMigrations } from '../../src/db/migrate.js'; import { mergeOrganizations } from '../../src/db/org-merge-db.js'; +import { OrganizationMergeUnavailableError } from '../../src/db/org-merge-containment.js'; import type { Pool } from 'pg'; import type { WorkOS } from '@workos-inc/node'; @@ -25,13 +30,28 @@ const THIRD_DOMAIN = 'merge-brands-third.test'; const ORPHAN_DOMAIN = 'merge-brands-orphan.test'; const MERGED_BY = 'user_merge_brands_admin'; +// Records rather than no-ops: the contained service must never reach it. +const deleteCalls: string[] = []; const workosStub = { organizations: { - deleteOrganization: async (_id: string) => {}, + deleteOrganization: async (id: string) => { deleteCalls.push(id); }, }, } as unknown as WorkOS; -describe('mergeOrganizations — brands.workos_organization_id repoint', () => { +async function expectMergeRefused(pool: Pool) { + deleteCalls.length = 0; + await expect(mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub)) + .rejects.toThrow(OrganizationMergeUnavailableError); + expect(deleteCalls).toEqual([]); + // The secondary organization is never deleted, so the FK never fires. + const secondary = await pool.query<{ count: string }>( + 'SELECT COUNT(*)::text AS count FROM organizations WHERE workos_organization_id = $1', + [SECONDARY_ORG], + ); + expect(secondary.rows[0]?.count).toBe('1'); +} + +describe('contained mergeOrganizations — brands keep their owner', () => { let pool: Pool; beforeAll(async () => { @@ -76,50 +96,49 @@ describe('mergeOrganizations — brands.workos_organization_id repoint', () => { ); } - it('repoints brands owned by the secondary org to the primary org', async () => { + it('refuses and leaves every brand ownership exactly as it was', async () => { + // One case rather than four: after an unconditional refusal there is no + // code path that could treat a secondary-owned, primary-owned, third-owned + // or NULL-owned brand differently, so seeding all four together and + // asserting the whole set is both stronger and honest about what is tested. await seedBrand(SECONDARY_DOMAIN_A, SECONDARY_ORG); await seedBrand(SECONDARY_DOMAIN_B, SECONDARY_ORG); - - const summary = await mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub); - - const after = await pool.query<{ workos_organization_id: string | null }>( - 'SELECT workos_organization_id FROM brands WHERE domain = ANY($1) ORDER BY domain', - [[SECONDARY_DOMAIN_A, SECONDARY_DOMAIN_B]], - ); - expect(after.rows).toHaveLength(2); - expect(after.rows[0]?.workos_organization_id).toBe(PRIMARY_ORG); - expect(after.rows[1]?.workos_organization_id).toBe(PRIMARY_ORG); - - // Summary reports the repoint so admins running merges can audit it. - const brandsEntry = summary.tables_merged.find((t) => t.table_name === 'brands'); - expect(brandsEntry).toBeDefined(); - expect(brandsEntry!.rows_moved).toBe(2); - }); - - it('does not touch brands owned by the primary or a third org', async () => { await seedBrand(PRIMARY_DOMAIN, PRIMARY_ORG); await seedBrand(THIRD_DOMAIN, THIRD_ORG); - - await mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub); - - const after = await pool.query<{ domain: string; workos_organization_id: string | null }>( - 'SELECT domain, workos_organization_id FROM brands WHERE domain = ANY($1) ORDER BY domain', - [[PRIMARY_DOMAIN, THIRD_DOMAIN]], - ); - expect(after.rows.find((r) => r.domain === PRIMARY_DOMAIN)?.workos_organization_id).toBe(PRIMARY_ORG); - expect(after.rows.find((r) => r.domain === THIRD_DOMAIN)?.workos_organization_id).toBe(THIRD_ORG); - }); - - it('does not touch brands with null workos_organization_id', async () => { await seedBrand(ORPHAN_DOMAIN, null); - await mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub); + await expectMergeRefused(pool); - const after = await pool.query<{ workos_organization_id: string | null }>( - 'SELECT workos_organization_id FROM brands WHERE domain = $1', - [ORPHAN_DOMAIN], + const after = await pool.query<{ + domain: string; + workos_organization_id: string | null; + prior_owner_org_id: string | null; + manifest_orphaned: boolean; + }>( + `SELECT domain, workos_organization_id, prior_owner_org_id, manifest_orphaned + FROM brands WHERE domain = ANY($1) ORDER BY domain`, + [[PRIMARY_DOMAIN, SECONDARY_DOMAIN_A, SECONDARY_DOMAIN_B, THIRD_DOMAIN, ORPHAN_DOMAIN]], ); - expect(after.rows[0]?.workos_organization_id).toBeNull(); + // Compared as a set so the assertion does not encode a collation order. + const asSet = (pairs: [string, string | null][]) => + pairs.map(([domain, org]) => `${domain}|${org ?? 'NULL'}`).sort(); + expect( + asSet(after.rows.map(row => [row.domain, row.workos_organization_id])), + ).toEqual(asSet([ + [ORPHAN_DOMAIN, null], + [PRIMARY_DOMAIN, PRIMARY_ORG], + [SECONDARY_DOMAIN_A, SECONDARY_ORG], + [SECONDARY_DOMAIN_B, SECONDARY_ORG], + [THIRD_DOMAIN, THIRD_ORG], + ])); + + // The secondary org row survives, so neither the FK ON DELETE SET NULL nor + // the orphan trigger fires — the hazard the repoint existed to avoid cannot + // arise while merge is contained. + for (const row of after.rows) { + expect(row.prior_owner_org_id).toBeNull(); + expect(row.manifest_orphaned).toBe(false); + } }); it('direct org delete (no merge) triggers FK SET NULL + orphan trigger', async () => { @@ -160,31 +179,4 @@ describe('mergeOrganizations — brands.workos_organization_id repoint', () => { expect(after.rows[0]?.is_public).toBe(false); expect(after.rows[0]?.domain_verified).toBe(false); }); - - it('repoint runs before the secondary org is deleted, so the FK SET NULL never fires for these rows', async () => { - // Without the repoint, the FK ON DELETE SET NULL would fire when the - // secondary org row is deleted at the end of the merge, leaving these - // brands owner-less. The repoint inside the merge transaction takes - // precedence — assert the column lands at primary, not NULL. - await seedBrand(SECONDARY_DOMAIN_A, SECONDARY_ORG); - - await mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub); - - const after = await pool.query<{ workos_organization_id: string | null }>( - 'SELECT workos_organization_id FROM brands WHERE domain = $1', - [SECONDARY_DOMAIN_A], - ); - // Specifically NOT null — the FK fired for any column that DIDN'T get - // repointed, but we explicitly UPDATE'd this one before the DELETE. - expect(after.rows[0]?.workos_organization_id).not.toBeNull(); - expect(after.rows[0]?.workos_organization_id).toBe(PRIMARY_ORG); - - // Confirm secondary org row was actually deleted (proves the FK - // would have fired had the repoint not run first). - const secondaryCheck = await pool.query<{ count: string }>( - 'SELECT COUNT(*)::text AS count FROM organizations WHERE workos_organization_id = $1', - [SECONDARY_ORG], - ); - expect(secondaryCheck.rows[0]?.count).toBe('0'); - }); }); diff --git a/server/tests/integration/org-merge-primary-org-repoint.test.ts b/server/tests/integration/org-merge-primary-org-repoint.test.ts index cfa826cbc56..8723d5ad67a 100644 --- a/server/tests/integration/org-merge-primary-org-repoint.test.ts +++ b/server/tests/integration/org-merge-primary-org-repoint.test.ts @@ -1,21 +1,20 @@ /** - * Integration test for the users.primary_organization_id repoint added in - * mergeOrganizations. + * users.primary_organization_id under the contained organization merge (#6827). * - * Without the repoint, every user whose primary pointed at the secondary - * org gets a dangling pointer after the merge — the secondary org row gets - * deleted, the FK ON DELETE SET NULL nulls the column, and the resolver - * has to re-derive on next read. Worse, if the user wasn't in any other - * paying org, the resolver might pick a non-paying alternative even - * though the merge intent was "treat them as part of primary." - * - * The repoint runs inside the merge transaction BEFORE the secondary org - * row is deleted, so users land at the primary org directly. + * These fixtures previously proved the repoint mergeOrganizations performed: + * users whose primary pointed at the secondary org landed at the primary org + * inside the merge transaction, before the secondary row was deleted and the + * FK ON DELETE SET NULL could null the column. Merge execution is now + * contained, so the same fixtures prove the stronger property instead — the + * contained service refuses and no user pointer, membership or organization + * row moves at all. Restore the repoint assertions together with a reviewed + * merge lifecycle. */ import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'; -import { initializeDatabase, closeDatabase, getPool } from '../../src/db/client.js'; +import { initializeDatabase, closeDatabase } from '../../src/db/client.js'; import { runMigrations } from '../../src/db/migrate.js'; import { mergeOrganizations } from '../../src/db/org-merge-db.js'; +import { OrganizationMergeUnavailableError } from '../../src/db/org-merge-containment.js'; import type { Pool } from 'pg'; import type { WorkOS } from '@workos-inc/node'; @@ -27,13 +26,28 @@ const USER_PRIMARY_ELSEWHERE = 'user_merge_repoint_elsewhere'; const USER_NULL_PRIMARY = 'user_merge_repoint_null'; const MERGED_BY = 'user_merge_repoint_admin'; +// Records rather than no-ops: the contained service must never reach it. +const deleteCalls: string[] = []; const workosStub = { organizations: { - deleteOrganization: async (_id: string) => {}, + deleteOrganization: async (id: string) => { deleteCalls.push(id); }, }, } as unknown as WorkOS; -describe('mergeOrganizations — users.primary_organization_id repoint', () => { +async function expectMergeRefused(pool: Pool) { + deleteCalls.length = 0; + await expect(mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub)) + .rejects.toThrow(OrganizationMergeUnavailableError); + expect(deleteCalls).toEqual([]); + // The secondary organization is never deleted, so the FK never fires. + const secondary = await pool.query<{ count: string }>( + 'SELECT COUNT(*)::text AS count FROM organizations WHERE workos_organization_id = $1', + [SECONDARY_ORG], + ); + expect(secondary.rows[0]?.count).toBe('1'); +} + +describe('contained mergeOrganizations — users keep their primary organization', () => { let pool: Pool; beforeAll(async () => { @@ -60,18 +74,27 @@ describe('mergeOrganizations — users.primary_organization_id repoint', () => { }); async function cleanup() { + const actors = [USER_PRIMARY_AT_SECONDARY, USER_PRIMARY_ELSEWHERE, USER_NULL_PRIMARY, MERGED_BY]; + // The users insert trigger creates one identities row per seeded user, and + // identities do not cascade from users, so capture the ids before the user + // rows (and their cascading link rows) go away. Scoped to these exact ids so + // the cleanup cannot reach another suite's rows. + const identities = (await pool.query<{ identity_id: string }>( + `SELECT identity_id FROM identity_workos_users WHERE workos_user_id = ANY($1)`, + [actors], + )).rows.map((row) => row.identity_id); await pool.query( `DELETE FROM organization_memberships WHERE workos_organization_id IN ($1, $2, $3)`, [PRIMARY_ORG, SECONDARY_ORG, THIRD_ORG], ); - await pool.query( - `DELETE FROM users WHERE workos_user_id IN ($1, $2, $3, $4)`, - [USER_PRIMARY_AT_SECONDARY, USER_PRIMARY_ELSEWHERE, USER_NULL_PRIMARY, MERGED_BY], - ); + await pool.query(`DELETE FROM users WHERE workos_user_id = ANY($1)`, [actors]); await pool.query( `DELETE FROM organizations WHERE workos_organization_id IN ($1, $2, $3)`, [PRIMARY_ORG, SECONDARY_ORG, THIRD_ORG], ); + if (identities.length) { + await pool.query(`DELETE FROM identities WHERE id = ANY($1)`, [identities]); + } } async function seedUser(userId: string, primaryOrgId: string | null) { @@ -92,79 +115,51 @@ describe('mergeOrganizations — users.primary_organization_id repoint', () => { ); } - it('repoints users whose primary was the secondary org to the primary org', async () => { + it('refuses and leaves every primary_organization_id and membership as it was', async () => { + // One case rather than four: after an unconditional refusal there is no + // code path that could treat a secondary-pointing, third-pointing or NULL + // primary differently, so seed all three and assert the whole set. await seedUser(USER_PRIMARY_AT_SECONDARY, SECONDARY_ORG); await seedMembership(USER_PRIMARY_AT_SECONDARY, SECONDARY_ORG); - - const summary = await mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub); - - const after = await pool.query<{ primary_organization_id: string | null }>( - 'SELECT primary_organization_id FROM users WHERE workos_user_id = $1', - [USER_PRIMARY_AT_SECONDARY], - ); - expect(after.rows[0]?.primary_organization_id).toBe(PRIMARY_ORG); - - // Summary reports the repoint so admins running merges can audit it. - const repointEntry = summary.tables_merged.find( - (t) => t.table_name === 'users.primary_organization_id', - ); - expect(repointEntry).toBeDefined(); - expect(repointEntry!.rows_moved).toBe(1); - }); - - it('does not touch users whose primary points at a different org', async () => { await seedUser(USER_PRIMARY_ELSEWHERE, THIRD_ORG); await seedMembership(USER_PRIMARY_ELSEWHERE, THIRD_ORG); await seedMembership(USER_PRIMARY_ELSEWHERE, SECONDARY_ORG); - - await mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub); - - const after = await pool.query<{ primary_organization_id: string | null }>( - 'SELECT primary_organization_id FROM users WHERE workos_user_id = $1', - [USER_PRIMARY_ELSEWHERE], - ); - expect(after.rows[0]?.primary_organization_id).toBe(THIRD_ORG); - }); - - it('does not touch users with null primary_organization_id', async () => { await seedUser(USER_NULL_PRIMARY, null); await seedMembership(USER_NULL_PRIMARY, SECONDARY_ORG); - await mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub); + await expectMergeRefused(pool); - const after = await pool.query<{ primary_organization_id: string | null }>( - 'SELECT primary_organization_id FROM users WHERE workos_user_id = $1', - [USER_NULL_PRIMARY], + const users = await pool.query<{ workos_user_id: string; primary_organization_id: string | null }>( + `SELECT workos_user_id, primary_organization_id FROM users + WHERE workos_user_id = ANY($1) ORDER BY workos_user_id`, + [[USER_PRIMARY_AT_SECONDARY, USER_PRIMARY_ELSEWHERE, USER_NULL_PRIMARY]], ); - expect(after.rows[0]?.primary_organization_id).toBeNull(); - }); - - it('repoint runs before the secondary org is deleted, so the FK SET NULL never fires for these rows', async () => { - // Without the repoint, the FK ON DELETE SET NULL would fire when the - // secondary org row is deleted at the end of the merge, dropping the - // user's primary to NULL even though we just moved their membership - // to the primary above. The repoint inside the merge transaction - // takes precedence — assert the column lands at primary, not NULL. - await seedUser(USER_PRIMARY_AT_SECONDARY, SECONDARY_ORG); - await seedMembership(USER_PRIMARY_AT_SECONDARY, SECONDARY_ORG); - - await mergeOrganizations(PRIMARY_ORG, SECONDARY_ORG, MERGED_BY, workosStub); - - const after = await pool.query<{ primary_organization_id: string | null }>( - 'SELECT primary_organization_id FROM users WHERE workos_user_id = $1', - [USER_PRIMARY_AT_SECONDARY], - ); - // Specifically NOT null — the FK fired for any column that DIDN'T get - // repointed, but we explicitly UPDATE'd this one before the DELETE. - expect(after.rows[0]?.primary_organization_id).not.toBeNull(); - expect(after.rows[0]?.primary_organization_id).toBe(PRIMARY_ORG); + expect( + Object.fromEntries(users.rows.map(row => [row.workos_user_id, row.primary_organization_id])), + ).toEqual({ + [USER_PRIMARY_AT_SECONDARY]: SECONDARY_ORG, + [USER_PRIMARY_ELSEWHERE]: THIRD_ORG, + [USER_NULL_PRIMARY]: null, + }); - // Confirm secondary org row was actually deleted (proves the FK - // would have fired had the repoint not run first). - const secondaryCheck = await pool.query<{ count: string }>( - 'SELECT COUNT(*)::text AS count FROM organizations WHERE workos_organization_id = $1', - [SECONDARY_ORG], + // No membership was moved to the primary organization either. Compared as a + // set so the assertion does not encode a database collation order. + const memberships = await pool.query<{ workos_user_id: string; workos_organization_id: string }>( + `SELECT workos_user_id, workos_organization_id FROM organization_memberships + WHERE workos_organization_id = ANY($1)`, + [[PRIMARY_ORG, SECONDARY_ORG, THIRD_ORG]], ); - expect(secondaryCheck.rows[0]?.count).toBe('0'); + const asSet = (pairs: [string, string][]) => + pairs.map(pair => pair.join('|')).sort(); + expect( + asSet(memberships.rows.map(row => [row.workos_user_id, row.workos_organization_id])), + ).toEqual(asSet([ + [USER_NULL_PRIMARY, SECONDARY_ORG], + [USER_PRIMARY_AT_SECONDARY, SECONDARY_ORG], + [USER_PRIMARY_ELSEWHERE, SECONDARY_ORG], + [USER_PRIMARY_ELSEWHERE, THIRD_ORG], + ])); + // Nothing at all landed on the primary organization. + expect(memberships.rows.filter(row => row.workos_organization_id === PRIMARY_ORG)).toEqual([]); }); }); diff --git a/server/tests/integration/organization-merge-containment.test.ts b/server/tests/integration/organization-merge-containment.test.ts new file mode 100644 index 00000000000..5c5c30d8a80 --- /dev/null +++ b/server/tests/integration/organization-merge-containment.test.ts @@ -0,0 +1,379 @@ +import { beforeAll, afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import request from 'supertest'; +import { generateKeyPair, SignJWT } from 'jose'; +import type { Pool } from 'pg'; + +const state = vi.hoisted(() => { + process.env.ADMIN_API_KEY = 'merge-test-static-key'; + process.env.ADMIN_EMAILS = 'sam@merge.example.test'; + return { + users: new Map(), + sessions: new Map(), + calls: [] as string[], + platformAdmin: false, + }; +}); + +// Every provider mutation the merge sequence performed is recorded. None may fire. +vi.mock('@workos-inc/node', () => ({ WorkOS: class { + organizations = { + deleteOrganization: vi.fn(async (id: string) => { state.calls.push(`org_delete:${id}`); }), + }; + apiKeys = { createValidation: vi.fn(async () => { state.calls.push('api_key'); throw new Error('Unexpected API key validation'); }) }; + authorization = { listOrganizationRoles: vi.fn(async () => { state.calls.push('roles'); return { data: [] }; }) }; + userManagement = { + loadSealedSession: ({ sessionData }: any) => { + state.calls.push('session'); + return { + authenticate: async () => state.sessions.get(sessionData) ?? { authenticated: false }, + refresh: async () => ({ authenticated: false }), + }; + }, + createOrganizationMembership: vi.fn(async ({ organizationId }: any) => { state.calls.push(`membership_create:${organizationId}`); }), + listOrganizationMemberships: vi.fn(async ({ organizationId }: any) => { state.calls.push(`memberships:${organizationId}`); return { data: [] }; }), + getUser: vi.fn(async (id: string) => { state.calls.push(`user:${id}`); return state.users.get(id); }), + }; +} })); +vi.mock('../../src/addie/mcp/admin-tools.js', async (importOriginal) => ({ + ...(await importOriginal()), + isWebUserAAOAdmin: vi.fn(async () => state.platformAdmin), +})); +// Keep unrelated route graphs inert so this harness does not initialize Addie +// indexes or agent tenants. HTTPServer still supplies the real parser/cookie/ +// CSRF/admin-router ordering the contained route sits behind. +vi.mock('../../src/routes/addie-admin.js', async () => { + const express = (await import('express')).default; + return { createAddieAdminRouter: () => ({ pageRouter: express.Router(), apiRouter: express.Router() }) }; +}); +vi.mock('../../src/routes/addie-chat.js', async () => { + const express = (await import('express')).default; + return { createAddieChatRouter: () => ({ pageRouter: express.Router(), apiRouter: express.Router() }), isWebChatReady: () => false }; +}); +vi.mock('../../src/routes/slack.js', async () => { + const express = (await import('express')).default; + return { createSlackRouter: () => ({ aaobotRouter: express.Router(), addieRouter: express.Router() }) }; +}); +vi.mock('../../src/routes/registry-api.js', async () => { + const express = (await import('express')).default; + return { createRegistryApiRouters: () => ({ router: express.Router(), v1AgentsRouter: express.Router(), complianceRefreshQueue: null }) }; +}); +vi.mock('../../src/training-agent/index.js', async () => { + const express = (await import('express')).default; + return { createTrainingAgentRouter: () => express.Router() }; +}); +vi.mock('../../src/creative-agent/index.js', async () => { + const express = (await import('express')).default; + return { createCreativeAgentRouter: () => express.Router() }; +}); +vi.mock('../../src/addie/index.js', () => ({ + sendAccountLinkedMessage: vi.fn(), + invalidateMemberContextCache: vi.fn(), + isAddieBoltReady: () => false, +})); +vi.mock('../../src/addie/jobs/scheduler.js', () => ({ + jobScheduler: { startAll: vi.fn(), stop: vi.fn(), stopAll: vi.fn() }, +})); +vi.mock('../../src/addie/jobs/job-definitions.js', () => ({ + registerAllJobs: vi.fn(), + JOB_NAMES: { GEO_MONITOR: 'geo-monitor', GEO_SNAPSHOT: 'geo-snapshot', GEO_CONTENT_PLANNER: 'geo-content-planner' }, +})); +vi.mock('../../src/services/organization-membership-notifications.js', () => ({ notifyMembershipSeats: vi.fn(), notifyMembershipSeatRequest: vi.fn() })); +vi.mock('../../src/slack/org-group-dm.js', () => ({ notifyMemberSeatChanged: vi.fn() })); + +import { initializeDatabase, closeDatabase } from '../../src/db/client.js'; +import { runMigrations } from '../../src/db/migrate.js'; +import { __setJWKSForTesting } from '../../src/auth/workos-jwt.js'; +import { stopAuthTimers, invalidateBanCache } from '../../src/middleware/auth.js'; +import { mergeOrganizations } from '../../src/db/org-merge-db.js'; +import { + ORGANIZATION_MERGE_UNAVAILABLE_ERROR, + ORGANIZATION_MERGE_UNAVAILABLE_MESSAGE, + OrganizationMergeUnavailableError, +} from '../../src/db/org-merge-containment.js'; +import { createAdminToolHandlers } from '../../src/addie/mcp/admin-tools.js'; +import type { MemberContext } from '../../src/addie/member-context.js'; +import type { WorkOS } from '@workos-inc/node'; + +const primary = 'org_merge_contained_primary'; +const secondary = 'org_merge_contained_secondary'; +const third = 'org_merge_contained_third'; +const A = 'user_merge_a'; +const B = 'user_merge_b'; +const CSRF = 'm'.repeat(64); +const unavailable = { + error: ORGANIZATION_MERGE_UNAVAILABLE_ERROR, + message: ORGANIZATION_MERGE_UNAVAILABLE_MESSAGE, +}; +let pool: Pool; +let app: Parameters[0]; +let signingKey: Awaited>['privateKey']; +let sequence = 0; + +async function token(actor = A) { + return new SignJWT({ client_id: 'client_mock_id' }) + .setProtectedHeader({ alg: 'RS256' }).setSubject(actor).setIssuedAt() + .setJti(String(++sequence)).setExpirationTime('5m').sign(signingKey); +} +async function cookie(actor = A) { + const id = `merge_session_${++sequence}`; + state.sessions.set(id, { authenticated: true, user: state.users.get(actor), accessToken: await token(actor) }); + return `wos-session=${id}; csrf-token=${CSRF}`; +} + +/** + * Full rows across everything organization merge used to rewrite. Comparing the + * whole set before/after catches a moved row, a dropped duplicate, a re-encrypted + * token, an audit entry and a cross-organization effect alike. + */ +async function snapshot() { + const result: Record = {}; + for (const table of ['organizations','users','identity_workos_users','organization_memberships','organization_domains', + 'organization_credential_grants','organization_join_requests','working_group_memberships','member_profiles', + 'agent_contexts','brands','org_activities','org_stakeholders','registry_audit_log','revenue_events', + 'subscription_line_items','authorization_epochs']) { + result[table] = (await pool.query(`SELECT to_jsonb(t) AS row FROM ${table} t ORDER BY to_jsonb(t)::text`)).rows; + } + return result; +} + +/** Make A a platform admin; asserts the seeded working group actually exists. */ +async function makePlatformAdmin() { + state.platformAdmin = true; + const inserted = await pool.query(`INSERT INTO working_group_memberships (working_group_id,workos_user_id,status) + SELECT id,$1,'active' FROM working_groups WHERE slug='aao-admin'`, [A]); + expect(inserted.rowCount, 'aao-admin working group fixture must exist').toBe(1); +} + +async function expectNoEffects(before: Record) { + expect(await snapshot()).toEqual(before); + expect(state.calls.filter(c => c.startsWith('org_delete:') || c.startsWith('membership_create:'))).toEqual([]); +} + +beforeAll(async () => { + const connectionString = process.env.DATABASE_URL || 'postgresql://adcp:localdev@localhost:55432/adcp_test'; + const url = new URL(connectionString); + if (!['localhost','127.0.0.1','[::1]'].includes(url.hostname) || !url.pathname.endsWith('_test')) { + throw new Error('Merge containment regressions require a disposable loopback *_test database'); + } + pool = initializeDatabase({ connectionString }); + await runMigrations(); + const { HTTPServer } = await import('../../src/http.js'); + app = (new HTTPServer({ backgroundServices: 'refresh-only' }) as unknown as { app: Parameters[0] }).app; + const keys = await generateKeyPair('RS256'); signingKey = keys.privateKey; + __setJWKSForTesting(async () => keys.publicKey); +}, 60000); + +async function cleanFixtures() { + const orgs = [primary, secondary, third]; + const actors = [A, B]; + // organization_memberships has no foreign key to organizations or users, and + // identities outlive the cascade from users, so both need explicit cleanup. + const identities = (await pool.query( + 'SELECT identity_id FROM identity_workos_users WHERE workos_user_id = ANY($1)', [actors] + )).rows.map(row => row.identity_id); + await pool.query('DELETE FROM agent_contexts WHERE organization_id = ANY($1)', [orgs]); + await pool.query('DELETE FROM brands WHERE workos_organization_id = ANY($1)', [orgs]); + await pool.query('DELETE FROM member_profiles WHERE workos_organization_id = ANY($1)', [orgs]); + await pool.query('DELETE FROM registry_audit_log WHERE workos_organization_id = ANY($1)', [orgs]); + await pool.query('DELETE FROM working_group_memberships WHERE workos_user_id = ANY($1)', [actors]); + await pool.query('DELETE FROM organization_memberships WHERE workos_user_id = ANY($1) OR workos_organization_id = ANY($2)', [actors, orgs]); + await pool.query('DELETE FROM organizations WHERE workos_organization_id = ANY($1)', [orgs]); + await pool.query('DELETE FROM users WHERE workos_user_id = ANY($1)', [actors]); + if (identities.length) await pool.query('DELETE FROM identities WHERE id = ANY($1)', [identities]); +} + +afterAll(async () => { if (pool) await cleanFixtures(); stopAuthTimers(); __setJWKSForTesting(null); await closeDatabase(); }); + +beforeEach(async () => { + vi.clearAllMocks(); + state.calls = []; state.users.clear(); state.sessions.clear(); state.platformAdmin = false; + for (const id of [A, B]) invalidateBanCache('user', id); + await cleanFixtures(); + + for (const id of [primary, secondary, third]) { + await pool.query( + "INSERT INTO organizations (workos_organization_id,name,is_personal) VALUES ($1,$2,false)", + [id, id === primary ? 'Pinnacle Agency' : id === secondary ? 'Pinnacle Media' : 'Nova Brands'] + ); + } + for (const id of [A, B]) { + const user = { + id, + email: id === A ? 'sam@merge.example.test' : 'alex@merge.example.test', + firstName: 'Sam', lastName: 'Adeyemi', emailVerified: true, + createdAt: new Date(0).toISOString(), updatedAt: new Date(0).toISOString(), + }; + state.users.set(id, user); + await pool.query('INSERT INTO users (workos_user_id,email,first_name,primary_organization_id) VALUES ($1,$2,$3,$4)', + [id, user.email, 'Sam', secondary]); + } + // Rows the merge sequence used to move, re-encrypt or delete. + await pool.query(`INSERT INTO organization_memberships (workos_user_id,workos_organization_id,workos_membership_id,email,role) + VALUES ($1,$2,$3,$4,'owner')`, [B, secondary, 'om_merge_b', 'alex@merge.example.test']); + await pool.query("INSERT INTO organization_domains (workos_organization_id,domain,verified) VALUES ($1,'merge.example.test',true)", [secondary]); + await pool.query("INSERT INTO member_profiles (workos_organization_id,display_name,slug) VALUES ($1,'Pinnacle Media','pinnacle-media-merge')", [secondary]); +}); + +describe('mounted organization merge containment', () => { + it('POST /api/admin/cleanup/merge requires authentication', async () => { + const before = await snapshot(); + const response = await request(app).post('/api/admin/cleanup/merge') + .set('Cookie', `csrf-token=${CSRF}`).set('X-CSRF-Token', CSRF) + .send({ primary_org_id: primary, secondary_org_id: secondary }); + + // Unlike the contained deletion routes, merge keeps its admin gating: the + // refusal is never reachable anonymously. + expect(response.status, JSON.stringify(response.body)).toBe(401); + expect(response.body.error).not.toBe(ORGANIZATION_MERGE_UNAVAILABLE_ERROR); + await expectNoEffects(before); + }); + + it('POST /api/admin/cleanup/merge rejects a non-admin authenticated caller', async () => { + const before = await snapshot(); + const response = await request(app).post('/api/admin/cleanup/merge') + .set('Cookie', await cookie(B)).set('X-CSRF-Token', CSRF) + .send({ primary_org_id: primary, secondary_org_id: secondary }); + + expect([401, 403]).toContain(response.status); + expect(response.body.error).not.toBe(ORGANIZATION_MERGE_UNAVAILABLE_ERROR); + await expectNoEffects(before); + }); + + it('CSRF rejection still precedes the contained route', async () => { + const before = await snapshot(); + const response = await request(app).post('/api/admin/cleanup/merge') + .set('Cookie', await cookie()).send({ primary_org_id: primary, secondary_org_id: secondary }); + + expect(response.status).toBe(403); + expect(response.body.error).toBe('CSRF validation failed'); + await expectNoEffects(before); + }); + + for (const body of [ + {}, + { primary_org_id: primary }, + { primary_org_id: primary, secondary_org_id: secondary }, + { primary_org_id: primary, secondary_org_id: primary }, + { primary_org_id: primary, secondary_org_id: secondary, stripe_customer_resolution: 'keep_primary' }, + { primary_org_id: primary, secondary_org_id: secondary, stripe_customer_resolution: 'not_a_resolution' }, + { primary_org_id: secondary, secondary_org_id: primary, force: true }, + { primary_org_id: 'org_merge_missing', secondary_org_id: 'org_merge_also_missing' }, + ]) { + it(`platform admin gets the stable refusal for ${JSON.stringify(body)} with no effects`, async () => { + await makePlatformAdmin(); + + const before = await snapshot(); + state.calls = []; + const response = await request(app).post('/api/admin/cleanup/merge') + .set('Cookie', await cookie()).set('X-CSRF-Token', CSRF).send(body); + + expect(response.status, JSON.stringify(response.body)).toBe(503); + expect(response.body).toEqual(unavailable); + expect(response.body).not.toHaveProperty('details'); + await expectNoEffects(before); + }); + } + + it('the static admin key reaches the refusal but cannot execute a merge', async () => { + const before = await snapshot(); + const response = await request(app).post('/api/admin/cleanup/merge') + .set('Authorization', 'Bearer merge-test-static-key') + .send({ primary_org_id: primary, secondary_org_id: secondary }); + + // Pinned rather than "one of several": the static admin key authenticates + // and authorizes, so it is admitted by requireGlobalAdmin and then refused + // by the containment. Either half changing should fail this test. + expect(response.status, JSON.stringify(response.body)).toBe(503); + expect(response.body).toEqual(unavailable); + await expectNoEffects(before); + }); + + it('GET /api/admin/cleanup/preview-merge stays available and read-only', async () => { + await makePlatformAdmin(); + + const before = await snapshot(); + const response = await request(app) + .get(`/api/admin/cleanup/preview-merge?primary=${primary}&secondary=${secondary}`) + .set('Cookie', await cookie()); + + expect(response.status, JSON.stringify(response.body)).toBe(200); + expect(response.body.primary_org.id).toBe(primary); + expect(response.body.secondary_org.id).toBe(secondary); + // Preview genuinely reports the rows a merge would move... + const tables = response.body.estimated_changes.map((c: { table_name: string }) => c.table_name); + expect(tables).toContain('organization_memberships'); + expect(tables).toContain('member_profiles'); + // ...and changes nothing while doing it. + await expectNoEffects(before); + }); + + it('preview-merge still requires authentication', async () => { + const response = await request(app) + .get(`/api/admin/cleanup/preview-merge?primary=${primary}&secondary=${secondary}`); + expect(response.status).toBe(401); + }); + + it('a direct service call refuses against real fixtures', async () => { + const before = await snapshot(); + const provider = { + organizations: { deleteOrganization: vi.fn(async () => { state.calls.push('org_delete:direct'); }) }, + userManagement: { createOrganizationMembership: vi.fn(async () => { state.calls.push('membership_create:direct'); }) }, + } as unknown as WorkOS; + + await expect(mergeOrganizations(primary, secondary, A, provider)) + .rejects.toThrow(OrganizationMergeUnavailableError); + + expect(provider.organizations.deleteOrganization).not.toHaveBeenCalled(); + await expectNoEffects(before); + }); + + it('the Addie tool refuses execution against real fixtures', async () => { + const before = await snapshot(); + const handlers = createAdminToolHandlers({ + is_mapped: true, is_member: false, slack_linked: true, organization: null, + workos_user: { workos_user_id: A, email: 'sam@merge.example.test', first_name: 'Sam', last_name: 'Adeyemi' }, + } as unknown as MemberContext); + + const response = await handlers.get('merge_organizations')!({ + primary_org_id: primary, secondary_org_id: secondary, preview: false, + }); + + expect(response).toContain(ORGANIZATION_MERGE_UNAVAILABLE_ERROR); + expect(response).not.toContain('Merge Complete'); + await expectNoEffects(before); + // The execution path does not even read provider memberships. + expect(state.calls.filter(c => c.startsWith('memberships:'))).toEqual([]); + }); + + it('the Addie tool still previews against real fixtures without effects', async () => { + const before = await snapshot(); + const handlers = createAdminToolHandlers({ + is_mapped: true, is_member: false, slack_linked: true, organization: null, + workos_user: { workos_user_id: A, email: 'sam@merge.example.test', first_name: 'Sam', last_name: 'Adeyemi' }, + } as unknown as MemberContext); + + const response = await handlers.get('merge_organizations')!({ + primary_org_id: primary, secondary_org_id: secondary, preview: true, + }); + + expect(response).toContain('Merge Preview'); + expect(response).toContain('organization_memberships'); + expect(response).not.toContain('To execute the merge'); + await expectNoEffects(before); + }); + + it('leaves the third organization untouched throughout', async () => { + await makePlatformAdmin(); + + const before = await snapshot(); + for (const body of [ + { primary_org_id: primary, secondary_org_id: third }, + { primary_org_id: third, secondary_org_id: secondary }, + ]) { + const response = await request(app).post('/api/admin/cleanup/merge') + .set('Cookie', await cookie()).set('X-CSRF-Token', CSRF).send(body); + expect(response.status).toBe(503); + } + await expectNoEffects(before); + }); +}); diff --git a/server/tests/unit/integrity/invariants.test.ts b/server/tests/unit/integrity/invariants.test.ts index fd530201ec6..36fcd94aea2 100644 --- a/server/tests/unit/integrity/invariants.test.ts +++ b/server/tests/unit/integrity/invariants.test.ts @@ -1222,7 +1222,14 @@ describe('unique-org-per-email-domain', () => { .toBe('org_dec_real'); expect(v.message).toContain('DoubleVerify'); expect(v.message).toContain('7 members'); - expect(v.remediation_hint).toContain('DELETE FROM organizations'); + // #6827: the hint used to hand the operator a raw organization delete with + // the ID pre-filled. Organization deletion and merge are contained, so it + // now routes to read-only inspection and escalation instead. This assertion + // is the inverse of the old one on purpose — see + // server/tests/unit/organization-delete-statement-guard.test.ts. + expect(v.remediation_hint).not.toMatch(/DELETE\s+FROM\s+organizations/i); + expect(v.remediation_hint).toContain('preview-merge'); + expect(v.remediation_hint).toContain('#6827'); }); it('emits one violation per duplicate when three rows share a domain', async () => { diff --git a/server/tests/unit/organization-delete-statement-guard.test.ts b/server/tests/unit/organization-delete-statement-guard.test.ts new file mode 100644 index 00000000000..69a91f40fb8 --- /dev/null +++ b/server/tests/unit/organization-delete-statement-guard.test.ts @@ -0,0 +1,156 @@ +import { describe, expect, it } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +/** + * #6827 static guard: no new executable path may delete an organization row. + * + * Organization deletion and organization merge are both contained, but a + * containment that only covers routes and services is a containment an operator + * can walk around — a script or a copy-pasteable remediation hint reproduces the + * same split provider/local state with no journal and no audit trail. This guard + * fails the build when a raw organization delete appears anywhere outside the + * explicitly justified allowlist below, so re-introducing a bypass has to be a + * deliberate, reviewed edit to this list rather than a quiet new file. + * + * Scope: JavaScript, TypeScript and SQL under server/src, server/scripts and + * scripts/. SQL is covered deliberately: a `.sql` runbook under scripts/ is the + * likeliest shape for the next bypass, because it is what an operator reaches + * for after being refused. Only the schema migration directory is excluded — + * those files define the schema rather than delete rows on an operator's behalf. + */ + +const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..'); +const SCAN_ROOTS = ['server/src', 'server/scripts', 'scripts']; +const SKIP_DIRS = new Set(['node_modules', 'dist', 'generated', '.git']); +/** + * Excluded by exact path rather than by directory name, so a directory that + * merely happens to be called "migrations" elsewhere is still scanned. + */ +const SKIP_PATHS = new Set(['server/src/db/migrations']); +const CODE_EXTENSIONS = new Set([ + '.ts', '.tsx', '.mts', '.cts', '.js', '.mjs', '.cjs', '.sql', +]); + +/** Matches a raw delete against the organizations table, across line breaks. */ +const ORG_DELETE = /DELETE\s+FROM\s+organizations\b/gi; +/** + * Non-global twin for single-string checks. `String.match` resets `lastIndex`, + * but a global regex shared across assertions is a footgun not worth leaving. + */ +const ORG_DELETE_ONCE = /DELETE\s+FROM\s+organizations\b/i; + +/** + * Every remaining occurrence, with the reason it is not an operator-reachable + * organization deletion. Anything not listed here fails. + */ +const ALLOWLIST: Record = { + 'server/src/db/organization-db.ts': { + occurrences: 1, + reason: + 'OrganizationDatabase.deleteOrganization has no callers anywhere in the tree ' + + '(dead before the containment work began) and is reachable only by adding one.', + }, + 'server/src/services/prospect.ts': { + occurrences: 1, + reason: + 'Prospect creation rolling back the row it inserted moments earlier in the same ' + + 'call when the domain link conflicts. It never removes a pre-existing organization.', + }, + 'server/scripts/setup-sandbox.ts': { + occurrences: 2, + reason: + 'Local sandbox seeding, bounded to org_aao_sandbox_* ids and refusing to run ' + + 'unless STRIPE_SECRET_KEY is sk_test_*. Never runs against production data.', + }, +}; + +function relative(absolute: string): string { + return path.relative(REPO_ROOT, absolute).split(path.sep).join('/'); +} + +function collectFiles(dir: string, found: string[] = []): string[] { + if (!fs.existsSync(dir)) return found; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const absolute = path.join(dir, entry.name); + if (entry.isDirectory()) { + if (SKIP_DIRS.has(entry.name) || SKIP_PATHS.has(relative(absolute))) continue; + collectFiles(absolute, found); + } else if (CODE_EXTENSIONS.has(path.extname(entry.name))) { + found.push(absolute); + } + } + return found; +} + +function scan(): Map { + const hits = new Map(); + for (const root of SCAN_ROOTS) { + for (const absolute of collectFiles(path.join(REPO_ROOT, root))) { + const matches = fs.readFileSync(absolute, 'utf8').match(ORG_DELETE); + if (matches?.length) hits.set(relative(absolute), matches.length); + } + } + return hits; +} + +describe('#6827 raw organization delete guard', () => { + const hits = scan(); + + it('scans a non-trivial number of files, so a broken walker cannot pass silently', () => { + const scanned = SCAN_ROOTS.flatMap(root => collectFiles(path.join(REPO_ROOT, root))); + expect(scanned.length).toBeGreaterThan(500); + // And SQL is genuinely in the walk, not just in the extension set. + expect(scanned.filter(file => file.endsWith('.sql')).length).toBeGreaterThan(0); + // The schema migration directory stays out by exact path. + expect(scanned.map(relative).filter(file => file.startsWith('server/src/db/migrations/'))).toEqual([]); + }); + + it('finds no raw organization delete outside the justified allowlist', () => { + const unexpected = [...hits.keys()].filter(file => !(file in ALLOWLIST)).sort(); + expect( + unexpected, + 'A raw organization delete appeared in a file with no recorded justification. ' + + 'Organization deletion and merge are contained under #6827; do not add a ' + + 'bypass. If this is genuinely not an operator-reachable deletion, add it to ' + + 'ALLOWLIST with the reason.', + ).toEqual([]); + }); + + it('holds each allowlisted file to its recorded occurrence count', () => { + for (const [file, { occurrences, reason }] of Object.entries(ALLOWLIST)) { + expect(hits.get(file), `${file} (${reason})`).toBe(occurrences); + } + }); + + it('keeps the duplicate-stub incident script non-destructive', () => { + const target = 'scripts/incidents/2026-05-cleanup-duplicate-prospect-stubs.ts'; + const source = fs.readFileSync(path.join(REPO_ROOT, target), 'utf8'); + + // No delete, no database client, no transaction control: the destructive + // path is removed rather than merely gated. + expect(source).not.toMatch(ORG_DELETE_ONCE); + expect(source).not.toMatch(/from ['"]pg['"]/); + expect(source).not.toMatch(/\bnew Client\b/); + expect(source).not.toMatch(/\b(BEGIN|COMMIT|ROLLBACK)\b/); + + // --execute is refused, and the refusal precedes every other statement so + // no configuration or network call can happen first. + expect(source).toMatch(/--execute/); + const refusalAt = source.indexOf("process.argv.includes('--execute')"); + const firstEnvReadAt = source.indexOf('process.env.'); + expect(refusalAt).toBeGreaterThan(-1); + expect(refusalAt).toBeLessThan(firstEnvReadAt); + }); + + it('keeps the duplicate-domain invariant from handing an operator a delete statement', () => { + const target = 'server/src/audit/integrity/invariants/unique-org-per-email-domain.ts'; + const source = fs.readFileSync(path.join(REPO_ROOT, target), 'utf8'); + + expect(source).not.toMatch(ORG_DELETE_ONCE); + // The remediation now routes to read-only inspection and escalation. + expect(source).toMatch(/preview-merge/); + expect(source).toMatch(/#6827/); + }); +}); diff --git a/server/tests/unit/organization-merge-containment-addie.test.ts b/server/tests/unit/organization-merge-containment-addie.test.ts new file mode 100644 index 00000000000..99867e89593 --- /dev/null +++ b/server/tests/unit/organization-merge-containment-addie.test.ts @@ -0,0 +1,224 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { MemberContext } from '../../src/addie/member-context.js'; + +// The Addie merge handler used to read provider memberships, run the database +// merge, write provider memberships and delete the provider organization twice. +// Every one of those collaborators is a throwing double here. +const effects = vi.hoisted(() => ({ + getPool: vi.fn(() => { throw new Error('Contained merge must not touch the database pool'); }), + query: vi.fn(() => { throw new Error('Contained merge must not query the database'); }), + mergeOrganizations: vi.fn(() => { throw new Error('Contained merge must not reach the merge service'); }), + previewMerge: vi.fn(), + listOrganizationMemberships: vi.fn(), + createOrganizationMembership: vi.fn(() => { throw new Error('Contained merge must not write provider memberships'); }), + deleteOrganization: vi.fn(() => { throw new Error('Contained merge must not delete a provider organization'); }), + // Not a throwing double: preview legitimately acquires a client, so this is + // asserted per-branch rather than globally forbidden. + getWorkos: vi.fn(), +})); + +vi.mock('../../src/db/client.js', async (importOriginal) => ({ + ...(await importOriginal()), + getPool: effects.getPool, + query: effects.query, +})); +vi.mock('../../src/db/org-merge-db.js', () => ({ + mergeOrganizations: effects.mergeOrganizations, + previewMerge: effects.previewMerge, +})); +vi.mock('../../src/auth/workos-client.js', async (importOriginal) => ({ + ...(await importOriginal()), + getWorkos: effects.getWorkos, +})); + +import { createAdminToolHandlers, ADMIN_TOOLS } from '../../src/addie/mcp/admin-tools.js'; +import { + ORGANIZATION_MERGE_UNAVAILABLE_ERROR, + ORGANIZATION_MERGE_UNAVAILABLE_MESSAGE, +} from '../../src/db/org-merge-containment.js'; + +const PRIMARY = 'org_merge_addie_primary'; +const SECONDARY = 'org_merge_addie_secondary'; + +const adminMemberContext = { + is_mapped: true, + is_member: false, + slack_linked: true, + organization: null, + workos_user: { + workos_user_id: 'user_merge_addie_admin', + email: 'sam@merge.example.test', + first_name: 'Sam', + last_name: 'Adeyemi', + }, +} as unknown as MemberContext; + +const previewFixture = { + primary_org: { id: PRIMARY, name: 'Pinnacle Agency' }, + secondary_org: { id: SECONDARY, name: 'Pinnacle Media' }, + estimated_changes: [{ table_name: 'organization_memberships', rows_to_move: 2 }], + stripe_customer_conflict: { + has_conflict: false, + primary_customer_id: null, + secondary_customer_id: null, + requires_resolution: false, + }, + warnings: [], +}; + +function merge(input: Record) { + return createAdminToolHandlers(adminMemberContext).get('merge_organizations')!(input); +} + +function providerDouble() { + return { + organizations: { deleteOrganization: effects.deleteOrganization }, + userManagement: { + createOrganizationMembership: effects.createOrganizationMembership, + listOrganizationMemberships: effects.listOrganizationMemberships, + }, + }; +} + +beforeEach(() => { + vi.clearAllMocks(); + effects.previewMerge.mockResolvedValue(previewFixture); + effects.listOrganizationMemberships.mockResolvedValue({ data: [] }); + effects.getWorkos.mockReturnValue(providerDouble()); +}); + +function expectNoExecutionEffects() { + for (const name of ['getPool', 'query', 'mergeOrganizations', 'createOrganizationMembership', 'deleteOrganization'] as const) { + expect(effects[name], `${name} must not be called`).not.toHaveBeenCalled(); + } +} + +describe('Addie merge_organizations — contained execution', () => { + const executeInputs = [ + { label: 'plain execute', input: { primary_org_id: PRIMARY, secondary_org_id: SECONDARY, preview: false } }, + { label: 'execute with stripe resolution', input: { primary_org_id: PRIMARY, secondary_org_id: SECONDARY, preview: false, stripe_customer_resolution: 'keep_primary' } }, + { label: 'execute with unknown resolution', input: { primary_org_id: PRIMARY, secondary_org_id: SECONDARY, preview: false, stripe_customer_resolution: 'not_a_resolution' } }, + { label: 'reversed direction', input: { primary_org_id: SECONDARY, secondary_org_id: PRIMARY, preview: false } }, + { label: 'extra unknown keys', input: { primary_org_id: PRIMARY, secondary_org_id: SECONDARY, preview: false, force: true, confirmation: 'Pinnacle Agency' } }, + ]; + + for (const { label, input } of executeInputs) { + it(`refuses (${label}) with the stable code and performs no work`, async () => { + const response = await merge(input); + + expect(response).toContain(ORGANIZATION_MERGE_UNAVAILABLE_MESSAGE); + expect(response).toContain(ORGANIZATION_MERGE_UNAVAILABLE_ERROR); + // The old success copy must be gone — Addie must not claim a merge. + expect(response).not.toContain('Merge Complete'); + expect(response).not.toContain('has been deleted'); + expect(response).not.toContain('rows moved'); + expectNoExecutionEffects(); + expect(effects.previewMerge).not.toHaveBeenCalled(); + expect(effects.listOrganizationMemberships).not.toHaveBeenCalled(); + }); + + it(`does not acquire a WorkOS client (${label})`, async () => { + // Stricter than "no provider method ran": the contained execution path + // must not construct or initialize a provider client at all. + await merge(input); + expect(effects.getWorkos).not.toHaveBeenCalled(); + }); + } + + it('steers away from manual workarounds instead of leaving the operator to improvise', async () => { + const response = await merge({ primary_org_id: PRIMARY, secondary_org_id: SECONDARY, preview: false }); + expect(response).toMatch(/preview=true/); + expect(response).toMatch(/#6827/); + expect(response).toMatch(/Do not substitute a manual database edit/); + }); + + it('refuses repeated execution attempts identically', async () => { + const input = { primary_org_id: PRIMARY, secondary_org_id: SECONDARY, preview: false }; + const first = await merge(input); + const second = await merge(input); + expect(second).toBe(first); + expectNoExecutionEffects(); + expect(effects.getWorkos).not.toHaveBeenCalled(); + }); +}); + +describe('Addie merge_organizations — read-only preview is preserved', () => { + for (const input of [ + { primary_org_id: PRIMARY, secondary_org_id: SECONDARY }, + { primary_org_id: PRIMARY, secondary_org_id: SECONDARY, preview: true }, + ]) { + it(`still previews for ${JSON.stringify(input)} without executing`, async () => { + const response = await merge(input); + + expect(effects.previewMerge).toHaveBeenCalledWith(PRIMARY, SECONDARY); + expect(response).toContain('Merge Preview'); + expect(response).toContain('organization_memberships'); + expectNoExecutionEffects(); + }); + + it(`acquires the WorkOS client only in the preview branch for ${JSON.stringify(input)}`, async () => { + // Positive control for the execution-path assertion above: getWorkos is + // genuinely observable here, so "not called" during execute is meaningful. + await merge(input); + expect(effects.getWorkos).toHaveBeenCalledTimes(1); + expect(effects.listOrganizationMemberships).toHaveBeenCalled(); + }); + } + + it('no longer instructs the caller to execute with preview=false', async () => { + const response = await merge({ primary_org_id: PRIMARY, secondary_org_id: SECONDARY }); + expect(response).not.toContain('To execute the merge'); + expect(response).toContain('read-only preview'); + expect(response).toContain(ORGANIZATION_MERGE_UNAVAILABLE_ERROR); + }); + + it('describes provider effects as hypothetical, not scheduled', async () => { + const response = await merge({ primary_org_id: PRIMARY, secondary_org_id: SECONDARY }); + expect(response).toContain('would be deleted from WorkOS'); + expect(response).not.toContain('will be deleted from WorkOS'); + }); + + it('still reports a Stripe customer conflict without resolving it', async () => { + effects.previewMerge.mockResolvedValue({ + ...previewFixture, + stripe_customer_conflict: { + has_conflict: true, + primary_customer_id: 'cus_primary_double', + secondary_customer_id: 'cus_secondary_double', + requires_resolution: true, + }, + }); + const response = await merge({ primary_org_id: PRIMARY, secondary_org_id: SECONDARY }); + expect(response).toContain('Stripe Customer Conflict'); + expectNoExecutionEffects(); + }); +}); + +describe('Addie merge_organizations — input guards and tool surface', () => { + for (const input of [ + {}, + { primary_org_id: PRIMARY }, + { secondary_org_id: SECONDARY }, + { primary_org_id: PRIMARY, secondary_org_id: PRIMARY, preview: false }, + ]) { + it(`rejects malformed input ${JSON.stringify(input)} without any effect`, async () => { + const response = await merge(input); + expect(response).toMatch(/^❌/); + expectNoExecutionEffects(); + expect(effects.previewMerge).not.toHaveBeenCalled(); + expect(effects.getWorkos).not.toHaveBeenCalled(); + }); + } + + it('still declares the tool so the contained handler stays reachable and refusing', async () => { + // The tool's declared description and usage_hints are intentionally NOT + // changed by this containment: scripts/addie-tool-surface-budget.json pins a + // reviewed profile-contract hash over every declared tool profile, and + // re-blessing it is its own review. The runtime refusal is authoritative; the + // stale "execute with preview=false" hint is recorded as a follow-up in + // docs/contributing/organization-deletion-containment.md. + const tool = ADMIN_TOOLS.find(t => t.name === 'merge_organizations'); + expect(tool).toBeDefined(); + expect(tool!.input_schema.properties).toHaveProperty('preview'); + }); +}); diff --git a/server/tests/unit/organization-merge-containment-route-order.test.ts b/server/tests/unit/organization-merge-containment-route-order.test.ts new file mode 100644 index 00000000000..db74a4a75d4 --- /dev/null +++ b/server/tests/unit/organization-merge-containment-route-order.test.ts @@ -0,0 +1,86 @@ +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; + +/** + * Pins the ORDERING claim the route comment and the containment document make: + * `POST /api/admin/cleanup/merge` refuses on its own, before the merge service. + * + * Its sibling suite (organization-merge-containment.test.ts) spreads the real + * org-merge-db module so the genuine contained `mergeOrganizations` is under + * test. That proves the service refuses, but it cannot distinguish "the route + * refuses first" from "the route calls the service and maps its throw to 503" — + * both produce a 503 and no effects. This file mocks the service with a throwing + * spy so that difference is observable. + */ +const effects = vi.hoisted(() => ({ + mergeOrganizations: vi.fn(() => { throw new Error('The route must not reach the merge service'); }), + previewMerge: vi.fn(() => { throw new Error('The contained route must not preview'); }), + getPool: vi.fn(() => { throw new Error('The contained route must not touch the database pool'); }), + globalAdminGate: vi.fn((_req: express.Request, _res: express.Response, next: express.NextFunction) => next()), +})); + +vi.mock('../../src/db/org-merge-db.js', () => ({ + mergeOrganizations: effects.mergeOrganizations, + previewMerge: effects.previewMerge, +})); +vi.mock('../../src/db/client.js', async (importOriginal) => ({ + ...(await importOriginal()), + getPool: effects.getPool, +})); +vi.mock('../../src/middleware/auth.js', async (importOriginal) => ({ + ...(await importOriginal()), + requireGlobalAdmin: [effects.globalAdminGate], +})); + +import { setupCleanupRoutes } from '../../src/routes/admin/cleanup.js'; +import { + ORGANIZATION_MERGE_UNAVAILABLE_ERROR, + ORGANIZATION_MERGE_UNAVAILABLE_MESSAGE, +} from '../../src/db/org-merge-containment.js'; +import { stopAuthTimers } from '../../src/middleware/auth.js'; + +function cleanupApp() { + const app = express(); + app.use(express.json()); + const apiRouter = express.Router(); + setupCleanupRoutes(apiRouter); + app.use('/api/admin', apiRouter); + return app; +} + +beforeEach(() => { vi.clearAllMocks(); }); +afterAll(() => { stopAuthTimers(); }); + +describe('POST /api/admin/cleanup/merge refuses before the merge service', () => { + for (const body of [ + {}, + { primary_org_id: 'org_a', secondary_org_id: 'org_b' }, + { primary_org_id: 'org_a', secondary_org_id: 'org_b', stripe_customer_resolution: 'keep_primary' }, + ]) { + it(`never calls mergeOrganizations for ${JSON.stringify(body)}`, async () => { + const response = await request(cleanupApp()).post('/api/admin/cleanup/merge').send(body); + + expect(response.status).toBe(503); + expect(response.body).toEqual({ + error: ORGANIZATION_MERGE_UNAVAILABLE_ERROR, + message: ORGANIZATION_MERGE_UNAVAILABLE_MESSAGE, + }); + // The discriminating assertion: a route that delegated and mapped the + // service's throw would have called this spy. + expect(effects.mergeOrganizations).not.toHaveBeenCalled(); + expect(effects.previewMerge).not.toHaveBeenCalled(); + expect(effects.getPool).not.toHaveBeenCalled(); + }); + } + + it('proves the spy is wired, so "not called" is meaningful', async () => { + // Positive control: the same mocked module is what the route file imports, + // and calling through it does reach the spy. + const { mergeOrganizations } = await import('../../src/db/org-merge-db.js'); + expect(() => mergeOrganizations('org_a', 'org_b', 'user_a')).toThrow( + 'The route must not reach the merge service', + ); + expect(effects.mergeOrganizations).toHaveBeenCalledTimes(1); + }); +}); diff --git a/server/tests/unit/organization-merge-containment.test.ts b/server/tests/unit/organization-merge-containment.test.ts new file mode 100644 index 00000000000..51a23544b34 --- /dev/null +++ b/server/tests/unit/organization-merge-containment.test.ts @@ -0,0 +1,181 @@ +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; + +// `getPool`, `query` and `previewMerge` are the discriminating doubles here: +// the real contained mergeOrganizations and the contained route would reach +// them if either stopped refusing. The three provider methods are tripwires +// rather than discriminators — they hang off the `providerDouble` passed as the +// ignored `_workos` argument, so they only fire if a future edit starts using +// it. `getWorkos` is deliberately NOT asserted in this file: nothing in its +// import graph can call it (cleanup.ts no longer imports it). That property is +// covered where it is observable, in +// organization-merge-containment-addie.test.ts. +const effects = vi.hoisted(() => ({ + getPool: vi.fn(() => { throw new Error('Contained merge must not touch the database pool'); }), + query: vi.fn(() => { throw new Error('Contained merge must not query the database'); }), + deleteOrganization: vi.fn(() => { throw new Error('Contained merge must not delete a provider organization'); }), + createOrganizationMembership: vi.fn(() => { throw new Error('Contained merge must not write provider memberships'); }), + listOrganizationMemberships: vi.fn(() => { throw new Error('Contained merge execution must not read provider memberships'); }), + previewMerge: vi.fn(), + globalAdminGate: vi.fn((_req: express.Request, _res: express.Response, next: express.NextFunction) => next()), +})); + +vi.mock('../../src/db/client.js', async (importOriginal) => ({ + ...(await importOriginal()), + getPool: effects.getPool, + query: effects.query, +})); +// Spread the original so `mergeOrganizations` under test is the real contained +// implementation; only the read-only preview is swapped for an observable double. +vi.mock('../../src/db/org-merge-db.js', async (importOriginal) => ({ + ...(await importOriginal()), + previewMerge: effects.previewMerge, +})); +vi.mock('../../src/middleware/auth.js', async (importOriginal) => ({ + ...(await importOriginal()), + requireGlobalAdmin: [effects.globalAdminGate], +})); + +import { mergeOrganizations } from '../../src/db/org-merge-db.js'; +import { + ORGANIZATION_MERGE_UNAVAILABLE_ERROR, + ORGANIZATION_MERGE_UNAVAILABLE_MESSAGE, + OrganizationMergeUnavailableError, +} from '../../src/db/org-merge-containment.js'; +import { setupCleanupRoutes } from '../../src/routes/admin/cleanup.js'; +import { stopAuthTimers } from '../../src/middleware/auth.js'; +import type { WorkOS } from '@workos-inc/node'; + +const unavailable = { + error: ORGANIZATION_MERGE_UNAVAILABLE_ERROR, + message: ORGANIZATION_MERGE_UNAVAILABLE_MESSAGE, +}; +const PRIMARY = 'org_merge_contained_primary'; +const SECONDARY = 'org_merge_contained_secondary'; + +// A provider double whose every method throws. Passing it into the contained +// service proves the refusal happens before the client is ever used. +const providerDouble = { + organizations: { deleteOrganization: effects.deleteOrganization }, + userManagement: { + createOrganizationMembership: effects.createOrganizationMembership, + listOrganizationMemberships: effects.listOrganizationMemberships, + }, +} as unknown as WorkOS; + +function cleanupApp() { + const app = express(); + app.use(express.json()); + const apiRouter = express.Router(); + setupCleanupRoutes(apiRouter); + app.use('/api/admin', apiRouter); + return app; +} + +function expectNoEffects() { + for (const [name, spy] of Object.entries(effects)) { + if (name === 'globalAdminGate') continue; + expect(spy, `${name} must not be called`).not.toHaveBeenCalled(); + } +} + +beforeEach(() => { + vi.clearAllMocks(); + effects.globalAdminGate.mockImplementation((_req, _res, next) => next()); +}); +afterAll(() => { stopAuthTimers(); }); + +describe('organization merge containment — shared service boundary', () => { + const variants: { label: string; args: Parameters }[] = [ + { label: 'ordinary pair', args: [PRIMARY, SECONDARY, 'user_admin', providerDouble] }, + { label: 'keep_primary resolution', args: [PRIMARY, SECONDARY, 'user_admin', providerDouble, { stripeCustomerResolution: 'keep_primary' }] }, + { label: 'use_secondary resolution', args: [PRIMARY, SECONDARY, 'user_admin', providerDouble, { stripeCustomerResolution: 'use_secondary' }] }, + { label: 'keep_both_unlinked resolution', args: [PRIMARY, SECONDARY, 'user_admin', providerDouble, { stripeCustomerResolution: 'keep_both_unlinked' }] }, + { label: 'reversed direction', args: [SECONDARY, PRIMARY, 'user_admin', providerDouble] }, + { label: 'identical ids', args: [PRIMARY, PRIMARY, 'user_admin', providerDouble] }, + { label: 'unknown ids', args: [{} as unknown as string, '', '', providerDouble] }, + ]; + + for (const { label, args } of variants) { + it(`refuses a direct call (${label}) before any collaborator`, async () => { + // Any overlooked or future caller that bypasses the route and the tool + // still cannot execute the sequence. + await expect(mergeOrganizations(...args)).rejects.toThrow(OrganizationMergeUnavailableError); + expectNoEffects(); + }); + } + + it('carries the stable code and message consistent with the deletion containment', async () => { + const error = await mergeOrganizations(PRIMARY, SECONDARY, 'user_admin', providerDouble).catch(e => e); + expect(error).toBeInstanceOf(OrganizationMergeUnavailableError); + expect(error.code).toBe('organization_merge_unavailable'); + expect(error.message).toBe('Organization merge is temporarily unavailable.'); + expect(error.name).toBe('OrganizationMergeUnavailableError'); + expectNoEffects(); + }); + + it('refuses repeated and concurrent calls identically and still does nothing', async () => { + const outcomes = await Promise.allSettled( + Array.from({ length: 4 }, () => mergeOrganizations(PRIMARY, SECONDARY, 'user_admin', providerDouble)) + ); + expect(outcomes.every(o => o.status === 'rejected')).toBe(true); + for (const outcome of outcomes) { + expect((outcome as PromiseRejectedResult).reason.code).toBe(ORGANIZATION_MERGE_UNAVAILABLE_ERROR); + } + expectNoEffects(); + }); +}); + +describe('organization merge containment — POST /api/admin/cleanup/merge', () => { + const bodies = [ + undefined, + {}, + { primary_org_id: PRIMARY }, + { primary_org_id: PRIMARY, secondary_org_id: SECONDARY }, + { primary_org_id: PRIMARY, secondary_org_id: PRIMARY }, + { primary_org_id: PRIMARY, secondary_org_id: SECONDARY, stripe_customer_resolution: 'keep_primary' }, + { primary_org_id: PRIMARY, secondary_org_id: SECONDARY, stripe_customer_resolution: 'not_a_resolution' }, + { primary_org_id: [PRIMARY, SECONDARY], secondary_org_id: { nested: SECONDARY }, force: true }, + ]; + + for (const body of bodies) { + it(`returns the stable unavailable response for body ${JSON.stringify(body)}`, async () => { + const response = await request(cleanupApp()).post('/api/admin/cleanup/merge').send(body as object); + expect(response.status).toBe(503); + expect(response.body).toEqual(unavailable); + // The former validation and 500 branches disclosed org state and error + // internals; every input now gets the identical refusal. + expect(Object.keys(response.body).sort()).toEqual(['error', 'message']); + expectNoEffects(); + }); + } + + it('keeps administrative gating: the global admin gate still runs', async () => { + await request(cleanupApp()).post('/api/admin/cleanup/merge').send({}); + expect(effects.globalAdminGate).toHaveBeenCalledTimes(1); + }); + + it('is unreachable when the global admin gate denies, and still has no effects', async () => { + effects.globalAdminGate.mockImplementation((_req, res) => { + res.status(401).json({ error: 'Authentication required' }); + }); + const response = await request(cleanupApp()).post('/api/admin/cleanup/merge').send({ + primary_org_id: PRIMARY, secondary_org_id: SECONDARY, + }); + expect(response.status).toBe(401); + expect(response.body.error).not.toBe(ORGANIZATION_MERGE_UNAVAILABLE_ERROR); + expectNoEffects(); + }); + + it('does not answer for neighbouring cleanup paths or other methods', async () => { + const app = cleanupApp(); + for (const path of ['/api/admin/cleanup/merge/extra', '/api/admin/cleanup/mergex', '/api/admin/cleanup']) { + const response = await request(app).post(path).send({}); + expect(response.status, path).toBe(404); + } + const wrongMethod = await request(app).delete('/api/admin/cleanup/merge').send({}); + expect(wrongMethod.status).toBe(404); + expectNoEffects(); + }); +});