Skip to content

Commit 6bfe67f

Browse files
authored
fix(gitlab): clarify permission validation failures (#10096)
Clarify GitLab account and project validation failures, add safe correlation metadata, and preserve routing-error classification.
1 parent 75334c3 commit 6bfe67f

3 files changed

Lines changed: 150 additions & 7 deletions

File tree

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import {
2+
knowledgeSecureFetchMock,
3+
knowledgeSecureFetchMockFns,
4+
} from '@sim/testing/mocks/knowledge-secure-fetch.mock'
5+
import { getMockLogger } from '@sim/testing/mocks/logger.mock'
6+
import { describe, expect, it, vi } from 'vitest'
7+
8+
vi.mock('@/lib/knowledge/documents/secure-fetch.server', () => knowledgeSecureFetchMock)
9+
10+
import { OutboundRoutingError } from '@/lib/core/network/routing'
11+
import { EGRESS_UNAVAILABLE_MESSAGE } from '@/lib/core/orchestration/types'
12+
import { prepareGitLabPermissionChange } from '@/connectors/gitlab/permission-config/prepare'
13+
14+
const fetchSource = knowledgeSecureFetchMockFns.mockSecureFetchWithRetry
15+
const input = {
16+
connectorType: 'gitlab',
17+
accessMode: 'admin',
18+
sourceConfig: { host: 'gitlab.example.com', project: 'group/project' },
19+
apiKey: 'test-private-token',
20+
}
21+
22+
describe('GitLab setup failures', () => {
23+
it.each([
24+
{ operation: 'account', status: 401, action: /token.*read_api/i },
25+
{ operation: 'account', status: 404, action: /host.*API access/i },
26+
{ operation: 'project', status: 403, action: /read_api.*access.*IP restrictions/i },
27+
{ operation: 'project', status: 404, action: /project ID.*token access.*IP restrictions/i },
28+
])(
29+
'identifies a $status during the $operation check without exposing provider content',
30+
async ({ operation, status, action }) => {
31+
if (operation === 'project') {
32+
fetchSource.mockResolvedValueOnce(Response.json({ id: 1, state: 'active' }))
33+
}
34+
fetchSource.mockResolvedValueOnce(
35+
new Response('Private upstream error page', {
36+
status,
37+
headers: { 'x-request-id': '01JEXAMPLECORRELATION' },
38+
})
39+
)
40+
41+
const result = prepareGitLabPermissionChange(input)
42+
await expect(result).rejects.toMatchObject({
43+
code: 'validation',
44+
message: expect.stringMatching(action),
45+
})
46+
await expect(result).rejects.toMatchObject({
47+
message: expect.not.stringMatching(
48+
/test-private-token|Private upstream|group\/project|gitlab\.example/
49+
),
50+
})
51+
const logs = getMockLogger('GitLabPermissions').warn.mock.calls
52+
expect(logs).toEqual([
53+
[
54+
'GitLab permission read failed',
55+
{
56+
operation,
57+
status,
58+
providerRequestId: '01JEXAMPLECORRELATION',
59+
},
60+
],
61+
])
62+
expect(fetchSource).toHaveBeenCalledTimes(operation === 'project' ? 2 : 1)
63+
}
64+
)
65+
66+
it.each([undefined, 'untrusted header text', 'x'.repeat(129)])(
67+
'omits absent or unsafe upstream correlation IDs (%s)',
68+
async (requestId) => {
69+
fetchSource.mockResolvedValueOnce(
70+
new Response(null, {
71+
status: 404,
72+
headers: requestId ? { 'x-request-id': requestId } : undefined,
73+
})
74+
)
75+
await expect(prepareGitLabPermissionChange(input)).rejects.toThrow()
76+
expect(getMockLogger('GitLabPermissions').warn).toHaveBeenCalledWith(
77+
'GitLab permission read failed',
78+
{ operation: 'account', status: 404 }
79+
)
80+
}
81+
)
82+
83+
it('preserves an egress outage instead of blaming the GitLab credential', async () => {
84+
fetchSource.mockRejectedValueOnce(new OutboundRoutingError('GATEWAY_UNAVAILABLE'))
85+
await expect(prepareGitLabPermissionChange(input)).rejects.toMatchObject({
86+
code: 'unavailable',
87+
message: EGRESS_UNAVAILABLE_MESSAGE,
88+
})
89+
})
90+
91+
it('keeps a missing internal routing scope out of GitLab validation errors', async () => {
92+
const error = new OutboundRoutingError('MISSING_SCOPE')
93+
fetchSource.mockRejectedValueOnce(error)
94+
await expect(prepareGitLabPermissionChange(input)).rejects.toBe(error)
95+
})
96+
})

‎apps/sim/connectors/gitlab/permission-config/prepare.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { getErrorMessage } from '@sim/utils/errors'
22
import { decryptApiKey, encryptApiKey } from '@/lib/api-key/crypto'
3-
import { OrchestrationError } from '@/lib/core/orchestration/types'
3+
import { OutboundRoutingError } from '@/lib/core/network/routing'
4+
import { asOrchestrationError, OrchestrationError } from '@/lib/core/orchestration/types'
45
import {
56
loadGitLabPermissionSnapshot,
67
type PreparedGitLabPermissions,
@@ -70,6 +71,9 @@ export async function prepareGitLabPermissionChange(input: {
7071
: ''),
7172
input.sourceConfig
7273
).catch((error: unknown) => {
74+
const classified = asOrchestrationError(error)
75+
if (classified) throw classified
76+
if (error instanceof OutboundRoutingError) throw error
7377
throw new OrchestrationError(
7478
'validation',
7579
getErrorMessage(error, 'Unable to validate the GitLab token and project.')

‎apps/sim/connectors/gitlab/permissions.ts‎

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { createLogger } from '@sim/logger'
12
import { normalizeEmail } from '@sim/utils/string'
23
import { groupToken, sortAccessTokens, userToken } from '@/lib/knowledge/access/tokens'
34
import { secureFetchWithRetry } from '@/lib/knowledge/documents/secure-fetch.server'
@@ -13,6 +14,8 @@ import {
1314
import type { ConnectorDirectory, ExternalDocument } from '@/connectors/types'
1415
import { normalizeGitLabHost } from '@/tools/gitlab/utils'
1516

17+
const logger = createLogger('GitLabPermissions')
18+
1619
const MAX_DIRECTORY_PAGES = 500
1720
const PAGE_SIZE = 100
1821
const MAX_RESPONSE_BYTES = 4 * 1024 * 1024
@@ -39,13 +42,14 @@ export async function validateGitLabCsvToken(
3942
signal?: AbortSignal
4043
): Promise<{ host: string; projectId: number; projectPath: string }> {
4144
const { base, project } = sourceAddress(sourceConfig)
42-
const viewer = await read<GitLabPermissionUser>(`${base}/user`, token, true, signal)
45+
const viewer = await read<GitLabPermissionUser>(`${base}/user`, token, 'account', true, signal)
4346
if (viewer.state !== 'active' || viewer.locked === true || !Number.isSafeInteger(viewer.id)) {
4447
throw new Error('An active GitLab identity with read_api access is required')
4548
}
4649
const record = await read<GitLabPermissionProject>(
4750
`${base}/projects/${project}`,
4851
token,
52+
'project',
4953
true,
5054
signal
5155
)
@@ -113,6 +117,7 @@ function sourceAddress(sourceConfig: Record<string, unknown>) {
113117
async function read<T>(
114118
url: string,
115119
token: string,
120+
operation: 'account' | 'project',
116121
validating = false,
117122
signal?: AbortSignal
118123
): Promise<T> {
@@ -125,7 +130,34 @@ async function read<T>(
125130
},
126131
{ ...(validating ? VALIDATE_RETRY_OPTIONS : {}), maxResponseBytes: MAX_RESPONSE_BYTES, signal }
127132
)
128-
if (!response.ok) throw new Error(`GitLab permission lookup failed (${response.status})`)
133+
if (!response.ok) {
134+
const requestId = response.headers.get('x-request-id')
135+
logger.warn('GitLab permission read failed', {
136+
operation,
137+
status: response.status,
138+
...(requestId && /^[a-zA-Z0-9_-]{1,128}$/.test(requestId)
139+
? { providerRequestId: requestId }
140+
: {}),
141+
})
142+
if (response.status === 401) {
143+
throw new Error('GitLab did not accept the token. Use a valid token with read_api scope.')
144+
}
145+
if (response.status === 403) {
146+
throw new Error(
147+
'GitLab denied access. Check read_api scope, token access, and IP restrictions.'
148+
)
149+
}
150+
if (response.status === 404) {
151+
throw new Error(
152+
operation === 'project'
153+
? 'Could not access this GitLab project. Check the project ID or full path, token access, and IP restrictions.'
154+
: 'Could not verify the GitLab account. Check the host and API access.'
155+
)
156+
}
157+
throw new Error(
158+
`GitLab could not verify ${operation} access (HTTP ${response.status}). Try again.`
159+
)
160+
}
129161
return (await response.json()) as T
130162
}
131163

@@ -136,7 +168,12 @@ export async function validateGitLabPermissionToken(
136168
): Promise<void> {
137169
await requireAdministrator(token, sourceConfig)
138170
const { base, project } = sourceAddress(sourceConfig)
139-
const record = await read<GitLabPermissionProject>(`${base}/projects/${project}`, token, true)
171+
const record = await read<GitLabPermissionProject>(
172+
`${base}/projects/${project}`,
173+
token,
174+
'project',
175+
true
176+
)
140177
await discoverGitLabPermissionPolicy(token, sourceConfig, record, true)
141178
}
142179

@@ -146,7 +183,7 @@ async function requireAdministrator(
146183
signal?: AbortSignal
147184
): Promise<void> {
148185
const { base } = sourceAddress(sourceConfig)
149-
const viewer = await read<GitLabPermissionUser>(`${base}/user`, token, true, signal)
186+
const viewer = await read<GitLabPermissionUser>(`${base}/user`, token, 'account', true, signal)
150187
if (viewer.is_admin !== true || viewer.state !== 'active' || viewer.locked === true) {
151188
throw new Error(
152189
'Mirror source permissions requires an active GitLab instance administrator token with read_api access'
@@ -295,7 +332,7 @@ async function loadSnapshot(
295332
await requireAdministrator(token, config, signal)
296333
const { base, project } = sourceAddress(config)
297334
const [record, users, members] = await Promise.all([
298-
read<GitLabPermissionProject>(`${base}/projects/${project}`, token, false, signal),
335+
read<GitLabPermissionProject>(`${base}/projects/${project}`, token, 'project', false, signal),
299336
listAll<GitLabPermissionUser>(
300337
`${base}/users?pagination=keyset&order_by=id&sort=asc`,
301338
token,
@@ -347,7 +384,13 @@ export async function openGitLabDirectory(
347384
}
348385
}
349386
const { tenant, base, project } = sourceAddress(config)
350-
const identity = await read<{ id: number }>(`${base}/projects/${project}`, token, false, signal)
387+
const identity = await read<{ id: number }>(
388+
`${base}/projects/${project}`,
389+
token,
390+
'project',
391+
false,
392+
signal
393+
)
351394
if (!Number.isInteger(identity.id)) throw new Error('GitLab did not return a project identity')
352395
const groups = FEATURES.map((feature) => ({ id: groupId(identity.id, feature) }))
353396
let pending: Promise<PermissionSnapshot> | undefined

0 commit comments

Comments
 (0)