Skip to content

Commit 1450a88

Browse files
authored
fix(workspaces): stop workspace admins from moving the billed account (#10058)
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.
1 parent fd21651 commit 1450a88

5 files changed

Lines changed: 48 additions & 89 deletions

File tree

‎apps/sim/lib/api/contracts/workspaces.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,6 @@ export const updateWorkspaceBodySchema = z.object({
8989
})
9090
.nullable()
9191
.optional(),
92-
billedAccountUserId: z.string().optional(),
9392
allowPersonalApiKeys: z.boolean().optional(),
9493
})
9594

‎apps/sim/lib/workspaces/application/operations.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ export const workspaceUpdateOperations = {
9898
delegatedServices: ['copilot'],
9999
}),
100100
/**
101-
* Name and logo only. Billing payer and the personal-key policy stay on
101+
* Name and logo only. The personal-key policy stays on
102102
* {@link workspaceUpdateOperations.update}, which only a signed-in session
103103
* reaches; this narrower operation is the one Copilot and the public API get.
104104
*

‎apps/sim/lib/workspaces/application/update-workspace.integration.ts‎

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
/**
22
* Workspace updates against real Postgres: the session route keeps its legacy
3-
* refusals, and Chat's settings tool renames a workspace only as an admin and
4-
* never reaches billing or the personal-key policy.
3+
* refusals, and Chat's settings tool renames a workspace only as an admin.
4+
* Neither can change the billed account, and Chat never reaches the
5+
* personal-key policy.
56
*/
67
import { db } from '@sim/db'
7-
import { auditLog, permissions, user, workspace } from '@sim/db/schema'
8+
import { auditLog, permissions, user, userStats, workspace } from '@sim/db/schema'
89
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
910
import { createDeferred } from '@sim/testing/helpers/deferred'
1011
import { authMock, authMockFns } from '@sim/testing/mocks/auth.mock'
@@ -23,6 +24,7 @@ import { PATCH } from '@/app/api/workspaces/[id]/route'
2324

