import { db } from '@sim/db' import { account, credential, credentialMember, workflow as workflowTable } from '@sim/db/schema' import { and, eq } from 'drizzle-orm' import type { NextRequest } from 'next/server' import { AuthType, checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils' export interface CredentialAccessResult { ok: boolean error?: string authType?: typeof AuthType.SESSION | typeof AuthType.INTERNAL_JWT requesterUserId?: string credentialOwnerUserId?: string workspaceId?: string resolvedCredentialId?: string credentialType?: 'oauth' | 'service_account' } /** * Centralizes auth + credential membership checks for OAuth usage. * - Workspace-scoped credential IDs enforce active credential_member access. * - Legacy account IDs are resolved to workspace-scoped credentials when workflowId is provided. * - Direct legacy account-ID access without workflowId is restricted to account owners only. */ export async function authorizeCredentialUse( request: NextRequest, params: { credentialId: string workflowId?: string requireWorkflowIdForInternal?: boolean callerUserId?: string } ): Promise { const { credentialId, workflowId, requireWorkflowIdForInternal = true, callerUserId } = params const auth = await checkSessionOrInternalAuth(request, { requireWorkflowId: requireWorkflowIdForInternal, }) if (!auth.success || !auth.userId) { return { ok: false, error: auth.error || 'Authentication required' } } if ( auth.authType === AuthType.INTERNAL_JWT && callerUserId !== undefined && callerUserId !== auth.userId ) { return { ok: false, error: 'Caller user does not match internal token subject' } } const actingUserId = auth.userId const [workflowContext] = workflowId ? await db .select({ workspaceId: workflowTable.workspaceId }) .from(workflowTable) .where(eq(workflowTable.id, workflowId)) .limit(1) : [null] if (workflowId && (!workflowContext || !workflowContext.workspaceId)) { return { ok: false, error: 'Workflow not found' } } const [platformCredential] = await db .select({ id: credential.id, workspaceId: credential.workspaceId, type: credential.type, accountId: credential.accountId, }) .from(credential) .where(eq(credential.id, credentialId)) .limit(1) if (platformCredential) { if (platformCredential.type === 'service_account') { if (workflowContext && workflowContext.workspaceId !== platformCredential.workspaceId) { return { ok: false, error: 'Credential is not accessible from this workflow workspace' } } const requesterPerm = await getUserEntityPermissions( actingUserId, 'workspace', platformCredential.workspaceId ) const [membership] = await db .select({ id: credentialMember.id }) .from(credentialMember) .where( and( eq(credentialMember.credentialId, platformCredential.id), eq(credentialMember.userId, actingUserId), eq(credentialMember.status, 'active') ) ) .limit(1) if (requesterPerm === null) { return { ok: false, error: 'You do not have access to this workspace.' } } if (!membership && requesterPerm !== 'admin') { return { ok: false, error: 'You do not have access to this credential. Ask the credential admin to add you as a member.', } } return { ok: true, authType: auth.authType as CredentialAccessResult['authType'], requesterUserId: auth.userId, credentialOwnerUserId: actingUserId, workspaceId: platformCredential.workspaceId, resolvedCredentialId: platformCredential.id, credentialType: 'service_account', } } if (platformCredential.type !== 'oauth' || !platformCredential.accountId) { return { ok: false, error: 'Unsupported credential type for OAuth access' } } if (workflowContext && workflowContext.workspaceId !== platformCredential.workspaceId) { return { ok: false, error: 'Credential is not accessible from this workflow workspace' } } const [accountRow] = await db .select({ userId: account.userId }) .from(account) .where(eq(account.id, platformCredential.accountId)) .limit(1) if (!accountRow) { return { ok: false, error: 'Credential account not found' } } const requesterPerm = await getUserEntityPermissions( actingUserId, 'workspace', platformCredential.workspaceId ) const [membership] = await db .select({ id: credentialMember.id }) .from(credentialMember) .where( and( eq(credentialMember.credentialId, platformCredential.id), eq(credentialMember.userId, actingUserId), eq(credentialMember.status, 'active') ) ) .limit(1) if (requesterPerm === null) { return { ok: false, error: 'You do not have access to this workspace.', } } if (!membership && requesterPerm !== 'admin') { return { ok: false, error: `You do not have access to this credential. Ask the credential admin to add you as a member.`, } } const ownerPerm = await getUserEntityPermissions( accountRow.userId, 'workspace', platformCredential.workspaceId ) if (ownerPerm === null) { return { ok: false, error: 'Unauthorized' } } return { ok: true, authType: auth.authType as CredentialAccessResult['authType'], requesterUserId: auth.userId, credentialOwnerUserId: accountRow.userId, workspaceId: platformCredential.workspaceId, resolvedCredentialId: platformCredential.accountId, credentialType: 'oauth', } } if (workflowContext?.workspaceId) { const [workspaceCredential] = await db .select({ id: credential.id, workspaceId: credential.workspaceId, accountId: credential.accountId, }) .from(credential) .where( and( eq(credential.type, 'oauth'), eq(credential.workspaceId, workflowContext.workspaceId), eq(credential.accountId, credentialId) ) ) .limit(1) if (!workspaceCredential?.accountId) { return { ok: false, error: 'Credential not found' } } const [accountRow] = await db .select({ userId: account.userId }) .from(account) .where(eq(account.id, workspaceCredential.accountId)) .limit(1) if (!accountRow) { return { ok: false, error: 'Credential account not found' } } const [membership] = await db .select({ id: credentialMember.id }) .from(credentialMember) .where( and( eq(credentialMember.credentialId, workspaceCredential.id), eq(credentialMember.userId, actingUserId), eq(credentialMember.status, 'active') ) ) .limit(1) if (!membership) { const requesterPerm = await getUserEntityPermissions( actingUserId, 'workspace', workflowContext.workspaceId ) if (requesterPerm !== 'admin') { return { ok: false, error: 'You do not have access to this credential. Ask the credential admin to add you as a member.', } } } const ownerPerm = await getUserEntityPermissions( accountRow.userId, 'workspace', workflowContext.workspaceId ) if (ownerPerm === null) { return { ok: false, error: 'Unauthorized' } } return { ok: true, authType: auth.authType as CredentialAccessResult['authType'], requesterUserId: auth.userId, credentialOwnerUserId: accountRow.userId, workspaceId: workflowContext.workspaceId, resolvedCredentialId: workspaceCredential.accountId, credentialType: 'oauth', } } const [legacyAccount] = await db .select({ userId: account.userId }) .from(account) .where(eq(account.id, credentialId)) .limit(1) if (!legacyAccount) { return { ok: false, error: 'Credential not found' } } if (auth.authType === AuthType.INTERNAL_JWT) { return { ok: false, error: 'workflowId is required' } } if (auth.userId !== legacyAccount.userId) { return { ok: false, error: 'Unauthorized' } } return { ok: true, authType: auth.authType as CredentialAccessResult['authType'], requesterUserId: auth.userId, credentialOwnerUserId: legacyAccount.userId, resolvedCredentialId: credentialId, credentialType: 'oauth', } }