Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,9 @@ import {
} from '@/lib/api/contracts/v1/admin'
import { parseRequest } from '@/lib/api/server'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { revokeWorkspaceCredentialMembershipsTx } from '@/lib/credentials/access'
import { removeWorkspaceSkillMembershipsTx } from '@/lib/skills/access'
import { revokeWorkspaceAccessTx } from '@/lib/workspaces/access/workspace-access'
import { getWorkspaceById } from '@/lib/workspaces/permissions/utils'
import {
reassignWorkflowOwnershipForWorkspaceMemberRemovalTx,
transferWorkspaceOwnershipToBilledAccountForMemberRemovalTx,
WorkspaceBillingAccountRemovalError,
} from '@/lib/workspaces/utils'
import { WorkspaceBillingAccountRemovalError } from '@/lib/workspaces/utils'
import { withAdminAuthParams } from '@/app/api/v1/admin/middleware'
import {
badRequestResponse,
Expand Down Expand Up @@ -278,28 +273,19 @@ export const DELETE = withRouteHandler(
)
}

await db.transaction(async (tx) => {
await transferWorkspaceOwnershipToBilledAccountForMemberRemovalTx({
tx,
const removed = await db.transaction(async (tx) => {
const result = await revokeWorkspaceAccessTx(tx, {
workspaceId,
departingUserId: existingMember.userId,
userId: existingMember.userId,
Comment thread
mzxchandra marked this conversation as resolved.
expectedPermissionId: existingMember.id,
})

const workflowOwnershipReassignment =
await reassignWorkflowOwnershipForWorkspaceMemberRemovalTx({
tx,
workspaceIds: [workspaceId],
departingUserId: existingMember.userId,
})
if (workflowOwnershipReassignment.unresolved.length > 0) {
if (!result.revoked) {
if (result.reason === 'membership-changed') return false
throw new WorkspaceBillingAccountRemovalError()
}

await tx.delete(permissions).where(eq(permissions.id, memberId))

await revokeWorkspaceCredentialMembershipsTx(tx, workspaceId, existingMember.userId)
await removeWorkspaceSkillMembershipsTx(tx, workspaceId, existingMember.userId)
return true
})
if (!removed) return notFoundResponse('Workspace member')

logger.info(`Admin API: Removed member ${memberId} from workspace ${workspaceId}`, {
userId: existingMember.userId,
Expand Down
31 changes: 4 additions & 27 deletions apps/sim/app/api/v1/admin/workspaces/[id]/members/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,10 @@ import {
} from '@/lib/api/contracts/v1/admin'
import { parseRequest } from '@/lib/api/server'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { revokeWorkspaceCredentialMembershipsTx } from '@/lib/credentials/access'
import { syncWorkspaceEnvCredentials } from '@/lib/credentials/environment'
import { removeWorkspaceSkillMembershipsTx } from '@/lib/skills/access'
import { revokeWorkspaceAccessTx } from '@/lib/workspaces/access/workspace-access'
import { getWorkspaceById } from '@/lib/workspaces/permissions/utils'
import {
reassignWorkflowOwnershipForWorkspaceMemberRemovalTx,
transferWorkspaceOwnershipToBilledAccountForMemberRemovalTx,
WorkspaceBillingAccountRemovalError,
} from '@/lib/workspaces/utils'
import { WorkspaceBillingAccountRemovalError } from '@/lib/workspaces/utils'
import { withAdminAuthParams } from '@/app/api/v1/admin/middleware'
import {
badRequestResponse,
Expand Down Expand Up @@ -395,26 +390,8 @@ export const DELETE = withRouteHandler(
}

await db.transaction(async (tx) => {
await transferWorkspaceOwnershipToBilledAccountForMemberRemovalTx({
tx,
workspaceId,
departingUserId: userId,
})

const workflowOwnershipReassignment =
await reassignWorkflowOwnershipForWorkspaceMemberRemovalTx({
tx,
workspaceIds: [workspaceId],
departingUserId: userId,
})
if (workflowOwnershipReassignment.unresolved.length > 0) {
throw new WorkspaceBillingAccountRemovalError()
}

await tx.delete(permissions).where(eq(permissions.id, existingPermission.id))

await revokeWorkspaceCredentialMembershipsTx(tx, workspaceId, userId)
await removeWorkspaceSkillMembershipsTx(tx, workspaceId, userId)
const result = await revokeWorkspaceAccessTx(tx, { workspaceId, userId: userId })
Comment thread
mzxchandra marked this conversation as resolved.
if (!result.revoked) throw new WorkspaceBillingAccountRemovalError()
})

logger.info(`Admin API: Removed user ${userId} from workspace ${workspaceId}`)
Expand Down
2 changes: 2 additions & 0 deletions apps/sim/background/cleanup-soft-deletes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { and, asc, eq, inArray, isNotNull, isNull, lt, sql } from 'drizzle-orm'
import { type CleanupJobPayload, runCleanupWithLimits } from '@/lib/billing/cleanup-dispatcher'
import {
decrementStorageUsageForBillingContextInTx,
lockWorkspaceStorageForMutationInTx,
resolveStorageBillingContext,
type StorageBillingContext,
} from '@/lib/billing/storage'
Expand Down Expand Up @@ -334,6 +335,7 @@ async function deleteExpiredBillableWorkspaceFileRows(
for (const batch of chunkArray(workspaceRows, DEFAULT_DELETE_CHUNK_SIZE)) {
try {
const deletedCount = await db.transaction(async (tx) => {
await lockWorkspaceStorageForMutationInTx(tx, workspaceId)
await releaseWorkspaceFileVersionsForPurgeInTx(
tx,
batch.map(({ id }) => id),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { credential, knowledgeBase, member, workspaceFiles } from '@sim/db/schema'
import { credential, knowledgeBase, member, user, workspaceFiles } from '@sim/db/schema'
import { dbChainMockFns, hasMockCondition, queueTableRows, resetDbChainMock } from '@sim/testing'
import {
organizationMemberLimitsMock,
Expand Down Expand Up @@ -39,13 +39,18 @@ describe('external organization access removal', () => {
it('preserves organization indexes and cached documents when a creator leaves with no workspaces', async () => {
queueTableRows(member, [{ id: 'membership', userId: 'departing', role: 'admin' }])
queueTableRows(member, [{ userId: 'surviving-owner' }])
queueTableRows(user, [{ email: 'departing@example.test' }])
queueTableRows(user, [{ email: 'departing@example.test' }])
queueTableRows(user, [{ id: 'surviving-owner' }])
queueTableRows(workspaceFiles, [{ id: 'cached-file', context: 'knowledge-base' }])
dbChainMockFns.returning.mockResolvedValueOnce([{ id: 'membership' }])

const result = await removeUserFromOrganization({
userId: 'departing',
organizationId: 'organization-a',
memberId: 'membership',
skipBillingLogic: true,
onError: 'throw',
})

expect(result.success).toBe(true)
Expand Down
59 changes: 14 additions & 45 deletions apps/sim/lib/billing/organizations/membership.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
account,
credential,
invitation,
knowledgeBase,
member,
organization,
permissionGroupMember,
Expand All @@ -19,7 +18,6 @@ import {
user,
userStats,
workspace,
workspaceFiles,
} from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
Expand All @@ -39,6 +37,7 @@ import {
import { acquireUserBillingIdentityLock } from '@/lib/billing/organizations/billing-identity-lock'
import { setOrgMemberUsageLimit } from '@/lib/billing/organizations/member-limits'
import { MEMBER_BILLING_RECONCILIATION_EVENT_TYPE } from '@/lib/billing/organizations/membership-reconciliation-event'
import { reassignOrganizationSharedResourcesTx } from '@/lib/billing/organizations/resource-handoff'
import { isPaid, sqlIsPro } from '@/lib/billing/plan-helpers'
import { changeOrganizationWorkspaceBilledAccountsInTx } from '@/lib/billing/storage/payer-transfer'
import {
Expand All @@ -63,10 +62,8 @@ import {
} from '@/lib/organizations/members/revocation'
import { reassignOrganizationProjects } from '@/lib/projects/membership'
import { removeWorkspaceSkillMembershipsTx } from '@/lib/skills/access'
import {
reassignWorkflowOwnershipForWorkspaceMemberRemovalTx,
WorkspaceBillingAccountRemovalError,
} from '@/lib/workspaces/utils'
import { reassignSharedResourceOwnershipForWorkspaceMemberRemovalTx } from '@/lib/workspaces/resource-handoff'
import { WorkspaceBillingAccountRemovalError } from '@/lib/workspaces/utils'
import { endDirectoryMembershipTx } from '@/ee/scim/lib/identity/end-directory-membership'

export { acquireUserBillingIdentityLock } from '@/lib/billing/organizations/billing-identity-lock'
Expand Down Expand Up @@ -546,14 +543,8 @@ async function reassignOwnedOrganizationResourcesTx({
organizationId: string
workspaceIds: string[]
}) {
const [ownerMembership] = await tx
.select({ userId: member.userId })
.from(member)
.where(and(eq(member.organizationId, organizationId), eq(member.role, 'owner')))
.limit(1)

const ownerId = ownerMembership?.userId
if (!ownerId || ownerId === userId) return 0
const ownerId = await reassignOrganizationSharedResourcesTx(tx, organizationId, userId)
if (!ownerId) return 0

await reassignOrganizationProjects(tx, {
organizationId,
Expand All @@ -562,28 +553,6 @@ async function reassignOwnedOrganizationResourcesTx({
workspaceIds,
})

/** Creator attribution must survive account deletion without changing document ACLs. */
await tx
.update(knowledgeBase)
.set({ userId: ownerId, updatedAt: new Date() })
.where(
and(
eq(knowledgeBase.organizationId, organizationId),
isNull(knowledgeBase.workspaceId),
eq(knowledgeBase.userId, userId)
)
)
await tx
.update(workspaceFiles)
.set({ userId: ownerId, updatedAt: new Date() })
.where(
and(
eq(workspaceFiles.organizationId, organizationId),
isNull(workspaceFiles.workspaceId),
eq(workspaceFiles.userId, userId)
)
)

if (workspaceIds.length === 0) return 0

const reassignedWorkspaces = await tx
Expand Down Expand Up @@ -1205,13 +1174,13 @@ export async function transferUserBetweenOrganizations(
workspaceIds,
})
if (workspaceIds.length > 0) {
const workflowOwnershipReassignment =
await reassignWorkflowOwnershipForWorkspaceMemberRemovalTx({
const resourceOwnershipReassignment =
await reassignSharedResourceOwnershipForWorkspaceMemberRemovalTx({
tx,
workspaceIds,
departingUserId: params.userId,
})
if (workflowOwnershipReassignment.unresolved.length > 0) {
if (resourceOwnershipReassignment.unresolved.length > 0) {
throw new WorkspaceBillingAccountRemovalError()
}
const deletedPermissions = await tx
Expand Down Expand Up @@ -1434,13 +1403,13 @@ export async function removeUserFromOrganization(
}
}

const workflowOwnershipReassignment =
await reassignWorkflowOwnershipForWorkspaceMemberRemovalTx({
const resourceOwnershipReassignment =
await reassignSharedResourceOwnershipForWorkspaceMemberRemovalTx({
tx,
workspaceIds,
departingUserId: userId,
})
if (workflowOwnershipReassignment.unresolved.length > 0) {
if (resourceOwnershipReassignment.unresolved.length > 0) {
throw new WorkspaceBillingAccountRemovalError()
}

Expand Down Expand Up @@ -1651,13 +1620,13 @@ export async function removeExternalUserFromOrganizationWorkspaces(params: {
}
}

const workflowOwnershipReassignment =
await reassignWorkflowOwnershipForWorkspaceMemberRemovalTx({
const resourceOwnershipReassignment =
await reassignSharedResourceOwnershipForWorkspaceMemberRemovalTx({
tx,
workspaceIds,
departingUserId: userId,
})
if (workflowOwnershipReassignment.unresolved.length > 0) {
if (resourceOwnershipReassignment.unresolved.length > 0) {
throw new WorkspaceBillingAccountRemovalError()
}

Expand Down
105 changes: 105 additions & 0 deletions apps/sim/lib/billing/organizations/resource-handoff.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import {
knowledgeBase,
member,
permissionGroup,
ssoProvider,
user,
workspaceFiles,
} from '@sim/db/schema'
import { and, asc, eq, isNull, ne, sql } from 'drizzle-orm'
import { OrchestrationError } from '@/lib/core/orchestration/types'
import type { DbOrTx, DbTransaction } from '@/lib/db/types'
import { handoffFileCreatorsInTx } from '@/lib/uploads/contexts/workspace/creator-handoff'

/** Organization references survive even when their creator no longer has a membership row. */
export async function listSharedResourceOrganizationIdsForUser(executor: DbOrTx, userId: string) {
const rows = await executor.execute<{ organizationId: string }>(sql`
SELECT DISTINCT "organizationId" FROM (
SELECT ${knowledgeBase.organizationId} AS "organizationId" FROM ${knowledgeBase}
WHERE ${knowledgeBase.userId} = ${userId} AND ${knowledgeBase.workspaceId} IS NULL
UNION ALL SELECT ${workspaceFiles.organizationId} FROM ${workspaceFiles}
WHERE ${workspaceFiles.userId} = ${userId} AND ${workspaceFiles.workspaceId} IS NULL
UNION ALL SELECT ${permissionGroup.organizationId} FROM ${permissionGroup} WHERE ${permissionGroup.createdBy} = ${userId}
UNION ALL SELECT ${ssoProvider.organizationId} FROM ${ssoProvider} WHERE ${ssoProvider.userId} = ${userId}
) owned WHERE "organizationId" IS NOT NULL ORDER BY "organizationId"
`)
return rows.map((row) => row.organizationId)
}

/** Retains organization-owned configuration without rewriting ACLs, credentials, or historical actors. */
export async function reassignOrganizationSharedResourcesTx(
tx: DbTransaction,
organizationId: string,
departingUserId: string
): Promise<string | null> {
const [successor] = await tx
.select({ userId: member.userId })
.from(member)
.where(
and(
eq(member.organizationId, organizationId),
eq(member.role, 'owner'),
ne(member.userId, departingUserId)
)
)
.orderBy(asc(member.userId))
.limit(1)
.for('share')
if (!successor) {
const owned = await listSharedResourceOrganizationIdsForUser(tx, departingUserId)
if (owned.includes(organizationId)) {
throw new OrchestrationError(
'conflict',
'Shared organization resources need an active organization owner before this account can leave or be deleted.'
)
}
return null
}
const [account] = await tx
.select({ id: user.id })
.from(user)
.where(eq(user.id, successor.userId))
.for('key share')
if (!account)
throw new OrchestrationError(
'conflict',
'The organization owner changed. Nothing was changed; try again.'
)
const userId = successor.userId
const updatedAt = new Date()
await tx
.update(knowledgeBase)
.set({ userId, updatedAt })
.where(
and(
eq(knowledgeBase.organizationId, organizationId),
isNull(knowledgeBase.workspaceId),
eq(knowledgeBase.userId, departingUserId)
)
)
await handoffFileCreatorsInTx(
tx,
and(
eq(workspaceFiles.organizationId, organizationId),
isNull(workspaceFiles.workspaceId),
eq(workspaceFiles.userId, departingUserId)
),
userId
)
await tx
.update(permissionGroup)
.set({ createdBy: userId, updatedAt })
.where(
and(
eq(permissionGroup.organizationId, organizationId),
eq(permissionGroup.createdBy, departingUserId)
)
)
await tx
.update(ssoProvider)
.set({ userId })
.where(
and(eq(ssoProvider.organizationId, organizationId), eq(ssoProvider.userId, departingUserId))
)
return userId
}
1 change: 1 addition & 0 deletions apps/sim/lib/billing/storage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export {
incrementAdmittedStorageUsageForBillingContextInTx,
incrementStorageUsageForBillingContextInTx,
type LegacyStorageUsageDelta,
lockWorkspaceStorageForMutationInTx,
maybeNotifyStorageLimitForBillingContext,
type WorkspaceStorageUsageDelta,
} from './tracking'
Loading
Loading