Skip to content

Commit 5aa429e

Browse files
authored
fix(credentials): apply credential membership to single-credential lookups (#10317)
* fix(credentials): apply credential membership to single-credential lookups GET /api/auth/oauth/credentials?credentialId skipped the membership check whenever a workflowId was supplied, and GET /api/credentials?credentialId resolved on workspace scope alone. A workspace reader who is not a member of a credential could read its display name, provider, and scopes, which the list forms of both endpoints hide. - the OAuth lookup checks canUseCredential on every request; a workflowId still pins the credential's workspace as an extra constraint - the internal lookup filters its result through the list mode's own visibility rule (listVisibleWorkspaceCredentials + gated service-account filter), so a credential hidden from the list reads as absent * fix(credentials): answer unsupported credential lookups before the access check
1 parent 6419048 commit 5aa429e

3 files changed

Lines changed: 261 additions & 45 deletions

File tree

‎apps/sim/app/api/auth/oauth/credentials/route.ts‎

Lines changed: 25 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import {
1919
capabilityRefusal,
2020
isWorkspaceCapabilityWithheld,
2121
} from '@/lib/permission-groups/capability-assertions'
22-
import { checkWorkspaceAccess } from '@/lib/workspaces/permissions/utils'
22+
import { checkWorkspaceAccess, type WorkspaceAccess } from '@/lib/workspaces/permissions/utils'
2323

2424
export const dynamic = 'force-dynamic'
2525

@@ -142,9 +142,10 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
142142
effectiveWorkspaceId = workflowAuthorization.workflow?.workspaceId || undefined
143143
}
144144

145+
let workspaceAccess: WorkspaceAccess | undefined
145146
let requesterCanAdmin = false
146147
if (effectiveWorkspaceId) {
147-
const workspaceAccess = await checkWorkspaceAccess(effectiveWorkspaceId, requesterUserId)
148+
workspaceAccess = await checkWorkspaceAccess(effectiveWorkspaceId, requesterUserId)
148149
if (!workspaceAccess.hasAccess) {
149150
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
150151
}
@@ -194,7 +195,7 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
194195
* Integrations, and read it. Both are checked; either withholding is a
195196
* refusal, and the resolver memoizes the repeat when they are the same.
196197
*
197-
* Asked after each branch's own access check, never before: a caller who
198+
* Asked after the access check, never before: a caller who
198199
* may not reach this credential at all must not learn from the refusal
199200
* wording that the workspace it belongs to is one their group governs.
200201
*/
@@ -205,21 +206,29 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
205206
platformCredential.workspaceId
206207
)
207208