2425
const adminId = generateId()
2526
const secondAdminId = generateId()
27+
const thirdAdminId = generateId()
2628
const writerId = generateId()
2729
const outsiderId = generateId()
2830
const workspaceId = generateId()
@@ -113,7 +115,7 @@ describe('workspace update operations', () => {
113115
beforeAll(async () => {
114116
const now = new Date()
115117
await db.insert(user).values(
116-
[adminId, secondAdminId, writerId, outsiderId].map((id) => ({
118+
[adminId, secondAdminId, thirdAdminId, writerId, outsiderId].map((id) => ({
117119
id,
118120
name: 'Workspace update fixture',
119121
email: `${id}@workspace-update.test`,
@@ -122,6 +124,13 @@ describe('workspace update operations', () => {
122124
updatedAt: now,
123125
}))
124126
)
127+
// Every real account has a stats row; without one a payer move would fail on the
128+
// missing storage aggregate instead of committing, and prove nothing.
129+
await db
130+
.insert(userStats)
131+
.values(
132+
[adminId, secondAdminId, thirdAdminId].map((userId) => ({ id: generateId(), userId }))
133+
)
125134
await insertWorkspaceFixture(db, [
126135
{
127136
id: workspaceId,
@@ -159,6 +168,13 @@ describe('workspace update operations', () => {
159168
userId: secondAdminId,
160169
permissionType: 'admin' as const,
161170
},
171+
{
172+
id: generateId(),
173+
entityType: 'workspace',
174+
entityId: workspaceId,
175+
userId: thirdAdminId,
176+
permissionType: 'admin' as const,
177+
},
162178
{
163179
id: generateId(),
164180
entityType: 'workspace',
@@ -173,7 +189,9 @@ describe('workspace update operations', () => {
173189
await db.delete(auditLog).where(inArray(auditLog.workspaceId, fixtureWorkspaceIds))
174190
await db.delete(permissions).where(inArray(permissions.entityId, fixtureWorkspaceIds))
175191
await deleteWorkspaceFixture(db, inArray(workspace.id, fixtureWorkspaceIds))
176-
await db.delete(user).where(inArray(user.id, [adminId, secondAdminId, writerId, outsiderId]))
192+
await db
193+
.delete(user)
194+
.where(inArray(user.id, [adminId, secondAdminId, thirdAdminId, writerId, outsiderId]))
177195
})
178196

179197
describe('session route', () => {
@@ -210,13 +228,14 @@ describe('workspace update operations', () => {
210228
expect(await response.json()).toMatchObject({ error: 'No updates provided' })
211229
})
212230

213-
it('refuses a billed-account change to a non-admin with the legacy message', async () => {
214-
signIn(adminId)
215-
const response = await patchWorkspace(workspaceId, { billedAccountUserId: writerId })
231+
it.each([
232+
['a co-admin who is not the payer', secondAdminId, thirdAdminId],
233+
['the payer, onto an admin who never agreed', adminId, secondAdminId],
234+
])('never lets %s move the billed account', async (_label, actorId, newPayerId) => {
235+
signIn(actorId)
236+
const response = await patchWorkspace(workspaceId, { billedAccountUserId: newPayerId })
216237
expect(response.status).toBe(400)
217-
expect(await response.json()).toMatchObject({
218-
error: 'Billed account must be a workspace admin',
219-
})
238+
expect(await response.json()).toMatchObject({ error: 'No updates provided' })
220239
expect((await readWorkspace(workspaceId)).billedAccountUserId).toBe(adminId)
221240
})
222241

@@ -287,7 +306,7 @@ describe('workspace update operations', () => {
287306
await expect(
288307
updateWorkspace.execute({
289308
principal,
290-
input: { workspaceId, patch: { billedAccountUserId: adminId } },
309+
input: { workspaceId, patch: { allowPersonalApiKeys: false } },
291310
})
292311
).rejects.toThrow('cannot perform operation workspaces.update')
293312
})

‎apps/sim/lib/workspaces/application/update-workspace.ts‎

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ function projectUpdateAudit(
3333
patch: WorkspaceUpdatePatch,
3434
{ previous, updated }: WorkspaceUpdateResult
3535
): WorkspaceUseCaseAuditEntry {
36-
const { name, logoUrl, allowPersonalApiKeys, billedAccountUserId } = patch
36+
const { name, logoUrl, allowPersonalApiKeys } = patch
3737
return {
3838
action: AuditAction.WORKSPACE_UPDATED,
3939
resourceType: AuditResourceType.WORKSPACE,
@@ -47,18 +47,15 @@ function projectUpdateAudit(
4747
...(allowPersonalApiKeys !== undefined && {
4848
allowPersonalApiKeys: { from: previous.allowPersonalApiKeys, to: allowPersonalApiKeys },
4949
}),
50-
...(billedAccountUserId !== undefined && {
51-
billedAccountUserId: { from: previous.billedAccountUserId, to: billedAccountUserId },
52-
}),
5350
},
5451
},
5552
}
5653
}
5754

5855
/**
59-
* The full workspace settings update: name, logo, personal-key policy and
60-
* billed account. An inactive or unreachable workspace is refused the same way
61-
* as a non-admin, so the caller cannot tell the two apart.
56+
* The full workspace settings update: name, logo and personal-key policy.
57+
* An inactive or unreachable workspace is refused the same way as a
58+
* non-admin, so the caller cannot tell the two apart.
6259
*/
6360
export const updateWorkspace = defineAuthorizedWorkspaceUseCase({
6461
operation: workspaceUpdateOperations.update,

‎apps/sim/lib/workspaces/update.ts‎

Lines changed: 12 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,14 @@
11
import { db } from '@sim/db'
22
import { workspace } from '@sim/db/schema'
33
import { and, eq, isNull } from 'drizzle-orm'
4-
import { changeWorkspaceStoragePayerInTx } from '@/lib/billing/storage/payer-transfer'
54
import { OrchestrationError } from '@/lib/core/orchestration/types'
6-
import type { DbOrTx } from '@/lib/db/types'
7-
import { getEffectiveWorkspacePermission } from '@/lib/workspaces/permissions/utils'
85

96
type WorkspaceRow = typeof workspace.$inferSelect
107

118
export interface WorkspaceUpdatePatch {
129
name?: string
1310
logoUrl?: string | null
1411
allowPersonalApiKeys?: boolean
15-
billedAccountUserId?: string
1612
}
1713

1814
export interface WorkspaceIdentity {
@@ -38,20 +34,16 @@ export async function readWorkspaceIdentityRecord(workspaceId: string): Promise<
3834
}
3935

4036
/**
41-
* Applies a workspace metadata patch to an active workspace. A billed-account
42-
* change moves the workspace's storage to the new payer in the same transaction.
37+
* Applies a workspace metadata patch to an active workspace. The billed account
38+
* is deliberately not patchable here: workspace admin does not carry authority
39+
* over the payer's pooled credit and storage.
4340
*/
4441
export async function applyWorkspaceUpdate(
4542
workspaceId: string,
4643
patch: WorkspaceUpdatePatch
4744
): Promise<WorkspaceUpdateResult> {
48-
const { name, logoUrl, allowPersonalApiKeys, billedAccountUserId } = patch
49-
if (
50-
name === undefined &&
51-
logoUrl === undefined &&
52-
billedAccountUserId === undefined &&
53-
allowPersonalApiKeys === undefined
54-
) {
45+
const { name, logoUrl, allowPersonalApiKeys } = patch
46+
if (name === undefined && logoUrl === undefined && allowPersonalApiKeys === undefined) {
5547
throw new OrchestrationError('validation', 'No updates provided')
5648
}
5749

@@ -62,67 +54,19 @@ export async function applyWorkspaceUpdate(
6254
.limit(1)
6355
if (!previous) throw new OrchestrationError('not_found', 'Workspace not found')
6456

65-
const updateData: Partial<WorkspaceRow> = {}
57+
const updateData: Partial<WorkspaceRow> = { updatedAt: new Date() }
6658
if (name !== undefined) updateData.name = name
6759
if (logoUrl !== undefined) updateData.logoUrl = logoUrl
6860
if (allowPersonalApiKeys !== undefined) updateData.allowPersonalApiKeys = allowPersonalApiKeys
6961

70-
if (billedAccountUserId !== undefined) {
71-
if (previous.organizationId && previous.workspaceMode === 'organization') {
72-
throw new OrchestrationError(
73-
'validation',
74-
'Organization workspaces use organization billing and cannot change billed account.'
75-
)
76-
}
77-
if (previous.workspaceMode === 'personal') {
78-
throw new OrchestrationError(
79-
'validation',
80-
'Personal workspaces are always billed to their owner and cannot change billed account.'
81-
)
82-
}
83-
const candidatePermission = await getEffectiveWorkspacePermission(billedAccountUserId, previous)
84-
if (candidatePermission !== 'admin') {
85-
throw new OrchestrationError('validation', 'Billed account must be a workspace admin')
86-
}
87-
}
88-
89-
updateData.updatedAt = new Date()
90-
91-
const updated =
92-
billedAccountUserId === undefined
93-
? await updateWorkspaceRow(db, workspaceId, updateData)
94-
: await db.transaction(async (tx) => {
95-
await changeWorkspaceStoragePayerInTx(tx, {
96-
workspaceId,
97-
organizationId: previous.organizationId,
98-
billedAccountUserId,
99-
expectedCurrentPayer: {
100-
organizationId: previous.organizationId,
101-
billedAccountUserId: previous.billedAccountUserId,
102-
},
103-
})
104-
return updateWorkspaceRow(tx, workspaceId, updateData)
105-
})
106-
107-
return { previous, updated }
108-
}
109-
110-
/**
111-
* Writes the patch only while the workspace is still active: an archival that
112-
* commits after the earlier reads leaves no row to update, which answers the
113-
* same not-found as a workspace that was already gone (and rolls back a
114-
* billed-account transfer).
115-
*/
116-
async function updateWorkspaceRow(
117-
executor: DbOrTx,
118-
workspaceId: string,
119-
updateData: Partial<WorkspaceRow>
120-
): Promise<WorkspaceRow> {
121-
const [row] = await executor
62+
// Writes only while still active: an archival that commits after the read above
63+
// leaves no row to update and answers the same not-found.
64+
const [updated] = await db
12265
.update(workspace)
12366
.set(updateData)
12467
.where(and(eq(workspace.id, workspaceId), isNull(workspace.archivedAt)))
12568
.returning()
126-
if (!row) throw new OrchestrationError('not_found', 'Workspace not found')
127-
return row
69+
if (!updated) throw new OrchestrationError('not_found', 'Workspace not found')
70+
71+
return { previous, updated }
12872
}

0 commit comments

Comments
 (0)