From 8e1867f2cbe5439caee46388c42679f29c623ec6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 16 Nov 2026 13:20:51 -0800 Subject: [PATCH 1/2] fix(gitlab): clarify permission validation failures --- .../gitlab/permission-config/prepare.test.ts | 90 +++++++++++++++++++ .../gitlab/permission-config/prepare.ts | 4 +- apps/sim/connectors/gitlab/permissions.ts | 55 ++++++++++-- 3 files changed, 142 insertions(+), 7 deletions(-) create mode 100644 apps/sim/connectors/gitlab/permission-config/prepare.test.ts diff --git a/apps/sim/connectors/gitlab/permission-config/prepare.test.ts b/apps/sim/connectors/gitlab/permission-config/prepare.test.ts new file mode 100644 index 00000000000..b6111ebd4e7 --- /dev/null +++ b/apps/sim/connectors/gitlab/permission-config/prepare.test.ts @@ -0,0 +1,90 @@ +import { + knowledgeSecureFetchMock, + knowledgeSecureFetchMockFns, +} from '@sim/testing/mocks/knowledge-secure-fetch.mock' +import { getMockLogger } from '@sim/testing/mocks/logger.mock' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/knowledge/documents/secure-fetch.server', () => knowledgeSecureFetchMock) + +import { OutboundRoutingError } from '@/lib/core/network/routing' +import { EGRESS_UNAVAILABLE_MESSAGE } from '@/lib/core/orchestration/types' +import { prepareGitLabPermissionChange } from '@/connectors/gitlab/permission-config/prepare' + +const fetchSource = knowledgeSecureFetchMockFns.mockSecureFetchWithRetry +const input = { + connectorType: 'gitlab', + accessMode: 'admin', + sourceConfig: { host: 'gitlab.example.com', project: 'group/project' }, + apiKey: 'test-private-token', +} + +describe('GitLab setup failures', () => { + it.each([ + { operation: 'account', status: 401, action: /token.*read_api/i }, + { operation: 'account', status: 404, action: /host.*API access/i }, + { operation: 'project', status: 403, action: /read_api.*access.*IP restrictions/i }, + { operation: 'project', status: 404, action: /project ID.*token access.*IP restrictions/i }, + ])( + 'identifies a $status during the $operation check without exposing provider content', + async ({ operation, status, action }) => { + if (operation === 'project') { + fetchSource.mockResolvedValueOnce(Response.json({ id: 1, state: 'active' })) + } + fetchSource.mockResolvedValueOnce( + new Response('Private upstream error page', { + status, + headers: { 'x-request-id': '01JEXAMPLECORRELATION' }, + }) + ) + + const result = prepareGitLabPermissionChange(input) + await expect(result).rejects.toMatchObject({ + code: 'validation', + message: expect.stringMatching(action), + }) + await expect(result).rejects.toMatchObject({ + message: expect.not.stringMatching( + /test-private-token|Private upstream|group\/project|gitlab\.example/ + ), + }) + const logs = getMockLogger('GitLabPermissions').warn.mock.calls + expect(logs).toEqual([ + [ + 'GitLab permission read failed', + { + operation, + status, + providerRequestId: '01JEXAMPLECORRELATION', + }, + ], + ]) + expect(fetchSource).toHaveBeenCalledTimes(operation === 'project' ? 2 : 1) + } + ) + + it.each([undefined, 'untrusted header text', 'x'.repeat(129)])( + 'omits absent or unsafe upstream correlation IDs (%s)', + async (requestId) => { + fetchSource.mockResolvedValueOnce( + new Response(null, { + status: 404, + headers: requestId ? { 'x-request-id': requestId } : undefined, + }) + ) + await expect(prepareGitLabPermissionChange(input)).rejects.toThrow() + expect(getMockLogger('GitLabPermissions').warn).toHaveBeenCalledWith( + 'GitLab permission read failed', + { operation: 'account', status: 404 } + ) + } + ) + + it('preserves an egress outage instead of blaming the GitLab credential', async () => { + fetchSource.mockRejectedValueOnce(new OutboundRoutingError('GATEWAY_UNAVAILABLE')) + await expect(prepareGitLabPermissionChange(input)).rejects.toMatchObject({ + code: 'unavailable', + message: EGRESS_UNAVAILABLE_MESSAGE, + }) + }) +}) diff --git a/apps/sim/connectors/gitlab/permission-config/prepare.ts b/apps/sim/connectors/gitlab/permission-config/prepare.ts index b695928cb3d..440c881e6b5 100644 --- a/apps/sim/connectors/gitlab/permission-config/prepare.ts +++ b/apps/sim/connectors/gitlab/permission-config/prepare.ts @@ -1,6 +1,6 @@ import { getErrorMessage } from '@sim/utils/errors' import { decryptApiKey, encryptApiKey } from '@/lib/api-key/crypto' -import { OrchestrationError } from '@/lib/core/orchestration/types' +import { asOrchestrationError, OrchestrationError } from '@/lib/core/orchestration/types' import { loadGitLabPermissionSnapshot, type PreparedGitLabPermissions, @@ -70,6 +70,8 @@ export async function prepareGitLabPermissionChange(input: { : ''), input.sourceConfig ).catch((error: unknown) => { + const classified = asOrchestrationError(error) + if (classified) throw classified throw new OrchestrationError( 'validation', getErrorMessage(error, 'Unable to validate the GitLab token and project.') diff --git a/apps/sim/connectors/gitlab/permissions.ts b/apps/sim/connectors/gitlab/permissions.ts index d20d3813842..6020342e6a3 100644 --- a/apps/sim/connectors/gitlab/permissions.ts +++ b/apps/sim/connectors/gitlab/permissions.ts @@ -1,3 +1,4 @@ +import { createLogger } from '@sim/logger' import { normalizeEmail } from '@sim/utils/string' import { groupToken, sortAccessTokens, userToken } from '@/lib/knowledge/access/tokens' import { secureFetchWithRetry } from '@/lib/knowledge/documents/secure-fetch.server' @@ -13,6 +14,8 @@ import { import type { ConnectorDirectory, ExternalDocument } from '@/connectors/types' import { normalizeGitLabHost } from '@/tools/gitlab/utils' +const logger = createLogger('GitLabPermissions') + const MAX_DIRECTORY_PAGES = 500 const PAGE_SIZE = 100 const MAX_RESPONSE_BYTES = 4 * 1024 * 1024 @@ -39,13 +42,14 @@ export async function validateGitLabCsvToken( signal?: AbortSignal ): Promise<{ host: string; projectId: number; projectPath: string }> { const { base, project } = sourceAddress(sourceConfig) - const viewer = await read(`${base}/user`, token, true, signal) + const viewer = await read(`${base}/user`, token, 'account', true, signal) if (viewer.state !== 'active' || viewer.locked === true || !Number.isSafeInteger(viewer.id)) { throw new Error('An active GitLab identity with read_api access is required') } const record = await read( `${base}/projects/${project}`, token, + 'project', true, signal ) @@ -113,6 +117,7 @@ function sourceAddress(sourceConfig: Record) { async function read( url: string, token: string, + operation: 'account' | 'project', validating = false, signal?: AbortSignal ): Promise { @@ -125,7 +130,34 @@ async function read( }, { ...(validating ? VALIDATE_RETRY_OPTIONS : {}), maxResponseBytes: MAX_RESPONSE_BYTES, signal } ) - if (!response.ok) throw new Error(`GitLab permission lookup failed (${response.status})`) + if (!response.ok) { + const requestId = response.headers.get('x-request-id') + logger.warn('GitLab permission read failed', { + operation, + status: response.status, + ...(requestId && /^[a-zA-Z0-9_-]{1,128}$/.test(requestId) + ? { providerRequestId: requestId } + : {}), + }) + if (response.status === 401) { + throw new Error('GitLab did not accept the token. Use a valid token with read_api scope.') + } + if (response.status === 403) { + throw new Error( + 'GitLab denied access. Check read_api scope, token access, and IP restrictions.' + ) + } + if (response.status === 404) { + throw new Error( + operation === 'project' + ? 'Could not access this GitLab project. Check the project ID or full path, token access, and IP restrictions.' + : 'Could not verify the GitLab account. Check the host and API access.' + ) + } + throw new Error( + `GitLab could not verify ${operation} access (HTTP ${response.status}). Try again.` + ) + } return (await response.json()) as T } @@ -136,7 +168,12 @@ export async function validateGitLabPermissionToken( ): Promise { await requireAdministrator(token, sourceConfig) const { base, project } = sourceAddress(sourceConfig) - const record = await read(`${base}/projects/${project}`, token, true) + const record = await read( + `${base}/projects/${project}`, + token, + 'project', + true + ) await discoverGitLabPermissionPolicy(token, sourceConfig, record, true) } @@ -146,7 +183,7 @@ async function requireAdministrator( signal?: AbortSignal ): Promise { const { base } = sourceAddress(sourceConfig) - const viewer = await read(`${base}/user`, token, true, signal) + const viewer = await read(`${base}/user`, token, 'account', true, signal) if (viewer.is_admin !== true || viewer.state !== 'active' || viewer.locked === true) { throw new Error( 'Mirror source permissions requires an active GitLab instance administrator token with read_api access' @@ -295,7 +332,7 @@ async function loadSnapshot( await requireAdministrator(token, config, signal) const { base, project } = sourceAddress(config) const [record, users, members] = await Promise.all([ - read(`${base}/projects/${project}`, token, false, signal), + read(`${base}/projects/${project}`, token, 'project', false, signal), listAll( `${base}/users?pagination=keyset&order_by=id&sort=asc`, token, @@ -347,7 +384,13 @@ export async function openGitLabDirectory( } } const { tenant, base, project } = sourceAddress(config) - const identity = await read<{ id: number }>(`${base}/projects/${project}`, token, false, signal) + const identity = await read<{ id: number }>( + `${base}/projects/${project}`, + token, + 'project', + false, + signal + ) if (!Number.isInteger(identity.id)) throw new Error('GitLab did not return a project identity') const groups = FEATURES.map((feature) => ({ id: groupId(identity.id, feature) })) let pending: Promise | undefined From 864912019a33695f0dbca8a3831741bd648c6fcf Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 16 Nov 2026 13:27:34 -0800 Subject: [PATCH 2/2] fix(gitlab): preserve missing routing scope failures --- .../sim/connectors/gitlab/permission-config/prepare.test.ts | 6 ++++++ apps/sim/connectors/gitlab/permission-config/prepare.ts | 2 ++ 2 files changed, 8 insertions(+) diff --git a/apps/sim/connectors/gitlab/permission-config/prepare.test.ts b/apps/sim/connectors/gitlab/permission-config/prepare.test.ts index b6111ebd4e7..b29bc99d033 100644 --- a/apps/sim/connectors/gitlab/permission-config/prepare.test.ts +++ b/apps/sim/connectors/gitlab/permission-config/prepare.test.ts @@ -87,4 +87,10 @@ describe('GitLab setup failures', () => { message: EGRESS_UNAVAILABLE_MESSAGE, }) }) + + it('keeps a missing internal routing scope out of GitLab validation errors', async () => { + const error = new OutboundRoutingError('MISSING_SCOPE') + fetchSource.mockRejectedValueOnce(error) + await expect(prepareGitLabPermissionChange(input)).rejects.toBe(error) + }) }) diff --git a/apps/sim/connectors/gitlab/permission-config/prepare.ts b/apps/sim/connectors/gitlab/permission-config/prepare.ts index 440c881e6b5..b1ea162d7a4 100644 --- a/apps/sim/connectors/gitlab/permission-config/prepare.ts +++ b/apps/sim/connectors/gitlab/permission-config/prepare.ts @@ -1,5 +1,6 @@ import { getErrorMessage } from '@sim/utils/errors' import { decryptApiKey, encryptApiKey } from '@/lib/api-key/crypto' +import { OutboundRoutingError } from '@/lib/core/network/routing' import { asOrchestrationError, OrchestrationError } from '@/lib/core/orchestration/types' import { loadGitLabPermissionSnapshot, @@ -72,6 +73,7 @@ export async function prepareGitLabPermissionChange(input: { ).catch((error: unknown) => { const classified = asOrchestrationError(error) if (classified) throw classified + if (error instanceof OutboundRoutingError) throw error throw new OrchestrationError( 'validation', getErrorMessage(error, 'Unable to validate the GitLab token and project.')