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
23 changes: 16 additions & 7 deletions apps/sim/app/api/credentials/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
import { db } from '@sim/db'
import { account, credential, credentialMember, workspace } from '@sim/db/schema'
import { account, credential, credentialMember, permissions, workspace } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { getPostgresErrorCode } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
Expand All @@ -22,7 +22,6 @@ import {
normalizeAtlassianDomain,
validateAtlassianServiceAccount,
} from '@/lib/credentials/atlassian-service-account'
import { getWorkspaceMemberUserIds } from '@/lib/credentials/environment'
import { syncWorkspaceOAuthCredentialsForUser } from '@/lib/credentials/oauth'
import { getServiceConfigByProviderId } from '@/lib/oauth'
import {
Expand Down Expand Up @@ -535,17 +534,27 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
})

if ((type === 'env_workspace' || type === 'service_account') && workspaceRow?.ownerId) {
const workspaceUserIds = await getWorkspaceMemberUserIds(workspaceId)
const wsPermissionRows = await db
.select({ userId: permissions.userId, permissionType: permissions.permissionType })
.from(permissions)
.where(
and(eq(permissions.entityType, 'workspace'), eq(permissions.entityId, workspaceId))
)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Permissions query bypasses transaction using db instead of tx

Medium Severity

Inside db.transaction(async (tx) => { ... }), the workspace permissions query on line 537 uses db instead of the transaction handle tx. Every other query in this transaction block correctly uses tx. This causes the permissions read to execute on a separate connection outside the transaction's isolation boundary, which means it won't see uncommitted changes from concurrent transactions consistently and consumes an extra connection from the pool. Since tx is available and used for all other operations in the same block, this looks like an oversight.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 78b6c88. Configure here.

const wsPermissionByUser = new Map(
wsPermissionRows.map((row) => [row.userId, row.permissionType])
)
const workspaceUserIds = Array.from(
new Set([workspaceRow.ownerId, ...wsPermissionRows.map((row) => row.userId)])
)
if (workspaceUserIds.length > 0) {
for (const memberUserId of workspaceUserIds) {
const wsPermission = wsPermissionByUser.get(memberUserId)
const isAdmin = memberUserId === workspaceRow.ownerId || wsPermission === 'admin'
await tx.insert(credentialMember).values({
id: generateId(),
credentialId,
userId: memberUserId,
role:
memberUserId === workspaceRow.ownerId || memberUserId === session.user.id
? 'admin'
: 'member',
role: isAdmin ? 'admin' : 'member',
status: 'active',
joinedAt: now,
invitedBy: session.user.id,
Expand Down
66 changes: 48 additions & 18 deletions apps/sim/lib/credentials/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ export async function getUserWorkspaceIds(userId: string): Promise<string[]> {
async function ensureWorkspaceCredentialMemberships(
credentialId: string,
memberUserIds: string[],
ownerUserId: string
ownerUserId: string,
wsPermissionByUser: Map<string, string>
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exported function now unused after callers removed

Low Severity

getWorkspaceMemberUserIds is still exported from environment.ts but is no longer called anywhere in the codebase. All callers were replaced in this PR with inline permission queries. This leaves dead code that could confuse future developers.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d1891c9. Configure here.

) {
if (!memberUserIds.length) return

Expand All @@ -87,7 +88,8 @@ async function ensureWorkspaceCredentialMemberships(
const now = new Date()

for (const memberUserId of memberUserIds) {
const targetRole = memberUserId === ownerUserId ? 'admin' : 'member'
const wsPermission = wsPermissionByUser.get(memberUserId)
const targetRole = memberUserId === ownerUserId || wsPermission === 'admin' ? 'admin' : 'member'
const existing = byUserId.get(memberUserId)
if (existing) {
if (existing.status === 'revoked') {
Expand Down Expand Up @@ -126,17 +128,27 @@ export async function syncWorkspaceEnvCredentials(params: {
actingUserId: string
}) {
const { workspaceId, envKeys, actingUserId } = params
const [[workspaceRow], memberUserIds] = await Promise.all([
const [[workspaceRow], wsPermissionRows] = await Promise.all([
db
.select({ ownerId: workspace.ownerId })
.from(workspace)
.where(eq(workspace.id, workspaceId))
.limit(1),
getWorkspaceMemberUserIds(workspaceId),
db
.select({ userId: permissions.userId, permissionType: permissions.permissionType })
.from(permissions)
.where(and(eq(permissions.entityType, 'workspace'), eq(permissions.entityId, workspaceId))),
Comment thread
cursor[bot] marked this conversation as resolved.
])

if (!workspaceRow) return

const wsPermissionByUser = new Map(
wsPermissionRows.map((row) => [row.userId, row.permissionType])
)
const memberUserIds = Array.from(
new Set([workspaceRow.ownerId, ...wsPermissionRows.map((row) => row.userId)])
)

const normalizedKeys = Array.from(new Set(envKeys.filter(Boolean)))
const existingCredentials = await db
.select({
Expand Down Expand Up @@ -182,7 +194,12 @@ export async function syncWorkspaceEnvCredentials(params: {
}

for (const credentialId of credentialIdsToEnsureMembership) {
await ensureWorkspaceCredentialMemberships(credentialId, memberUserIds, workspaceRow.ownerId)
await ensureWorkspaceCredentialMemberships(
credentialId,
memberUserIds,
workspaceRow.ownerId,
wsPermissionByUser
)
Comment thread
cursor[bot] marked this conversation as resolved.
}

if (normalizedKeys.length > 0) {
Expand Down Expand Up @@ -216,18 +233,27 @@ export async function createWorkspaceEnvCredentials(params: {
const keys = Array.from(new Set(newKeys.filter(Boolean)))
if (keys.length === 0) return

const [[workspaceRow], memberUserIds] = await Promise.all([
const [[workspaceRow], wsPermissionRows] = await Promise.all([
db
.select({ ownerId: workspace.ownerId })
.from(workspace)
.where(eq(workspace.id, workspaceId))
.limit(1),
getWorkspaceMemberUserIds(workspaceId),
db
.select({ userId: permissions.userId, permissionType: permissions.permissionType })
.from(permissions)
.where(and(eq(permissions.entityType, 'workspace'), eq(permissions.entityId, workspaceId))),
])

if (!workspaceRow) return

const ownerUserId = workspaceRow.ownerId
const wsPermissionByUser = new Map(
wsPermissionRows.map((row) => [row.userId, row.permissionType])
)
const memberUserIds = Array.from(
new Set([ownerUserId, ...wsPermissionRows.map((row) => row.userId)])
)
const now = new Date()
const createdIds: string[] = []

Expand Down Expand Up @@ -255,17 +281,21 @@ export async function createWorkspaceEnvCredentials(params: {

// Bulk-insert memberships for all new credentials × all workspace members in one query
const membershipValues = createdIds.flatMap((credentialId) =>
memberUserIds.map((memberUserId) => ({
id: generateId(),
credentialId,
userId: memberUserId,
role: (memberUserId === ownerUserId ? 'admin' : 'member') as 'admin' | 'member',
status: 'active' as const,
joinedAt: now,
invitedBy: ownerUserId,
createdAt: now,
updatedAt: now,
}))
memberUserIds.map((memberUserId) => {
const wsPermission = wsPermissionByUser.get(memberUserId)
const isAdmin = memberUserId === ownerUserId || wsPermission === 'admin'
return {
id: generateId(),
credentialId,
userId: memberUserId,
role: (isAdmin ? 'admin' : 'member') as 'admin' | 'member',
status: 'active' as const,
joinedAt: now,
invitedBy: ownerUserId,
createdAt: now,
updatedAt: now,
}
})
)

await db.insert(credentialMember).values(membershipValues).onConflictDoNothing()
Expand Down
Loading