208-
if (platformCredential.type === 'service_account') {
209-
if (
210-
workflowId &&
211-
(!effectiveWorkspaceId || platformCredential.workspaceId !== effectiveWorkspaceId)
212-
) {
213-
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
214-
}
209+
// Before any access check, so an unsupported credential reads the same as an unknown id.
210+
if (
211+
platformCredential.type !== 'service_account' &&
212+
(platformCredential.type !== 'oauth' || !platformCredential.accountId)
213+
) {
214+
return NextResponse.json({ credentials: [] }, { status: 200 })
215+
}
215216

216-
if (!workflowId) {
217-
const access = await getCredentialActorContext(platformCredential.id, requesterUserId)
218-
if (!canUseCredential(access)) {
219-
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
220-
}
221-
}
217+
// A workflowId only pins the credential's workspace; membership is checked on every lookup.
218+
if (
219+
workflowId &&
220+
(!effectiveWorkspaceId || platformCredential.workspaceId !== effectiveWorkspaceId)
221+
) {
222+
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
223+
}
224+
const access = await getCredentialActorContext(platformCredential.id, requesterUserId, {
225+
workspaceAccess,
226+
})
227+
if (!canUseCredential(access)) {
228+
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
229+
}
222230

231+
if (platformCredential.type === 'service_account') {
223232
// permission-group-enforced: integrations.manage — the credentialId path carries its own workspace scope
224233
if (await credentialScopeWithheld()) {
225234
return NextResponse.json(
@@ -245,21 +254,6 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
245254
)
246255
}
247256

248-
if (platformCredential.type !== 'oauth' || !platformCredential.accountId) {
249-
return NextResponse.json({ credentials: [] }, { status: 200 })
250-
}
251-
252-
if (workflowId) {
253-
if (!effectiveWorkspaceId || platformCredential.workspaceId !== effectiveWorkspaceId) {
254-
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
255-
}
256-
} else {
257-
const access = await getCredentialActorContext(platformCredential.id, requesterUserId)
258-
if (!canUseCredential(access)) {
259-
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
260-
}
261-
}
262-
263257
// permission-group-enforced: integrations.manage — the credentialId path carries its own workspace scope
264258
if (await credentialScopeWithheld()) {
265259
return NextResponse.json(

‎apps/sim/lib/credentials/application/crud.ts‎

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -137,33 +137,38 @@ export const listInternalCredentials = defineAuthorizedWorkspaceUseCase({
137137
},
138138
authorizationOptions: {},
139139
async execute({ principal, input, context }): Promise<ListInternalCredentialsResult> {
140+
const userId = requirePrincipalSubjectUserId(principal)
141+
const workspaceAccess = await checkWorkspaceAccess(context.workspaceId, userId)
142+
const viewer = { userId, organizationId: context.workspaceOrganizationId }
140143
if (input.credentialId) {
141-
return {
142-
mode: 'lookup',
143-
credential: await findWorkspaceCredentialLookup({
144-
workspaceId: context.workspaceId,
145-
credentialId: input.credentialId,
146-
userId: requirePrincipalSubjectUserId(principal),
147-
}),
148-
}
144+
const found = await findWorkspaceCredentialLookup({
145+
workspaceId: context.workspaceId,
146+
credentialId: input.credentialId,
147+
userId,
148+
})
149+
if (!found) return { mode: 'lookup', credential: null }
150+
// Visibility is the list mode's own rule, so a credential hidden there reads as absent here.
151+
const page = await listVisibleWorkspaceCredentials({
152+
workspaceId: context.workspaceId,
153+
userId,
154+
workspaceAccess,
155+
ids: [found.id],
156+
})
157+
const [visible] = await filterGatedServiceAccountCredentials(page.data, viewer)
158+
return { mode: 'lookup', credential: visible ? found : null }
149159
}
150160

151-
const userId = requirePrincipalSubjectUserId(principal)
152161
if (!input.type || input.type === 'oauth') {
153162
await syncWorkspaceOAuthCredentialsForUser({ workspaceId: context.workspaceId, userId })
154163
}
155-
const workspaceAccess = await checkWorkspaceAccess(context.workspaceId, userId)
156164
const page = await listVisibleWorkspaceCredentials({
157165
workspaceId: context.workspaceId,
158166
userId,
159167
workspaceAccess,
160168
types: input.type ? [input.type] : undefined,
161169
providerId: input.providerId,
162170
})
163-
const credentials = await filterGatedServiceAccountCredentials(page.data, {
164-
userId,
165-
organizationId: context.workspaceOrganizationId,
166-
})
171+
const credentials = await filterGatedServiceAccountCredentials(page.data, viewer)
167172
return { mode: 'list', credentials }
168173
},
169174
})
Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
import { db } from '@sim/db'
2+
import {
3+
account,
4+
credential,
5+
credentialMember,
6+
permissions,
7+
user,
8+
workflow,
9+
workspace,
10+
} from '@sim/db/schema'
11+
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
12+
import { createSessionPrincipal } from '@sim/testing/factories/principal.factory'
13+
import { createRouteContext } from '@sim/testing/helpers/http'
14+
import { createMockRequest } from '@sim/testing/mocks/request.mock'
15+
import { generateId } from '@sim/utils/id'
16+
import { eq, inArray } from 'drizzle-orm'
17+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
18+
19+
const { sessionUser } = vi.hoisted(() => ({ sessionUser: { id: '' } }))
20+
vi.mock('@/lib/auth/hybrid', async (importOriginal) => ({
21+
...(await importOriginal<typeof import('@/lib/auth/hybrid')>()),
22+
checkSessionOrInternalAuth: async () => ({
23+
success: true,
24+
userId: sessionUser.id,
25+
authType: 'session',
26+
}),
27+
}))
28+
29+
import { listInternalCredentials } from '@/lib/credentials/application/crud'
30+
import { GET } from '@/app/api/auth/oauth/credentials/route'
31+
32+
/**
33+
* Single-credential lookups must apply the same credential-membership rule as the
34+
* list endpoints: a workspace teammate who is not a member of a connection never
35+
* learns its account identity, provider, or scopes.
36+
*/
37+
const ownerId = generateId()
38+
const memberId = generateId()
39+
const outsiderId = generateId()
40+
const adminId = generateId()
41+
const userIds = [ownerId, memberId, outsiderId, adminId]
42+
const workspaceId = generateId()
43+
const workflowId = generateId()
44+
const accountId = generateId()
45+
const oauthCredentialId = generateId()
46+
const serviceAccountCredentialId = generateId()
47+
const personalEnvCredentialId = generateId()
48+
49+
async function lookupOAuth(userId: string, query: Record<string, string>) {
50+
sessionUser.id = userId
51+
const params = new URLSearchParams(query).toString()
52+
const response = await GET(
53+
createMockRequest({ method: 'GET', url: `/api/auth/oauth/credentials?${params}` }),
54+
createRouteContext({})
55+
)
56+
const body = (await response.json()) as { credentials?: Array<{ name: string }> }
57+
return { status: response.status, names: body.credentials?.map((row) => row.name) }
58+
}
59+
60+
async function lookupInternal(userId: string, credentialId: string) {
61+
const result = await listInternalCredentials.execute({
62+
principal: createSessionPrincipal({ userId }),
63+
input: { workspaceId, credentialId },
64+
})
65+
if (result.mode !== 'lookup') throw new Error('Expected a lookup result')
66+
return result.credential?.displayName ?? null
67+
}
68+
69+
beforeAll(async () => {
70+
const now = new Date()
71+
await db.insert(user).values(
72+
userIds.map((id) => ({
73+
id,
74+
name: id,
75+
email: `${id}@credential-lookup.invalid`,
76+
emailVerified: true,
77+
createdAt: now,
78+
updatedAt: now,
79+
}))
80+
)
81+
await insertWorkspaceFixture(db, {
82+
id: workspaceId,
83+
name: 'Credential lookup',
84+
ownerId,
85+
billedAccountUserId: ownerId,
86+
})
87+
await db.insert(permissions).values(
88+
userIds.map((userId) => ({
89+
id: generateId(),
90+
userId,
91+
entityType: 'workspace' as const,
92+
entityId: workspaceId,
93+
permissionType: userId === adminId ? ('admin' as const) : ('read' as const),
94+
}))
95+
)
96+
await db.insert(workflow).values({
97+
id: workflowId,
98+
userId: ownerId,
99+
workspaceId,
100+
name: 'Credential lookup',
101+
lastSynced: now,
102+
createdAt: now,
103+
updatedAt: now,
104+
})
105+
await db.insert(account).values({
106+
id: accountId,
107+
accountId: 'owner@example.com',
108+
providerId: 'google-email',
109+
userId: ownerId,
110+
scope: 'https://www.googleapis.com/auth/gmail.send',
111+
createdAt: now,
112+
updatedAt: now,
113+
})
114+
await db.insert(credential).values([
115+
{
116+
id: oauthCredentialId,
117+
workspaceId,
118+
type: 'oauth',
119+
displayName: 'owner@example.com',
120+
providerId: 'google-email',
121+
accountId,
122+
createdBy: ownerId,
123+
},
124+
{
125+
id: serviceAccountCredentialId,
126+
workspaceId,
127+
type: 'service_account',
128+
displayName: 'robot@example.iam.gserviceaccount.com',
129+
providerId: 'google-service-account',
130+
createdBy: ownerId,
131+
},
132+
{
133+
id: personalEnvCredentialId,
134+
workspaceId,
135+
type: 'env_personal',
136+
displayName: 'OWNER_PRIVATE_KEY',
137+
envKey: 'OWNER_PRIVATE_KEY',
138+
envOwnerUserId: ownerId,
139+
createdBy: ownerId,
140+
},
141+
])
142+
await db.insert(credentialMember).values([
143+
...[oauthCredentialId, serviceAccountCredentialId, personalEnvCredentialId].map(
144+
(credentialId) => ({
145+
id: generateId(),
146+
credentialId,
147+
userId: ownerId,
148+
role: 'admin' as const,
149+
status: 'active' as const,
150+
})
151+
),
152+
...[oauthCredentialId, serviceAccountCredentialId].map((credentialId) => ({
153+
id: generateId(),
154+
credentialId,
155+
userId: memberId,
156+
role: 'member' as const,
157+
status: 'active' as const,
158+
})),
159+
])
160+
})
161+
162+
afterAll(async () => {
163+
await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId))
164+
await db.delete(user).where(inArray(user.id, userIds))
165+
})
166+
167+
describe('GET /api/auth/oauth/credentials by credentialId', () => {
168+
it.each([
169+
['an OAuth', oauthCredentialId],
170+
['a service-account', serviceAccountCredentialId],
171+
])('refuses a non-member who pins %s credential to its workflow', async (_, credentialId) => {
172+
expect(await lookupOAuth(outsiderId, { credentialId, workflowId })).toEqual({
173+
status: 403,
174+
names: undefined,
175+
})
176+
})
177+
178+
it('answers a non-member about an unsupported credential exactly as about an unknown id', async () => {
179+
const unknown = await lookupOAuth(outsiderId, { credentialId: generateId(), workflowId })
180+
expect(unknown).toEqual({ status: 200, names: [] })
181+
expect(
182+
await lookupOAuth(outsiderId, { credentialId: personalEnvCredentialId, workflowId })
183+
).toEqual(unknown)
184+
})
185+
186+
it.each([
187+
['a credential member', memberId],
188+
['a workspace admin', adminId],
189+
])('returns the credential to %s pinning its workflow', async (_, userId) => {
190+
expect(await lookupOAuth(userId, { credentialId: oauthCredentialId, workflowId })).toEqual({
191+
status: 200,
192+
names: ['owner@example.com'],
193+
})
194+
})
195+
})
196+
197+
describe('listInternalCredentials lookup mode', () => {
198+
it('reads a credential the caller is not a member of as absent', async () => {
199+
expect(await lookupInternal(outsiderId, oauthCredentialId)).toBeNull()
200+
})
201+
202+
it('reads a legacy account id the caller is not a member of as absent', async () => {
203+
expect(await lookupInternal(outsiderId, accountId)).toBeNull()
204+
})
205+
206+
it("hides another user's personal environment variable, even from a workspace admin", async () => {
207+
expect(await lookupInternal(adminId, personalEnvCredentialId)).toBeNull()
208+
expect(await lookupInternal(ownerId, personalEnvCredentialId)).toBe('OWNER_PRIVATE_KEY')
209+
})
210+
211+
it.each([
212+
['a credential member', memberId],
213+
['a workspace admin', adminId],
214+
])('returns the credential to %s', async (_, userId) => {
215+
expect(await lookupInternal(userId, oauthCredentialId)).toBe('owner@example.com')
216+
})
217+
})

0 commit comments

Comments
 (0)