Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion apps/sim/lib/api/contracts/workspaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ export const updateWorkspaceBodySchema = z.object({
})
.nullable()
.optional(),
billedAccountUserId: z.string().optional(),
allowPersonalApiKeys: z.boolean().optional(),
})

Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/workspaces/application/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
43 changes: 31 additions & 12 deletions apps/sim/lib/workspaces/application/update-workspace.integration.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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()
Expand Down Expand Up @@ -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`,
Expand All @@ -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,
Expand Down Expand Up @@ -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',
Expand All @@ -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', () => {
Expand Down Expand Up @@ -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)
})

Expand Down Expand Up @@ -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')
})
Expand Down
11 changes: 4 additions & 7 deletions apps/sim/lib/workspaces/application/update-workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
80 changes: 12 additions & 68 deletions apps/sim/lib/workspaces/update.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
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

export interface WorkspaceUpdatePatch {
name?: string
logoUrl?: string | null
allowPersonalApiKeys?: boolean
billedAccountUserId?: string
}

export interface WorkspaceIdentity {
Expand All @@ -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<WorkspaceUpdateResult> {
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')
}

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

const updateData: Partial<WorkspaceRow> = {}
const updateData: Partial<WorkspaceRow> = { 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<WorkspaceRow>
): Promise<WorkspaceRow> {
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 }
}
Loading