From 95f9e0f22bfa24650b3ec805b3150213439cae42 Mon Sep 17 00:00:00 2001 From: Brian O'Kelley Date: Thu, 17 Sep 2026 23:28:38 +0000 Subject: [PATCH] fix(orgs): make organization deletion temporarily unavailable (#6827) Return a stable 503 from the self-service and administrative organization deletion routes before route authentication, provider calls, or local effects. Exclude these contained requests from post-response authorization observation. Preserve the landed membership and authentication correction. Keep organization merge and operator bypass containment in the separate dependent change. Document the durable lifecycle requirements for re-enabling deletion without claiming a journal, compensation, or rollback guarantee. Co-Authored-By: Claude Opus 5 (1M context) --- .../organization-deletion-containment.md | 187 +++++++++++ .../organization-authorization-observer.ts | 14 +- server/src/routes/admin/accounts-billing.ts | 129 +------- server/src/routes/organizations.ts | 123 +------ .../tests/integration/admin-endpoints.test.ts | 143 ++++----- .../organization-deletion-containment.test.ts | 299 ++++++++++++++++++ .../integration/self-service-delete.test.ts | 172 +++++----- .../organization-deletion-containment.test.ts | 66 ++++ 8 files changed, 721 insertions(+), 412 deletions(-) create mode 100644 docs/contributing/organization-deletion-containment.md create mode 100644 server/tests/integration/organization-deletion-containment.test.ts create mode 100644 server/tests/unit/organization-deletion-containment.test.ts diff --git a/docs/contributing/organization-deletion-containment.md b/docs/contributing/organization-deletion-containment.md new file mode 100644 index 00000000000..b63b7d75ef8 --- /dev/null +++ b/docs/contributing/organization-deletion-containment.md @@ -0,0 +1,187 @@ +--- +description: Why direct organization deletion is unavailable, which routes are contained, and the durable lifecycle requirements for re-enabling deletion. +"og:title": AdCP organization deletion containment +--- + +# 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. + +Requests reaching either handler receive HTTP **503** with the stable body: + +```json +{ + "error": "organization_deletion_unavailable", + "message": "Organization deletion is temporarily unavailable." +} +``` + +The response is unconditional and contains no organization-specific information. +It runs before route authentication, which can hydrate local identity and cache +state, and before authorization, subscription reads, WorkOS/Stripe calls, local +writes, cascades, deletion audit records, cache invalidation or notifications. +The existing server-only observer exclusion prevents post-response canonical or +exact-credential WorkOS reads, including for an already populated principal. +There is no bypass for an exact owner/admin, platform administrator, static admin +key, tenant API key, development session, credential grant, matching email/domain, +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. + +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 +were already reachable unauthenticated on the identical path. Because 503 is a +server-error status, `requestMetrics` records every contained request as a failed +`/api` request, so an unauthenticated caller can raise the 5xx rate for these two +paths at no cost. No page results: the only Slack alerting on this path is the +10-second slow-response gate and this handler is constant-time. An external +error-budget monitor keyed on 5xx should exclude these two routes. Successful authentication is not +needed to learn that this operation is unavailable; no data or authority is +returned. Organization reads and unrelated membership/domain routes retain their +existing behavior and authorization. This change does not establish their +broader security acceptance or restore any previously contained operation. + +## Two deliberate divergences from neighbouring handlers + +**Returning before `requireAuth`/`requireAdmin`.** The repository's precedent for +a switched-off admin endpoint keeps both guards and returns 410 — see the removed +payment-link and invoice routes in `server/src/routes/admin/prospects.ts`. Those +are *permanently* removed endpoints where running authentication first costs +nothing. This containment diverges because `requireAuth` itself performs provider +and database work: WorkOS API-key validation, sealed-session loading and platform +ban lookups. Those are exactly the side effects this slice must not perform, so +the response has to precede them. The contained handler is strictly cheaper than +the middleware it replaced, and the mounted tests assert that neither API-key +validation nor session loading fires. + +**A machine-stable snake_case error code.** Neighbouring 503s in these two files +use a human sentence in `error`. `organization_deletion_unavailable` is a stable +identifier on purpose, so a caller can branch on containment without string +matching, and it is consistent with the dozens of other snake_case error codes +already used across `server/src/routes/`. The human-readable text lives in +`message`. + +## Why deletion remains unavailable + +The parent implementation used canonical `req.user.id` for the self-service +owner lookup. Linked credential A could therefore authorize using sibling B's +owner membership. Administrative deletion depended on the existing admin policy, +which also includes canonical identity and static administration. Exact identity +checks alone would not repair the deletion lifecycle. + +Both handlers read the organization and payment history, obtained subscription +information (potentially reading Stripe), checked confirmation, and then: + +1. Inserted `organization_deleted` into the local audit table. +2. Attempted WorkOS organization deletion (admin skipped it if WorkOS was absent). +3. Swallowed a WorkOS error and continued with local organization deletion and + its foreign-key effects. +4. Reported success if the local delete completed. + +Those steps were not one transaction. Provider failure could leave a live +provider organization with local state deleted. A timeout could complete late; +a local failure after provider success could leave the opposite split state. +The early audit asserted deletion before either outcome was known. Subscription +creation could race the preliminary billing reads. The containment removes this +sequence; it does not attempt to recreate an organization as compensation. + +The parent behavior above was demonstrated during investigation by running the +parent commit's handlers against a disposable local PostgreSQL database with a +WorkOS double. That demonstration is deliberately **not** committed: its +assertions require the deleting handlers, so it cannot live in this tree and +cannot be re-run from it. Treat the list below as investigation findings, not as +a reproducible gate. The last item is the one a reader can verify statically from +the schema. What the demonstration established about the parent tree: + +- A linked credential with no membership of its own completed a self-service + deletion using its canonical sibling's owner membership. WorkOS deletion was + called, an audit row was written, and the organization row was removed. +- A WorkOS rejection was swallowed: the local organization row was still + deleted and the caller still received `success: true`. +- The `organization_deleted` audit row survived that provider failure, so a + durable record claimed a deletion that had only half happened. +- A platform administrator completed the same sequence through the + administrative entry point. +- Both entry points returned the organization name in a pre-deletion + confirmation error before *exact-credential* authority had been established. + Authority as such was checked: self-service required an `owner` role and the + administrative route required `requireAuth` plus `requireAdmin`. The defect is + that self-service authority was borrowable from a canonical sibling, not that + it was absent. +- Local `organization_memberships` rows were not removed with the organization, + leaving dangling membership state for an organization that no longer existed. + This one is verifiable from the schema: `organization_memberships` + (`server/src/db/migrations/055_organization_memberships.sql`) declares no + foreign key to `organizations` or `users`, and no later migration adds one. + 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. + +## Operator handling while deletion is unavailable + +There is no operator bypass, break-glass credential or hidden flag: the response +is unconditional. A member's legitimate workspace-deletion request — including a +data-erasure request with a compliance deadline — is therefore queued until +deletion is re-enabled, and must be escalated to the engineering owner of #6827 +rather than worked around. Direct `psql` deletion and organization merge are both +unsafe substitutes: they reproduce exactly the split provider/local state and the +dangling membership rows described above. + +The administrative UI is unchanged by this slice. The danger-zone modal in +`server/public/admin-account-detail.html` still offers a Delete workspace button +and still says workspaces with payment history or an active subscription cannot +be deleted, which is now misleading — no workspace can be deleted. The button +degrades correctly (the operator sees the unavailable message after confirming), +but the copy and the disabled state are a known follow-up. + +## Acceptance requirements before enabling deletion + +A separately reviewed design and implementation must satisfy every row below on +both entry points and all other participating writers. A role check, feature +flag, migration alone, best-effort rollback, or an in-memory lock is insufficient. + +| Boundary / failure | Required durable behavior and acceptance evidence | +| --- | --- | +| Exact authority and target | Bind the authenticated credential, explicit organization, permitted action, membership/grant policy, provider organization ID and authorization epoch to the operation. Reject conflicting/malformed selectors and canonical sibling substitution. Recheck authority at defined irreversible boundaries. Any future admin authority policy requires explicit review; existing static/platform status is not an exception to this containment. | +| Durable operation journal | Persist a unique operation ID, caller/idempotency binding, exact actor and target, immutable preconditions and provenance, provider request correlation, state/version, attempts and known/unknown outcomes before any external mutation. Journal/tombstone retention must survive organization deletion, process death and database recovery. Enumerate every allowed transition and who can perform it. | +| Prepare failure | Journal/precondition/audit-intent failure causes zero provider or destructive local work. Prove connection errors, transaction rollback, epoch changes and billing conflicts. No success or accepted claim without the corresponding durable record. | +| Provider rejection or absence | Classify a definite rejection separately from an unknown outcome. Preserve local organization, memberships, grants and provenance. A missing provider client must never authorize local-only deletion. Record an honest durable outcome and permitted recovery action. | +| Timeout, disconnect and late completion | Persist an unknown/reconciliation-required state across timeout, process crash and restart. Correlate late provider completion, webhook and polling evidence to the same exact operation. Prove completion before/after retry, duplicate and out-of-order events, and no second delete or premature success. A transport timeout is not proof of provider rollback. | +| Local failure after provider success | Preserve the provider outcome durably and expose reconciliation-required status. Inject failure at every local write/commit boundary. Specify exact forward reconciliation or a provider-supported compensation that restores the same IDs, memberships, roles, seats, grants, provenance and dependent resources. If exact restoration is impossible, document that limit and require a safe recovery workflow; never invent replacement identities or silently recreate approximate state. | +| Mandatory audit | Commit truthful intent/outcome records with the corresponding journal/local state transition; audit must survive cascades and identify the exact credential, target and operation. Audit failure blocks success. Prove failures before provider dispatch and after provider completion, without falsely claiming deletion or losing the provider outcome. | +| Replay and recovery | Same key plus same actor/target/payload returns the same durable operation/outcome; conflicting reuse fails. Prove retries after every crash boundary, concurrent duplicate requests, worker lease expiry and restarts. Neither replay nor a stale session may create new authority or repeat an irreversible provider effect. | +| Concurrent subscription creation | Coordinate deletion with checkout, invoice, admin, webhook, sync and subscription writers using a shared durable fence/version protocol. Prove both orderings: subscription wins and deletion refuses without provider effects; deletion reserves the organization and subsequent subscription creation cannot attach or complete unnoticed. Include an in-flight remote subscription that completes after local checks. Locking only the deletion route is insufficient. | +| Concurrent membership/identity changes | Coordinate with membership, grants, owner changes, link/unlink, epoch and ban writers. Preserve historical provenance and reject stale authority without borrowing a sibling. Document unavoidable provider compare-and-swap limits and reconcile them honestly. | +| Local dependent state, cache and notifications | Inventory every cascade/set-null/restrict edge and retained audit/journal record. Make local transitions atomic and bind cache invalidation/notifications to committed outcomes with durable delivery/deduplication. Prove no premature success notifications, missed invalidation or cross-organization effects. | +| 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. diff --git a/server/src/middleware/organization-authorization-observer.ts b/server/src/middleware/organization-authorization-observer.ts index 81412ec6113..fd1e5de73c3 100644 --- a/server/src/middleware/organization-authorization-observer.ts +++ b/server/src/middleware/organization-authorization-observer.ts @@ -8,10 +8,16 @@ const logger = createLogger('organization-authorization-observer'); const MAX_CONCURRENT_COMPARISONS = 5; let inFlightComparisons = 0; -// Exact membership mutations have their own mandatory authority checks. Do not -// make additional canonical-credential provider reads after those requests, -// including authentication/preflight denials. This server-only marker changes -// observation only; it never supplies or bypasses authorization. +// Two kinds of request opt out of post-response observation. Exact membership +// mutations have their own mandatory authority checks, and the #6827 contained +// organization-deletion routes deliberately have no authority checks at all +// because they return before authentication. Neither should trigger additional +// canonical-credential provider reads afterwards, including on +// authentication/preflight denials and on an already populated principal. +// Exclusion therefore does NOT imply an authority check ran. This server-only +// marker changes observation only; it never supplies or bypasses authorization. +// Re-enabling organization deletion must drop its exclusion so the +// canonical-vs-exact shadow telemetry covers the route again. const excludedRequests = new WeakSet(); export const excludeOrganizationAuthorizationObservation: RequestHandler = (req, _res, next) => { excludedRequests.add(req); diff --git a/server/src/routes/admin/accounts-billing.ts b/server/src/routes/admin/accounts-billing.ts index f6fdc101909..c4c90c8d2eb 100644 --- a/server/src/routes/admin/accounts-billing.ts +++ b/server/src/routes/admin/accounts-billing.ts @@ -4,7 +4,7 @@ * Billing and lifecycle actions for accounts: * - Sync organization data from WorkOS and Stripe * - Get payment history - * - Delete workspace (only when no payment history or active subscription) + * - Workspace deletion is temporarily unavailable (#6827) */ import { Router } from "express"; @@ -12,6 +12,7 @@ import { WorkOS } from "@workos-inc/node"; import Stripe from "stripe"; import { getPool } from "../../db/client.js"; import { createLogger } from "../../logger.js"; +import { excludeOrganizationAuthorizationObservation } from "../../middleware/organization-authorization-observer.js"; import { requireAuth, requireAdmin } from "../../middleware/auth.js"; import { OrganizationDatabase, @@ -551,125 +552,17 @@ export function setupAccountsBillingRoutes( } ); - // DELETE /api/admin/accounts/:orgId - Delete a workspace - // Blocked if the org has any payment history or an active subscription. + // #6827: force-delete has the same lifecycle containment as self-service. + // Do not authenticate/hydrate, resolve admin authority, inspect billing, + // record a deletion audit or call providers without a durable journal and + // exact reconciliation contract. No credential or admin role bypasses this. apiRouter.delete( "/accounts/:orgId", - requireAuth, - requireAdmin, - async (req, res) => { - const { orgId } = req.params; - const { confirmation } = req.body; - - try { - const pool = getPool(); - - const orgResult = await pool.query( - "SELECT workos_organization_id, name, stripe_customer_id FROM organizations WHERE workos_organization_id = $1", - [orgId] - ); - - if (orgResult.rows.length === 0) { - return res.status(404).json({ - error: "Organization not found", - message: "The specified organization does not exist", - }); - } - - const org = orgResult.rows[0]; - - const revenueResult = await pool.query( - "SELECT COUNT(*) as count FROM revenue_events WHERE workos_organization_id = $1", - [orgId] - ); - - const hasPayments = parseInt(revenueResult.rows[0].count) > 0; - - if (hasPayments) { - return res.status(400).json({ - error: "Cannot delete paid workspace", - message: - "This workspace has payment history and cannot be deleted. Contact support if you need to remove this workspace.", - has_payments: true, - }); - } - - const orgDb = new OrganizationDatabase(); - const subscriptionInfo = await orgDb.getSubscriptionInfo(orgId); - if ( - subscriptionInfo && - (subscriptionInfo.status === "active" || - subscriptionInfo.status === "past_due") - ) { - return res.status(400).json({ - error: "Cannot delete workspace with active subscription", - message: - "This workspace has an active subscription. Please cancel the subscription first before deleting the workspace.", - has_active_subscription: true, - subscription_status: subscriptionInfo.status, - }); - } - - if (!confirmation || confirmation !== org.name) { - return res.status(400).json({ - error: "Confirmation required", - message: `To delete this workspace, please provide the exact name "${org.name}" in the confirmation field.`, - requires_confirmation: true, - organization_name: org.name, - }); - } - - await orgDb.recordAuditLog({ - workos_organization_id: orgId, - workos_user_id: req.user!.id, - action: "organization_deleted", - resource_type: "organization", - resource_id: orgId, - details: { - name: org.name, - deleted_by: "admin", - admin_email: req.user!.email, - }, - }); - - if (workos) { - try { - await workos.organizations.deleteOrganization(orgId); - logger.info( - { orgId, name: org.name, adminEmail: req.user!.email }, - "Deleted organization from WorkOS" - ); - } catch (workosError) { - logger.warn( - { err: workosError, orgId }, - "Failed to delete organization from WorkOS - continuing with local deletion" - ); - } - } - - await pool.query( - "DELETE FROM organizations WHERE workos_organization_id = $1", - [orgId] - ); - - logger.info( - { orgId, name: org.name, adminEmail: req.user!.email }, - "Admin deleted organization" - ); - - res.json({ - success: true, - message: `Workspace "${org.name}" has been deleted`, - deleted_org_id: orgId, - }); - } catch (error) { - logger.error({ err: error, orgId }, "Error deleting organization"); - res.status(500).json({ - error: "Internal server error", - message: "Unable to delete organization", - }); - } - } + excludeOrganizationAuthorizationObservation, + (_req, res) => res.status(503).json({ + error: "organization_deletion_unavailable", + message: "Organization deletion is temporarily unavailable.", + }) ); // POST /api/admin/accounts/:orgId/reset-subscription-state diff --git a/server/src/routes/organizations.ts b/server/src/routes/organizations.ts index 93bbd77b33e..2f55aec3419 100644 --- a/server/src/routes/organizations.ts +++ b/server/src/routes/organizations.ts @@ -8,6 +8,7 @@ import { respondToAdminAuthorizationError } from '../auth/admin-authorization-re */ import { Router, type Request } from "express"; +import { excludeOrganizationAuthorizationObservation } from "../middleware/organization-authorization-observer.js"; import { registerOrganizationMembershipMutations } from "./organization-membership-mutations.js"; import { WorkOS } from "@workos-inc/node"; import { getPool, query } from "../db/client.js"; @@ -1182,119 +1183,15 @@ export function createOrganizationsRouter(): Router { } }); - // DELETE /api/organizations/:orgId - Delete own workspace (owner only) - // Cannot delete if workspace has any payment history - router.delete('/:orgId', requireAuth, async (req, res) => { - try { - const user = req.user!; - const { orgId } = req.params; - const { confirmation } = req.body; - - // Verify user is owner of this organization - const membership = await resolveUserOrgMembership(workos, user.id, orgId); - if (!membership) { - return res.status(403).json({ - error: 'Access denied', - message: 'You are not a member of this organization', - }); - } - - // Only owners can delete - const userRole = membership.role; - if (userRole !== 'owner') { - return res.status(403).json({ - error: 'Insufficient permissions', - message: 'Only the organization owner can delete the workspace', - }); - } - - // Get organization from database - const pool = getPool(); - const orgResult = await pool.query( - 'SELECT workos_organization_id, name, stripe_customer_id FROM organizations WHERE workos_organization_id = $1', - [orgId] - ); - - if (orgResult.rows.length === 0) { - return res.status(404).json({ - error: 'Organization not found', - message: 'The specified organization does not exist', - }); - } - - const org = orgResult.rows[0]; - - // Check if organization has any payment history - const revenueResult = await pool.query( - 'SELECT COUNT(*) as count FROM revenue_events WHERE workos_organization_id = $1', - [orgId] - ); - - const hasPayments = parseInt(revenueResult.rows[0].count) > 0; - - if (hasPayments) { - return res.status(400).json({ - error: 'Cannot delete paid workspace', - message: 'This workspace has payment history and cannot be deleted. Please contact support if you need to remove this workspace.', - has_payments: true, - }); - } - - // Check for active subscription (checks both Stripe and local DB) - const subscriptionInfo = await orgDb.getSubscriptionInfo(orgId); - if (subscriptionInfo && (subscriptionInfo.status === 'active' || subscriptionInfo.status === 'past_due')) { - return res.status(400).json({ - error: 'Cannot delete workspace with active subscription', - message: 'This workspace has an active subscription. Please cancel the subscription first before deleting the workspace.', - has_active_subscription: true, - subscription_status: subscriptionInfo.status, - }); - } - - // Require confirmation by typing the organization name - if (!confirmation || confirmation !== org.name) { - return res.status(400).json({ - error: 'Confirmation required', - message: `To delete this workspace, please provide the exact name "${org.name}" in the confirmation field.`, - requires_confirmation: true, - organization_name: org.name, - }); - } - - // Record audit log before deletion (while org still exists) - await orgDb.recordAuditLog({ - workos_organization_id: orgId, - workos_user_id: user.id, - action: 'organization_deleted', - resource_type: 'organization', - resource_id: orgId, - details: { name: org.name, deleted_by: 'self_service', user_email: user.email }, - }); - - // Delete from WorkOS - try { - await workos!.organizations.deleteOrganization(orgId); - logger.info({ orgId, name: org.name, userId: user.id }, 'Deleted organization from WorkOS'); - } catch (workosError) { - logger.warn({ err: workosError, orgId }, 'Failed to delete organization from WorkOS - continuing with local deletion'); - } - - // Delete from local database (cascades to related tables) - await pool.query('DELETE FROM organizations WHERE workos_organization_id = $1', [orgId]); - - logger.info({ orgId, name: org.name, userId: user.id, userEmail: user.email }, 'User deleted their own organization'); - - res.json({ - success: true, - message: `Workspace "${org.name}" has been deleted`, - deleted_org_id: orgId, - }); - } catch (error) { - logger.error({ err: error }, 'Delete organization error'); - res.status(500).json({ - error: 'Failed to delete organization', - }); - } + // #6827: deletion is unavailable until a durable lifecycle journal and exact + // reconciliation contract exist. Return before auth (which can hydrate local + // identity/cache state), authority/subscription reads, audit or provider work. + // This generic response exposes no organization data and has no role bypass. + router.delete('/:orgId', excludeOrganizationAuthorizationObservation, (_req, res) => { + return res.status(503).json({ + error: 'organization_deletion_unavailable', + message: 'Organization deletion is temporarily unavailable.', + }); }); // ========================================================================= diff --git a/server/tests/integration/admin-endpoints.test.ts b/server/tests/integration/admin-endpoints.test.ts index 83586ff8385..f5b5a9e4f7e 100644 --- a/server/tests/integration/admin-endpoints.test.ts +++ b/server/tests/integration/admin-endpoints.test.ts @@ -244,9 +244,18 @@ describe('Admin Endpoints Integration Tests', () => { }); }); - describe('DELETE /api/admin/accounts/:orgId', () => { + // #6827: administrative force-delete has the same containment as self-service. + // The fixtures below keep the former decision inputs (unknown organization, + // confirmation text, payment history, active subscription) to prove none of + // them change the response or mutate stored rows, and that admin authority is + // not an exception. + describe('DELETE /api/admin/accounts/:orgId (contained)', () => { const DELETE_TEST_ORG_ID = 'org_delete_test'; const DELETE_TEST_PAID_ORG_ID = 'org_delete_test_paid'; + const unavailable = { + error: 'organization_deletion_unavailable', + message: 'Organization deletion is temporarily unavailable.', + }; beforeEach(async () => { // Create test organizations for delete tests @@ -275,75 +284,71 @@ describe('Admin Endpoints Integration Tests', () => { afterEach(async () => { // Clean up test data + await pool.query('DELETE FROM member_profiles WHERE workos_organization_id = $1', [DELETE_TEST_ORG_ID]); await pool.query('DELETE FROM revenue_events WHERE workos_organization_id = $1', [DELETE_TEST_PAID_ORG_ID]); await pool.query('DELETE FROM organizations WHERE workos_organization_id IN ($1, $2)', [DELETE_TEST_ORG_ID, DELETE_TEST_PAID_ORG_ID]); }); - it('should return 404 for non-existent organization', async () => { + async function expectContained(orgId: string, body: unknown) { const response = await request(app) - .delete('/api/admin/accounts/org_nonexistent') - .send({ confirmation: 'Some Name' }) - .expect(404); + .delete(`/api/admin/accounts/${orgId}`) + .send(body as object) + .expect(503); - expect(response.body.error).toBe('Organization not found'); - }); + expect(response.body).toEqual(unavailable); + return response; + } - it('should require confirmation to delete', async () => { - const response = await request(app) - .delete(`/api/admin/accounts/${DELETE_TEST_ORG_ID}`) - .send({}) - .expect(400); + async function orgRow(orgId: string) { + const result = await pool.query( + 'SELECT to_jsonb(o) AS row FROM organizations o WHERE workos_organization_id = $1', + [orgId] + ); + return result.rows[0]?.row ?? null; + } - expect(response.body.error).toBe('Confirmation required'); - expect(response.body.requires_confirmation).toBe(true); - expect(response.body.organization_name).toBe('Delete Test Org'); + it('returns the contained response for a non-existent organization', async () => { + // The former 404 leaked organization existence; the contained response does not. + const response = await expectContained('org_nonexistent', { confirmation: 'Some Name' }); + expect(response.body.error).not.toBe('Organization not found'); }); - it('should reject wrong confirmation name', async () => { - const response = await request(app) - .delete(`/api/admin/accounts/${DELETE_TEST_ORG_ID}`) - .send({ confirmation: 'Wrong Name' }) - .expect(400); + it('returns the contained response without confirmation and discloses no org data', async () => { + const before = await orgRow(DELETE_TEST_ORG_ID); + const response = await expectContained(DELETE_TEST_ORG_ID, {}); - expect(response.body.error).toBe('Confirmation required'); + expect(response.body).not.toHaveProperty('organization_name'); + expect(response.body).not.toHaveProperty('requires_confirmation'); + expect(await orgRow(DELETE_TEST_ORG_ID)).toEqual(before); }); - it('should prevent deletion of organization with payment history', async () => { - const response = await request(app) - .delete(`/api/admin/accounts/${DELETE_TEST_PAID_ORG_ID}`) - .send({ confirmation: 'Paid Test Org' }) - .expect(400); + it('returns the contained response for a wrong confirmation name', async () => { + const before = await orgRow(DELETE_TEST_ORG_ID); + await expectContained(DELETE_TEST_ORG_ID, { confirmation: 'Wrong Name' }); + expect(await orgRow(DELETE_TEST_ORG_ID)).toEqual(before); + }); - expect(response.body.error).toBe('Cannot delete paid workspace'); - expect(response.body.has_payments).toBe(true); + it('returns the contained response for an organization with payment history', async () => { + const before = await orgRow(DELETE_TEST_PAID_ORG_ID); + const response = await expectContained(DELETE_TEST_PAID_ORG_ID, { confirmation: 'Paid Test Org' }); - // Verify org still exists - const checkResult = await pool.query( - 'SELECT 1 FROM organizations WHERE workos_organization_id = $1', + expect(response.body).not.toHaveProperty('has_payments'); + expect(await orgRow(DELETE_TEST_PAID_ORG_ID)).toEqual(before); + + const revenue = await pool.query( + 'SELECT COUNT(*)::int AS count FROM revenue_events WHERE workos_organization_id = $1', [DELETE_TEST_PAID_ORG_ID] ); - expect(checkResult.rows.length).toBe(1); + expect(revenue.rows[0].count).toBe(1); }); - it('should successfully delete unpaid organization with correct confirmation', async () => { - const response = await request(app) - .delete(`/api/admin/accounts/${DELETE_TEST_ORG_ID}`) - .send({ confirmation: 'Delete Test Org' }) - .expect(200); - - expect(response.body.success).toBe(true); - expect(response.body.deleted_org_id).toBe(DELETE_TEST_ORG_ID); - - // Verify org is deleted - const checkResult = await pool.query( - 'SELECT 1 FROM organizations WHERE workos_organization_id = $1', - [DELETE_TEST_ORG_ID] - ); - expect(checkResult.rows.length).toBe(0); + it('does not delete an unpaid organization even with the exact confirmation', async () => { + const before = await orgRow(DELETE_TEST_ORG_ID); + await expectContained(DELETE_TEST_ORG_ID, { confirmation: 'Delete Test Org' }); + expect(await orgRow(DELETE_TEST_ORG_ID)).toEqual(before); }); - it('should cascade delete related member profiles', async () => { - // Create a member profile for the test org + it('does not cascade into related member profiles', async () => { await pool.query( `INSERT INTO member_profiles (workos_organization_id, display_name, slug, created_at, updated_at) VALUES ($1, $2, $3, NOW(), NOW()) @@ -351,32 +356,16 @@ describe('Admin Endpoints Integration Tests', () => { [DELETE_TEST_ORG_ID, 'Test Profile', 'test-profile'] ); - // Verify profile exists - const beforeResult = await pool.query( - 'SELECT 1 FROM member_profiles WHERE workos_organization_id = $1', - [DELETE_TEST_ORG_ID] - ); - expect(beforeResult.rows.length).toBe(1); + await expectContained(DELETE_TEST_ORG_ID, { confirmation: 'Delete Test Org' }); - // Delete the organization - await request(app) - .delete(`/api/admin/accounts/${DELETE_TEST_ORG_ID}`) - .send({ confirmation: 'Delete Test Org' }) - .expect(200); - - // Verify profile is cascaded deleted const afterResult = await pool.query( 'SELECT 1 FROM member_profiles WHERE workos_organization_id = $1', [DELETE_TEST_ORG_ID] ); - expect(afterResult.rows.length).toBe(0); + expect(afterResult.rows.length).toBe(1); }); - // OrganizationDatabase.getSubscriptionInfo reads subscription_status from the DB row; - // mocking the stripe-client import has no effect. Seed the column directly. - // The active-subscription guard applies to admin-initiated deletes too; force-deletion - // of a subscribed org requires a DB-level intervention (clear subscription_status). - it('should prevent deletion of organization with active subscription', async () => { + it('returns the contained response for an organization with an active subscription', async () => { const SUB_ORG_ID = 'org_delete_test_sub'; await pool.query( `INSERT INTO organizations (workos_organization_id, name, subscription_status, created_at, updated_at) @@ -385,21 +374,11 @@ describe('Admin Endpoints Integration Tests', () => { [SUB_ORG_ID, 'Subscribed Test Org'] ); - const response = await request(app) - .delete(`/api/admin/accounts/${SUB_ORG_ID}`) - .send({ confirmation: 'Subscribed Test Org' }) - .expect(400); - - expect(response.body.error).toBe('Cannot delete workspace with active subscription'); - expect(response.body.has_active_subscription).toBe(true); - expect(response.body.subscription_status).toBe('active'); + const before = await orgRow(SUB_ORG_ID); + const response = await expectContained(SUB_ORG_ID, { confirmation: 'Subscribed Test Org' }); - // Verify org still exists - const checkResult = await pool.query( - 'SELECT 1 FROM organizations WHERE workos_organization_id = $1', - [SUB_ORG_ID] - ); - expect(checkResult.rows.length).toBe(1); + expect(response.body).not.toHaveProperty('subscription_status'); + expect(await orgRow(SUB_ORG_ID)).toEqual(before); // SUB_ORG_ID is not covered by the inner afterEach; clean up inline. await pool.query('DELETE FROM organizations WHERE workos_organization_id = $1', [SUB_ORG_ID]); diff --git a/server/tests/integration/organization-deletion-containment.test.ts b/server/tests/integration/organization-deletion-containment.test.ts new file mode 100644 index 00000000000..d8ac2ff96ed --- /dev/null +++ b/server/tests/integration/organization-deletion-containment.test.ts @@ -0,0 +1,299 @@ +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 = 'deletion-test-static-key'; + process.env.ADMIN_EMAILS = 'sam@deletion.example.test'; + return { + members: [] as any[], users: new Map(), sessions: new Map(), + calls: [] as string[], platformAdmin: false, + }; +}); +vi.mock('@workos-inc/node', () => ({ WorkOS: class { + authorization = { listOrganizationRoles: vi.fn(async () => { state.calls.push('roles'); return { data: [{ slug: 'owner', name: 'Owner' }, { slug: 'admin', name: 'Admin' }, { slug: 'member', name: 'Member' }] }; }) }; + organizations = { deleteOrganization: vi.fn(async (id: string) => { state.calls.push(`delete:${id}`); }) }; + apiKeys = { createValidation: vi.fn(async () => { state.calls.push('api_key'); throw new Error('Unexpected API key validation'); }) }; + userManagement = { + loadSealedSession: ({ sessionData }: any) => { + state.calls.push('session'); + return { authenticate: async () => state.sessions.get(sessionData) ?? { authenticated: false }, refresh: async () => ({ authenticated: false }) }; + }, + listOrganizationMemberships: vi.fn(async ({ userId, organizationId }: any) => { + state.calls.push(`memberships:${userId}`); + return { data: structuredClone(state.members.filter(m => (!userId || m.userId === userId) && (!organizationId || m.organizationId === organizationId))) }; + }), + getUser: vi.fn(async (id: string) => { state.calls.push(`user:${id}`); return state.users.get(id); }), + }; +} })); +vi.mock('../../src/addie/mcp/admin-tools.js', () => ({ isWebUserAAOAdmin: vi.fn(async () => state.platformAdmin) })); +// HTTPServer supplies the production cookie/CSRF/organization route ordering. Keep unrelated +// route graphs inert so this focused harness does not initialize Addie indexes or agent tenants. +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 * as stripeClient from '../../src/billing/stripe-client.js'; +import * as auth from '../../src/middleware/auth.js'; +import * as orgFilters from '../../src/db/org-filters.js'; +import * as addie from '../../src/addie/index.js'; +import * as notifications from '../../src/services/organization-membership-notifications.js'; +import * as slack from '../../src/slack/org-group-dm.js'; +import { OrganizationDatabase } from '../../src/db/organization-db.js'; + +const org = 'org_deletion_test'; +const otherOrg = 'org_deletion_other'; +const A = 'user_deletion_a'; +const B = 'user_deletion_b'; +const CSRF = 'd'.repeat(64); +const unavailable = { error: 'organization_deletion_unavailable', message: 'Organization deletion is temporarily unavailable.' }; +const paths = [`/api/organizations/${org}`, `/api/admin/accounts/${org}`]; +let pool: Pool; +let app: Parameters[0]; +let signingKey: Awaited>['privateKey']; +let sequence = 0; + +async function token(actor = A, selected: string | null = org) { + return new SignJWT({ client_id: 'client_mock_id', ...(selected ? { org_id: selected } : {}) }) + .setProtectedHeader({ alg: 'RS256' }).setSubject(actor).setIssuedAt().setJti(String(++sequence)).setExpirationTime('5m').sign(signingKey); +} +async function cookie(actor = A, selected: string | null = org) { + const id = `deletion_session_${++sequence}`; + state.sessions.set(id, { authenticated: true, user: state.users.get(actor), accessToken: await token(actor, selected) }); + return `wos-session=${id}; csrf-token=${CSRF}`; +} +async function member(userId: string, role = 'owner', organizationId = org) { + const id = `om_${userId}_${organizationId}`; + state.members = state.members.filter(m => m.id !== id); + state.members.push({ id, userId, organizationId, status: 'active', role: { slug: role } }); + await pool.query(`INSERT INTO organization_memberships (workos_user_id,workos_organization_id,workos_membership_id,email,role) + VALUES ($1,$2,$3,$4,$5) ON CONFLICT (workos_user_id,workos_organization_id) DO UPDATE SET role=$5`, [userId,organizationId,id,state.users.get(userId).email,role]); +} +async function snapshot() { + const result: Record = {}; + // Full rows catch cascades, grants/provenance rewrites, audit and unrelated changes. + for (const table of ['organizations','users','identity_workos_users','organization_memberships','organization_domains', + 'organization_credential_grants','organization_join_requests','invitation_seat_types','seat_upgrade_requests', + 'registry_audit_log','revenue_events','working_group_memberships','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; +} +async function assertContained(path: string, headers: Record, body: unknown = { confirmation: 'Pinnacle Agency' }) { + const before = await snapshot(); + const providerBefore = structuredClone(state.members); + state.calls = []; + const querySpy = vi.spyOn(pool, 'query'); + const connectSpy = vi.spyOn(pool, 'connect'); + const auditSpy = vi.spyOn(OrganizationDatabase.prototype, 'recordAuditLog'); + const billingSpy = vi.spyOn(OrganizationDatabase.prototype, 'getSubscriptionInfo'); + const stripeSpy = vi.spyOn(stripeClient, 'getStripeSubscriptionInfo'); + const cacheSpies = [vi.spyOn(auth, 'invalidateSessionCache'), vi.spyOn(orgFilters, 'invalidateMembershipCache')]; + let response; + try { + response = await request(app).delete(path).set(headers).send(body as object); + // Include the real response-finish observer; do not mock it inert. + await new Promise(resolve => setImmediate(resolve)); + expect(response.status, JSON.stringify({ body: response.body, providerCalls: state.calls })).toBe(503); + expect(response.body).toEqual(unavailable); + expect(state.calls).toEqual([]); + expect(querySpy).not.toHaveBeenCalled(); + expect(connectSpy).not.toHaveBeenCalled(); + expect(auditSpy).not.toHaveBeenCalled(); + expect(billingSpy).not.toHaveBeenCalled(); + expect(stripeSpy).not.toHaveBeenCalled(); + for (const spy of cacheSpies) expect(spy).not.toHaveBeenCalled(); + for (const spy of [addie.sendAccountLinkedMessage, addie.invalidateMemberContextCache, + notifications.notifyMembershipSeats, notifications.notifyMembershipSeatRequest, slack.notifyMemberSeatChanged]) expect(spy).not.toHaveBeenCalled(); + } finally { + querySpy.mockRestore(); connectSpy.mockRestore(); auditSpy.mockRestore(); billingSpy.mockRestore(); stripeSpy.mockRestore(); + for (const spy of cacheSpies) spy.mockRestore(); + } + expect(await snapshot()).toEqual(before); + expect(state.members).toEqual(providerBefore); + return response; +} +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('Deletion 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() { + // organization_memberships has no foreign key to organizations or users, and + // identities outlive the cascade from users, so both need explicit cleanup. + // Without it the local owner/admin rows from one case bleed into the next — + // the grant-only and anonymous cases would silently run with a leftover + // membership — and rows leak into the shared test database. + const identities = (await pool.query( + 'SELECT identity_id FROM identity_workos_users WHERE workos_user_id = ANY($1)', [[A,B]] + )).rows.map(row => row.identity_id); + await pool.query('DELETE FROM registry_audit_log WHERE workos_organization_id = ANY($1)', [[org,otherOrg]]); + await pool.query('DELETE FROM working_group_memberships WHERE workos_user_id = ANY($1)', [[A,B]]); + await pool.query('DELETE FROM organization_memberships WHERE workos_user_id = ANY($1) OR workos_organization_id = ANY($2)', [[A,B],[org,otherOrg]]); + await pool.query('DELETE FROM organizations WHERE workos_organization_id = ANY($1)', [[org,otherOrg]]); + await pool.query('DELETE FROM users WHERE workos_user_id = ANY($1)', [[A,B]]); + 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.members = []; state.users.clear(); state.sessions.clear(); state.platformAdmin = false; + for (const id of [A,B]) invalidateBanCache('user',id); + await cleanFixtures(); + for (const id of [org,otherOrg]) await pool.query("INSERT INTO organizations (workos_organization_id,name,is_personal) VALUES ($1,'Pinnacle Agency',false)", [id]); + for (const id of [A,B]) { + const user = { id, email: id === A ? 'sam@deletion.example.test' : 'alex@deletion.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',org]); + } + // Re-linking A onto B's identity orphans the identity the insert trigger just + // made for A, so drop it here; cleanFixtures only sees the surviving link. + const identity = (await pool.query('SELECT identity_id FROM identity_workos_users WHERE workos_user_id=$1',[B])).rows[0].identity_id; + const orphaned = (await pool.query('SELECT identity_id FROM identity_workos_users WHERE workos_user_id=$1',[A])).rows[0].identity_id; + await pool.query('UPDATE identity_workos_users SET identity_id=$1,is_primary=false WHERE workos_user_id=$2',[identity,A]); + if (orphaned !== identity) await pool.query('DELETE FROM identities WHERE id=$1',[orphaned]); + await pool.query("INSERT INTO organization_domains (workos_organization_id,domain,verified) VALUES ($1,'deletion.example.test',true)",[org]); +}); + +describe('mounted organization deletion lifecycle containment', () => { + for (const path of paths) { + for (const [actor,sibling] of [[A,B],[B,A]]) it(`${path}: linked ${actor} cannot borrow sibling owner`, async () => { + // Make the sibling canonical in both directions, not just linked. + await pool.query('UPDATE identity_workos_users SET is_primary=false WHERE workos_user_id = ANY($1)',[[A,B]]); + await pool.query('UPDATE identity_workos_users SET is_primary=true WHERE workos_user_id=$1',[sibling]); + await member(sibling); + await assertContained(path, { Cookie: await cookie(actor), 'X-CSRF-Token': CSRF, 'X-Organization-Id': org }); + }); + for (const role of ['owner','admin','member']) it(`${path}: exact ${role} cannot bypass`, async () => { + await member(A,role); + await assertContained(path, { Cookie: await cookie(), 'X-CSRF-Token': CSRF, 'X-Organization-Id': org }); + }); + it(`${path}: platform admin cannot bypass`, async () => { + state.platformAdmin = true; + const platform = 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(platform.rowCount).toBe(1); + await assertContained(path, { Cookie: await cookie(), 'X-CSRF-Token': CSRF }); + }); + it(`${path}: grant-only, email/domain and primary organization cannot bypass`, async () => { + await pool.query("INSERT INTO organization_credential_grants (workos_organization_id,workos_user_id,role,granted_by_workos_user_id) VALUES ($1,$2,'owner',$3)",[org,A,B]); + await assertContained(path, { Cookie: await cookie(), 'X-CSRF-Token': CSRF }); + }); + for (const bearer of ['deletion-test-static-key','sk_workos_tenant_key','invalid']) it(`${path}: ${bearer} cannot bypass or trigger credential validation`, async () => { + await assertContained(path, { Authorization: `Bearer ${bearer}` }); + }); + for (const selected of [org,otherOrg,null]) it(`${path}: JWT selected ${selected} and conflicting selectors do not select a deletion`, async () => { + await member(A); await member(B,'owner',otherOrg); + await assertContained(`${path}?org=${otherOrg}&organization_id=${otherOrg}`, { + Authorization: `Bearer ${await token(A,selected)}`, 'X-Organization-Id': otherOrg, + }, { confirmation: 'Pinnacle Agency', organization_id: otherOrg, organizationId: [org,otherOrg], orgId: otherOrg, force: true }); + }); + for (const status of [null,'active','past_due','trialing','canceled']) it(`${path}: subscription ${status} cannot bypass or trigger Stripe`, async () => { + await member(A); + await pool.query("UPDATE organizations SET subscription_status=$1,stripe_customer_id='cus_deletion_spy' WHERE workos_organization_id=$2",[status,org]); + await assertContained(path, { Cookie: await cookie(), 'X-CSRF-Token': CSRF }); + }); + it(`${path}: unknown organization and absent confirmation return the same contract`, async () => { + await assertContained(path.replace(org,'org_deletion_missing'), { Authorization: `Bearer ${await token()}` }, {}); + }); + it(`${path}: replay and concurrent requests stay effect-free`, async () => { + await member(A); + const headers = { Authorization: `Bearer ${await token()}` }; + const before = await snapshot(); + const responses = await Promise.all(Array.from({length: 4}, () => request(app).delete(path).set(headers).send({ confirmation: 'Pinnacle Agency' }))); + for (const response of responses) { expect(response.status).toBe(503); expect(response.body).toEqual(unavailable); } + expect(state.calls).toEqual([]); expect(await snapshot()).toEqual(before); + await assertContained(path,headers); + }); + it(`${path}: cookie CSRF rejection still precedes route handling`, async () => { + const before = await snapshot(); + const response = await request(app).delete(path).set('Cookie',await cookie()).send({ confirmation: 'Pinnacle Agency' }); + expect(response.status).toBe(403); expect(response.body.error).toBe('CSRF validation failed'); + expect(state.calls).toEqual([]); expect(await snapshot()).toEqual(before); + }); + it(`${path}: anonymous callers with valid CSRF get no organization information`, async () => { + await assertContained(path, { Cookie: `csrf-token=${CSRF}`, 'X-CSRF-Token': CSRF }); + }); + } + for (const path of ['/api/organizations', '/api/admin/accounts', `/api/organizations/${org}/unmounted-deletion-path`, `/api/admin/accounts/${org}/unmounted-deletion-path`]) { + it(`unmounted DELETE ${path} stays 404`, async () => { + const response = await request(app).delete(path).set('Cookie',`csrf-token=${CSRF}`).set('X-CSRF-Token',CSRF).send({}); + expect(response.status,JSON.stringify(response.body)).toBe(404); + expect(response.body.error).not.toBe(unavailable.error); + expect(state.calls).toEqual([]); + }); + } + for (const path of [`/api/organizations/${org}/roles`, `/api/organizations/${org}/domains`, `/api/admin/accounts/${org}/payments`]) { + it(`neighboring GET ${path} still requires authentication`, async () => { + const response = await request(app).get(path); + expect(response.status,JSON.stringify(response.body)).toBe(401); + expect(response.body.error).not.toBe(unavailable.error); + }); + } + // Both neighbours share the contained prefix and need an extra path segment, so they + // prove the containment route match was not broadened over sibling mutations. + for (const path of [`/api/organizations/${org}/members/om_protected`, + `/api/admin/accounts/${org}/agents/${encodeURIComponent('https://agent.deletion.example.test')}`]) { + it(`neighboring DELETE ${path} still requires authentication`, async () => { + const response = await request(app).delete(path).set('Cookie',`csrf-token=${CSRF}`).set('X-CSRF-Token',CSRF).send({}); + expect(response.status,JSON.stringify(response.body)).toBe(401); + expect(response.body.error).not.toBe(unavailable.error); + }); + } + it('read-only organization roles remain available through real authentication', async () => { + await member(A); await member(B); + const response = await request(app).get(`/api/organizations/${org}/roles`).set('Cookie',await cookie()); + expect(response.status,JSON.stringify(response.body)).toBe(200); + expect(response.body.roles.length).toBeGreaterThan(0); + expect(state.calls).toContain('session'); + expect(state.calls.some(c => c.startsWith('delete:'))).toBe(false); + }); +}); diff --git a/server/tests/integration/self-service-delete.test.ts b/server/tests/integration/self-service-delete.test.ts index d5b51f8d5c5..d9d90b35f1a 100644 --- a/server/tests/integration/self-service-delete.test.ts +++ b/server/tests/integration/self-service-delete.test.ts @@ -141,40 +141,64 @@ describe('Self-Service Delete Workspace', () => { await pool.query('DELETE FROM organizations WHERE workos_organization_id = $1', ['org_member_only']); }); - describe('DELETE /api/organizations/:orgId', () => { - // Handler returns 403 Access denied for non-existent orgs: membership check runs - // before existence check, so callers cannot enumerate org IDs by probing deletions. - it('should return 403 when the requesting user has no membership in the org', async () => { - const response = await request(app) - .delete('/api/organizations/org_nonexistent') - .send({ confirmation: 'Some Name' }) - .expect(403); + // #6827: self-service deletion is contained. Every request reaching the route + // gets one stable temporary-unavailable response before provider, database, + // cache, notification or audit work. These cases keep the original fixtures so + // the former decision inputs (confirmation text, payment history, active + // subscription, non-owner role, unknown organization) are proven not to change + // the outcome and not to mutate stored rows. + describe('DELETE /api/organizations/:orgId (contained)', () => { + const unavailable = { + error: 'organization_deletion_unavailable', + message: 'Organization deletion is temporarily unavailable.', + }; - expect(response.body.error).toBe('Access denied'); + beforeEach(() => { + workosMocks.deleteOrganization.mockClear(); }); - it('should require confirmation to delete', async () => { + async function expectContained(orgId: string, body: unknown) { const response = await request(app) - .delete(`/api/organizations/${TEST_ORG_ID}`) - .send({}) - .expect(400); + .delete(`/api/organizations/${orgId}`) + .send(body as object) + .expect(503); + + expect(response.body).toEqual(unavailable); + expect(workosMocks.deleteOrganization).not.toHaveBeenCalled(); + return response; + } + + async function orgRow(orgId: string) { + const result = await pool.query( + 'SELECT to_jsonb(o) AS row FROM organizations o WHERE workos_organization_id = $1', + [orgId] + ); + return result.rows[0]?.row ?? null; + } - expect(response.body.error).toBe('Confirmation required'); - expect(response.body.requires_confirmation).toBe(true); - expect(response.body.organization_name).toBe('Self Delete Test Org'); + it('returns the same response for an organization the caller does not belong to', async () => { + // No membership lookup runs, so the response cannot be used to enumerate + // organization IDs and cannot be distinguished from the owner response. + await expectContained('org_nonexistent', { confirmation: 'Some Name' }); }); - it('should reject wrong confirmation name', async () => { - const response = await request(app) - .delete(`/api/organizations/${TEST_ORG_ID}`) - .send({ confirmation: 'Wrong Name' }) - .expect(400); + it('returns the contained response without confirmation and leaves the row intact', async () => { + const before = await orgRow(TEST_ORG_ID); + const response = await expectContained(TEST_ORG_ID, {}); + + // No organization name, confirmation prompt or other org data is disclosed. + expect(response.body).not.toHaveProperty('organization_name'); + expect(response.body).not.toHaveProperty('requires_confirmation'); + expect(await orgRow(TEST_ORG_ID)).toEqual(before); + }); - expect(response.body.error).toBe('Confirmation required'); + it('returns the contained response for a wrong confirmation name', async () => { + const before = await orgRow(TEST_ORG_ID); + await expectContained(TEST_ORG_ID, { confirmation: 'Wrong Name' }); + expect(await orgRow(TEST_ORG_ID)).toEqual(before); }); - it('should prevent deletion of organization with payment history', async () => { - // Create org with payment history + it('returns the contained response for an organization with payment history', async () => { const PAID_ORG_ID = 'org_self_delete_paid'; await pool.query( `INSERT INTO organizations (workos_organization_id, name, stripe_customer_id, created_at, updated_at) @@ -182,15 +206,14 @@ describe('Self-Service Delete Workspace', () => { ON CONFLICT (workos_organization_id) DO UPDATE SET name = $2, stripe_customer_id = $3`, [PAID_ORG_ID, 'Paid Org', 'cus_paid'] ); - - // Add a revenue event await pool.query( `INSERT INTO revenue_events (workos_organization_id, revenue_type, amount_paid, currency, paid_at) VALUES ($1, $2, $3, $4, NOW())`, [PAID_ORG_ID, 'subscription_initial', 2999, 'usd'] ); - // Override the WorkOS membership mock so this test's user owns PAID_ORG_ID. + // Owning PAID_ORG_ID no longer changes anything, but keep the fixture + // faithful to the authority the contained route used to accept. workosMocks.listOrganizationMemberships.mockImplementation(({ organizationId }: { organizationId: string }) => { if (organizationId === PAID_ORG_ID) { return Promise.resolve({ @@ -206,41 +229,27 @@ describe('Self-Service Delete Workspace', () => { return Promise.resolve({ data: [] }); }); - const response = await request(app) - .delete(`/api/organizations/${PAID_ORG_ID}`) - .send({ confirmation: 'Paid Org' }) - .expect(400); + const before = await orgRow(PAID_ORG_ID); + const response = await expectContained(PAID_ORG_ID, { confirmation: 'Paid Org' }); - expect(response.body.error).toBe('Cannot delete paid workspace'); - expect(response.body.has_payments).toBe(true); + // The payment-history verdict is no longer disclosed either. + expect(response.body).not.toHaveProperty('has_payments'); + expect(await orgRow(PAID_ORG_ID)).toEqual(before); - // Verify org still exists - const checkResult = await pool.query( - 'SELECT 1 FROM organizations WHERE workos_organization_id = $1', + const revenue = await pool.query( + 'SELECT COUNT(*)::int AS count FROM revenue_events WHERE workos_organization_id = $1', [PAID_ORG_ID] ); - expect(checkResult.rows.length).toBe(1); + expect(revenue.rows[0].count).toBe(1); }); - it('should successfully delete unpaid organization with correct confirmation', async () => { - const response = await request(app) - .delete(`/api/organizations/${TEST_ORG_ID}`) - .send({ confirmation: 'Self Delete Test Org' }) - .expect(200); - - expect(response.body.success).toBe(true); - expect(response.body.deleted_org_id).toBe(TEST_ORG_ID); - - // Verify org is deleted - const checkResult = await pool.query( - 'SELECT 1 FROM organizations WHERE workos_organization_id = $1', - [TEST_ORG_ID] - ); - expect(checkResult.rows.length).toBe(0); + it('does not delete an unpaid organization even with the exact confirmation', async () => { + const before = await orgRow(TEST_ORG_ID); + await expectContained(TEST_ORG_ID, { confirmation: 'Self Delete Test Org' }); + expect(await orgRow(TEST_ORG_ID)).toEqual(before); }); - it('should cascade delete related member profiles', async () => { - // Create a member profile for the test org + it('does not cascade into related member profiles', async () => { await pool.query( `INSERT INTO member_profiles (workos_organization_id, display_name, slug, created_at, updated_at) VALUES ($1, $2, $3, NOW(), NOW()) @@ -248,29 +257,16 @@ describe('Self-Service Delete Workspace', () => { [TEST_ORG_ID, 'Test Profile', 'test-profile-self-delete'] ); - // Verify profile exists - const beforeResult = await pool.query( - 'SELECT 1 FROM member_profiles WHERE workos_organization_id = $1', - [TEST_ORG_ID] - ); - expect(beforeResult.rows.length).toBe(1); - - // Delete the organization - await request(app) - .delete(`/api/organizations/${TEST_ORG_ID}`) - .send({ confirmation: 'Self Delete Test Org' }) - .expect(200); + await expectContained(TEST_ORG_ID, { confirmation: 'Self Delete Test Org' }); - // Verify profile is cascade deleted const afterResult = await pool.query( 'SELECT 1 FROM member_profiles WHERE workos_organization_id = $1', [TEST_ORG_ID] ); - expect(afterResult.rows.length).toBe(0); + expect(afterResult.rows.length).toBe(1); }); - it('should reject non-owner attempting to delete', async () => { - // Create org where user is only a member + it('returns the contained response for a non-owner member', async () => { const MEMBER_ORG_ID = 'org_member_only'; await pool.query( `INSERT INTO organizations (workos_organization_id, name, created_at, updated_at) @@ -279,19 +275,15 @@ describe('Self-Service Delete Workspace', () => { [MEMBER_ORG_ID, 'Member Only Org'] ); - const response = await request(app) - .delete(`/api/organizations/${MEMBER_ORG_ID}`) - .send({ confirmation: 'Member Only Org' }) - .expect(403); + const before = await orgRow(MEMBER_ORG_ID); + const response = await expectContained(MEMBER_ORG_ID, { confirmation: 'Member Only Org' }); - expect(response.body.error).toBe('Insufficient permissions'); + // A member and an owner are indistinguishable here; neither is permitted. + expect(response.body.error).not.toBe('Insufficient permissions'); + expect(await orgRow(MEMBER_ORG_ID)).toEqual(before); }); - // OrganizationDatabase.getSubscriptionInfo reads subscription_status from the DB row; - // mocking the stripe-client import has no effect. Seed the column directly. - // No stripe_customer_id needed: without it, getSubscriptionInfo returns localInfo - // (built from subscription_status) without ever consulting Stripe. - it('should prevent deletion of organization with active subscription', async () => { + it('returns the contained response for an organization with an active subscription', async () => { const SUB_ORG_ID = 'org_self_delete_sub'; await pool.query( `INSERT INTO organizations (workos_organization_id, name, subscription_status, created_at, updated_at) @@ -315,21 +307,11 @@ describe('Self-Service Delete Workspace', () => { return Promise.resolve({ data: [] }); }); - const response = await request(app) - .delete(`/api/organizations/${SUB_ORG_ID}`) - .send({ confirmation: 'Subscribed Org' }) - .expect(400); - - expect(response.body.error).toBe('Cannot delete workspace with active subscription'); - expect(response.body.has_active_subscription).toBe(true); - expect(response.body.subscription_status).toBe('active'); - - // Verify org still exists - const checkResult = await pool.query( - 'SELECT 1 FROM organizations WHERE workos_organization_id = $1', - [SUB_ORG_ID] - ); - expect(checkResult.rows.length).toBe(1); + const before = await orgRow(SUB_ORG_ID); + const response = await expectContained(SUB_ORG_ID, { confirmation: 'Subscribed Org' }); + + expect(response.body).not.toHaveProperty('subscription_status'); + expect(await orgRow(SUB_ORG_ID)).toEqual(before); }); }); }); diff --git a/server/tests/unit/organization-deletion-containment.test.ts b/server/tests/unit/organization-deletion-containment.test.ts new file mode 100644 index 00000000000..6b3e34b52af --- /dev/null +++ b/server/tests/unit/organization-deletion-containment.test.ts @@ -0,0 +1,66 @@ +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; + +const effects = vi.hoisted(() => ({ + auth: vi.fn(() => { throw new Error('Authentication must not hydrate a contained deletion'); }), + admin: vi.fn(() => { throw new Error('Admin resolution must not run'); }), + database: vi.fn(() => { throw new Error('Database must not be accessed'); }), + provider: vi.fn(() => { throw new Error('Provider must not be accessed'); }), +})); +vi.mock('@workos-inc/node', () => ({ WorkOS: class { + organizations = { deleteOrganization: effects.provider }; + userManagement = { listOrganizationMemberships: effects.provider }; +} })); +vi.mock('../../src/middleware/auth.js', async (importOriginal) => ({ + ...(await importOriginal()), + requireAuth: effects.auth, requireAdmin: effects.admin, +})); +vi.mock('../../src/db/client.js', async (importOriginal) => ({ + ...(await importOriginal()), + getPool: effects.database, query: effects.database, +})); +vi.mock('../../src/auth/workos-client.js', async (importOriginal) => ({ + ...(await importOriginal()), + getAuthorizationObserverWorkos: effects.provider, +})); + +import { createOrganizationsRouter } from '../../src/routes/organizations.js'; +import { setupAccountsBillingRoutes } from '../../src/routes/admin/accounts-billing.js'; +import { observeLinkedCredentialOrganizationAuthorization } from '../../src/middleware/organization-authorization-observer.js'; +import { stopAuthTimers } from '../../src/middleware/auth.js'; + +function app(providerPresent: boolean) { + const app = express(); + app.use(express.json()); + // A prehydrated linked principal must not trigger the finish observer either. + app.use((req, res, next) => { + req.user = { id: 'user_b', authWorkosUserId: 'user_a' } as express.Request['user']; + res.on('finish', () => { void observeLinkedCredentialOrganizationAuthorization(req, `DELETE ${req.path}`, res.statusCode); }); + next(); + }); + app.use('/api/organizations', createOrganizationsRouter()); + const admin = express.Router(); + setupAccountsBillingRoutes(admin, { workos: providerPresent ? { organizations: { deleteOrganization: effects.provider } } as any : null }); + app.use('/api/admin', admin); + return app; +} + +beforeEach(() => { vi.clearAllMocks(); }); +afterAll(() => { stopAuthTimers(); }); +describe('organization deletion unconditional unavailable contract', () => { + for (const providerPresent of [true,false]) { + for (const path of ['/api/organizations/org_a','/api/admin/accounts/org_a']) { + for (const body of [undefined, {}, { confirmation: 'Pinnacle Agency', force: true, organization_id: 'org_b' }]) { + it(`${path}: provider=${providerPresent}, body=${JSON.stringify(body)} refuses before any collaborator`, async () => { + const response = await request(app(providerPresent)).delete(`${path}?org=org_b&org=org_c`) + .set('X-Organization-Id','org_b').set('Authorization','Bearer arbitrary').send(body); + await new Promise(resolve => setImmediate(resolve)); + expect(response.status).toBe(503); + expect(response.body).toEqual({ error: 'organization_deletion_unavailable', message: 'Organization deletion is temporarily unavailable.' }); + for (const spy of Object.values(effects)) expect(spy).not.toHaveBeenCalled(); + }); + } + } + } +});