From bc9ac75f1e4b5a2f796f5a877d3af62991e21702 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 14 Nov 2026 14:12:18 -0800 Subject: [PATCH] fix(workspaces): stop workspace admins from moving the billed account The workspace settings PATCH accepted billedAccountUserId from any workspace admin and only checked that the new payer was also an admin. The caller never needed billing authority and the new payer never agreed, so a co-admin could move a shared workspace's model spend and storage onto another admin's personal plan. No client has sent the field since the settings hook dropped it, so remove it from the general patch instead of gating a dead write path. --- apps/sim/lib/api/contracts/workspaces.ts | 1 - .../lib/workspaces/application/operations.ts | 2 +- .../update-workspace.integration.ts | 43 +++++++--- .../application/update-workspace.ts | 11 +-- apps/sim/lib/workspaces/update.ts | 80 +++---------------- 5 files changed, 48 insertions(+), 89 deletions(-) diff --git a/apps/sim/lib/api/contracts/workspaces.ts b/apps/sim/lib/api/contracts/workspaces.ts index eec5c4f760d..d26609ff336 100644 --- a/apps/sim/lib/api/contracts/workspaces.ts +++ b/apps/sim/lib/api/contracts/workspaces.ts @@ -89,7 +89,6 @@ export const updateWorkspaceBodySchema = z.object({ }) .nullable() .optional(), - billedAccountUserId: z.string().optional(), allowPersonalApiKeys: z.boolean().optional(), }) diff --git a/apps/sim/lib/workspaces/application/operations.ts b/apps/sim/lib/workspaces/application/operations.ts index d4a4476786a..d4a5bb63fd7 100644 --- a/apps/sim/lib/workspaces/application/operations.ts +++ b/apps/sim/lib/workspaces/application/operations.ts @@ -98,7 +98,7 @@ export const workspaceUpdateOperations = { delegatedServices: ['copilot'], }), /** - * Name and logo only. Billing payer and the personal-key policy stay on + * Name and logo only. The personal-key policy stays on * {@link workspaceUpdateOperations.update}, which only a signed-in session * reaches; this narrower operation is the one Copilot and the public API get. * diff --git a/apps/sim/lib/workspaces/application/update-workspace.integration.ts b/apps/sim/lib/workspaces/application/update-workspace.integration.ts index 5f03bea5c63..f2dedce1c23 100644 --- a/apps/sim/lib/workspaces/application/update-workspace.integration.ts +++ b/apps/sim/lib/workspaces/application/update-workspace.integration.ts @@ -1,10 +1,11 @@ /** * Workspace updates against real Postgres: the session route keeps its legacy - * refusals, and Chat's settings tool renames a workspace only as an admin and - * never reaches billing or the personal-key policy. + * refusals, and Chat's settings tool renames a workspace only as an admin. + * Neither can change the billed account, and Chat never reaches the + * personal-key policy. */ import { db } from '@sim/db' -import { auditLog, permissions, user, workspace } from '@sim/db/schema' +import { auditLog, permissions, user, userStats, workspace } from '@sim/db/schema' import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' import { createDeferred } from '@sim/testing/helpers/deferred' import { authMock, authMockFns } from '@sim/testing/mocks/auth.mock' @@ -23,6 +24,7 @@ import { PATCH } from '@/app/api/workspaces/[id]/route' const adminId = generateId() const secondAdminId = generateId() +const thirdAdminId = generateId() const writerId = generateId() const outsiderId = generateId() const workspaceId = generateId() @@ -113,7 +115,7 @@ describe('workspace update operations', () => { beforeAll(async () => { const now = new Date() await db.insert(user).values( - [adminId, secondAdminId, writerId, outsiderId].map((id) => ({ + [adminId, secondAdminId, thirdAdminId, writerId, outsiderId].map((id) => ({ id, name: 'Workspace update fixture', email: `${id}@workspace-update.test`, @@ -122,6 +124,13 @@ describe('workspace update operations', () => { updatedAt: now, })) ) + // Every real account has a stats row; without one a payer move would fail on the + // missing storage aggregate instead of committing, and prove nothing. + await db + .insert(userStats) + .values( + [adminId, secondAdminId, thirdAdminId].map((userId) => ({ id: generateId(), userId })) + ) await insertWorkspaceFixture(db, [ { id: workspaceId, @@ -159,6 +168,13 @@ describe('workspace update operations', () => { userId: secondAdminId, permissionType: 'admin' as const, }, + { + id: generateId(), + entityType: 'workspace', + entityId: workspaceId, + userId: thirdAdminId, + permissionType: 'admin' as const, + }, { id: generateId(), entityType: 'workspace', @@ -173,7 +189,9 @@ describe('workspace update operations', () => { await db.delete(auditLog).where(inArray(auditLog.workspaceId, fixtureWorkspaceIds)) await db.delete(permissions).where(inArray(permissions.entityId, fixtureWorkspaceIds)) await deleteWorkspaceFixture(db, inArray(workspace.id, fixtureWorkspaceIds)) - await db.delete(user).where(inArray(user.id, [adminId, secondAdminId, writerId, outsiderId])) + await db + .delete(user) + .where(inArray(user.id, [adminId, secondAdminId, thirdAdminId, writerId, outsiderId])) }) describe('session route', () => { @@ -210,13 +228,14 @@ describe('workspace update operations', () => { expect(await response.json()).toMatchObject({ error: 'No updates provided' }) }) - it('refuses a billed-account change to a non-admin with the legacy message', async () => { - signIn(adminId) - const response = await patchWorkspace(workspaceId, { billedAccountUserId: writerId }) + it.each([ + ['a co-admin who is not the payer', secondAdminId, thirdAdminId], + ['the payer, onto an admin who never agreed', adminId, secondAdminId], + ])('never lets %s move the billed account', async (_label, actorId, newPayerId) => { + signIn(actorId) + const response = await patchWorkspace(workspaceId, { billedAccountUserId: newPayerId }) expect(response.status).toBe(400) - expect(await response.json()).toMatchObject({ - error: 'Billed account must be a workspace admin', - }) + expect(await response.json()).toMatchObject({ error: 'No updates provided' }) expect((await readWorkspace(workspaceId)).billedAccountUserId).toBe(adminId) }) @@ -287,7 +306,7 @@ describe('workspace update operations', () => { await expect( updateWorkspace.execute({ principal, - input: { workspaceId, patch: { billedAccountUserId: adminId } }, + input: { workspaceId, patch: { allowPersonalApiKeys: false } }, }) ).rejects.toThrow('cannot perform operation workspaces.update') }) diff --git a/apps/sim/lib/workspaces/application/update-workspace.ts b/apps/sim/lib/workspaces/application/update-workspace.ts index dae7dcaa7d0..a7b70473892 100644 --- a/apps/sim/lib/workspaces/application/update-workspace.ts +++ b/apps/sim/lib/workspaces/application/update-workspace.ts @@ -33,7 +33,7 @@ function projectUpdateAudit( patch: WorkspaceUpdatePatch, { previous, updated }: WorkspaceUpdateResult ): WorkspaceUseCaseAuditEntry { - const { name, logoUrl, allowPersonalApiKeys, billedAccountUserId } = patch + const { name, logoUrl, allowPersonalApiKeys } = patch return { action: AuditAction.WORKSPACE_UPDATED, resourceType: AuditResourceType.WORKSPACE, @@ -47,18 +47,15 @@ function projectUpdateAudit( ...(allowPersonalApiKeys !== undefined && { allowPersonalApiKeys: { from: previous.allowPersonalApiKeys, to: allowPersonalApiKeys }, }), - ...(billedAccountUserId !== undefined && { - billedAccountUserId: { from: previous.billedAccountUserId, to: billedAccountUserId }, - }), }, }, } } /** - * The full workspace settings update: name, logo, personal-key policy and - * billed account. An inactive or unreachable workspace is refused the same way - * as a non-admin, so the caller cannot tell the two apart. + * The full workspace settings update: name, logo and personal-key policy. + * An inactive or unreachable workspace is refused the same way as a + * non-admin, so the caller cannot tell the two apart. */ export const updateWorkspace = defineAuthorizedWorkspaceUseCase({ operation: workspaceUpdateOperations.update, diff --git a/apps/sim/lib/workspaces/update.ts b/apps/sim/lib/workspaces/update.ts index b45b4f80ac2..d6b33419ac0 100644 --- a/apps/sim/lib/workspaces/update.ts +++ b/apps/sim/lib/workspaces/update.ts @@ -1,10 +1,7 @@ import { db } from '@sim/db' import { workspace } from '@sim/db/schema' import { and, eq, isNull } from 'drizzle-orm' -import { changeWorkspaceStoragePayerInTx } from '@/lib/billing/storage/payer-transfer' import { OrchestrationError } from '@/lib/core/orchestration/types' -import type { DbOrTx } from '@/lib/db/types' -import { getEffectiveWorkspacePermission } from '@/lib/workspaces/permissions/utils' type WorkspaceRow = typeof workspace.$inferSelect @@ -12,7 +9,6 @@ export interface WorkspaceUpdatePatch { name?: string logoUrl?: string | null allowPersonalApiKeys?: boolean - billedAccountUserId?: string } export interface WorkspaceIdentity { @@ -38,20 +34,16 @@ export async function readWorkspaceIdentityRecord(workspaceId: string): Promise< } /** - * Applies a workspace metadata patch to an active workspace. A billed-account - * change moves the workspace's storage to the new payer in the same transaction. + * Applies a workspace metadata patch to an active workspace. The billed account + * is deliberately not patchable here: workspace admin does not carry authority + * over the payer's pooled credit and storage. */ export async function applyWorkspaceUpdate( workspaceId: string, patch: WorkspaceUpdatePatch ): Promise { - const { name, logoUrl, allowPersonalApiKeys, billedAccountUserId } = patch - if ( - name === undefined && - logoUrl === undefined && - billedAccountUserId === undefined && - allowPersonalApiKeys === undefined - ) { + const { name, logoUrl, allowPersonalApiKeys } = patch + if (name === undefined && logoUrl === undefined && allowPersonalApiKeys === undefined) { throw new OrchestrationError('validation', 'No updates provided') } @@ -62,67 +54,19 @@ export async function applyWorkspaceUpdate( .limit(1) if (!previous) throw new OrchestrationError('not_found', 'Workspace not found') - const updateData: Partial = {} + const updateData: Partial = { updatedAt: new Date() } if (name !== undefined) updateData.name = name if (logoUrl !== undefined) updateData.logoUrl = logoUrl if (allowPersonalApiKeys !== undefined) updateData.allowPersonalApiKeys = allowPersonalApiKeys - if (billedAccountUserId !== undefined) { - if (previous.organizationId && previous.workspaceMode === 'organization') { - throw new OrchestrationError( - 'validation', - 'Organization workspaces use organization billing and cannot change billed account.' - ) - } - if (previous.workspaceMode === 'personal') { - throw new OrchestrationError( - 'validation', - 'Personal workspaces are always billed to their owner and cannot change billed account.' - ) - } - const candidatePermission = await getEffectiveWorkspacePermission(billedAccountUserId, previous) - if (candidatePermission !== 'admin') { - throw new OrchestrationError('validation', 'Billed account must be a workspace admin') - } - } - - updateData.updatedAt = new Date() - - const updated = - billedAccountUserId === undefined - ? await updateWorkspaceRow(db, workspaceId, updateData) - : await db.transaction(async (tx) => { - await changeWorkspaceStoragePayerInTx(tx, { - workspaceId, - organizationId: previous.organizationId, - billedAccountUserId, - expectedCurrentPayer: { - organizationId: previous.organizationId, - billedAccountUserId: previous.billedAccountUserId, - }, - }) - return updateWorkspaceRow(tx, workspaceId, updateData) - }) - - return { previous, updated } -} - -/** - * Writes the patch only while the workspace is still active: an archival that - * commits after the earlier reads leaves no row to update, which answers the - * same not-found as a workspace that was already gone (and rolls back a - * billed-account transfer). - */ -async function updateWorkspaceRow( - executor: DbOrTx, - workspaceId: string, - updateData: Partial -): Promise { - const [row] = await executor + // Writes only while still active: an archival that commits after the read above + // leaves no row to update and answers the same not-found. + const [updated] = await db .update(workspace) .set(updateData) .where(and(eq(workspace.id, workspaceId), isNull(workspace.archivedAt))) .returning() - if (!row) throw new OrchestrationError('not_found', 'Workspace not found') - return row + if (!updated) throw new OrchestrationError('not_found', 'Workspace not found') + + return { previous, updated } }