|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { safeCompare } from '@sim/security/compare' |
| 3 | +import { generateId } from '@sim/utils/id' |
| 4 | +import { NextResponse } from 'next/server' |
| 5 | +import { getNotificationUrl, getProviderConfig } from '@/lib/webhooks/provider-subscription-utils' |
| 6 | +import type { |
| 7 | + AuthContext, |
| 8 | + DeleteSubscriptionContext, |
| 9 | + EventMatchContext, |
| 10 | + FormatInputContext, |
| 11 | + FormatInputResult, |
| 12 | + SubscriptionContext, |
| 13 | + SubscriptionResult, |
| 14 | + WebhookProviderHandler, |
| 15 | +} from '@/lib/webhooks/providers/types' |
| 16 | + |
| 17 | +const logger = createLogger('WebhookProvider:GitLab') |
| 18 | + |
| 19 | +const GITLAB_API_BASE = 'https://gitlab.com/api/v4' |
| 20 | + |
| 21 | +function asRecord(value: unknown): Record<string, unknown> { |
| 22 | + return (value as Record<string, unknown>) || {} |
| 23 | +} |
| 24 | + |
| 25 | +function gitlabProjectHooksUrl(projectId: string): string { |
| 26 | + return `${GITLAB_API_BASE}/projects/${encodeURIComponent(projectId)}/hooks` |
| 27 | +} |
| 28 | + |
| 29 | +/** |
| 30 | + * Best-effort cleanup that deletes any project hook pointing at `url`. Used to |
| 31 | + * avoid orphaning a hook when the create response can't be parsed for its id. |
| 32 | + */ |
| 33 | +async function cleanupGitLabHookByUrl( |
| 34 | + projectId: string, |
| 35 | + accessToken: string, |
| 36 | + url: string |
| 37 | +): Promise<void> { |
| 38 | + const res = await fetch(gitlabProjectHooksUrl(projectId), { |
| 39 | + headers: { 'PRIVATE-TOKEN': accessToken }, |
| 40 | + }).catch(() => null) |
| 41 | + if (!res || !res.ok) return |
| 42 | + |
| 43 | + const hooks = (await res.json().catch(() => null)) as Array<{ id?: number; url?: string }> | null |
| 44 | + if (!Array.isArray(hooks)) return |
| 45 | + |
| 46 | + await Promise.all( |
| 47 | + hooks |
| 48 | + .filter((hook) => hook.url === url && hook.id != null) |
| 49 | + .map((hook) => |
| 50 | + fetch(`${gitlabProjectHooksUrl(projectId)}/${hook.id}`, { |
| 51 | + method: 'DELETE', |
| 52 | + headers: { 'PRIVATE-TOKEN': accessToken }, |
| 53 | + }).catch(() => null) |
| 54 | + ) |
| 55 | + ) |
| 56 | +} |
| 57 | + |
| 58 | +export const gitlabHandler: WebhookProviderHandler = { |
| 59 | + /** |
| 60 | + * GitLab echoes the configured "Secret token" verbatim in the `X-Gitlab-Token` |
| 61 | + * header (plain equality, not an HMAC). The secret is generated during |
| 62 | + * auto-registration, so a missing secret means misconfiguration — fail closed. |
| 63 | + */ |
| 64 | + verifyAuth({ request, requestId, providerConfig }: AuthContext) { |
| 65 | + const secret = providerConfig.webhookSecret as string | undefined |
| 66 | + if (!secret) { |
| 67 | + logger.warn(`[${requestId}] GitLab webhook secret not configured`) |
| 68 | + return new NextResponse('Unauthorized - Missing GitLab webhook secret', { status: 401 }) |
| 69 | + } |
| 70 | + |
| 71 | + const token = request.headers.get('X-Gitlab-Token') |
| 72 | + if (!token) { |
| 73 | + logger.warn(`[${requestId}] GitLab webhook missing X-Gitlab-Token header`) |
| 74 | + return new NextResponse('Unauthorized - Missing GitLab token', { status: 401 }) |
| 75 | + } |
| 76 | + |
| 77 | + if (!safeCompare(token, secret)) { |
| 78 | + logger.warn(`[${requestId}] GitLab token verification failed`) |
| 79 | + return new NextResponse('Unauthorized - Invalid GitLab token', { status: 401 }) |
| 80 | + } |
| 81 | + |
| 82 | + return null |
| 83 | + }, |
| 84 | + |
| 85 | + async matchEvent({ body, requestId, providerConfig }: EventMatchContext) { |
| 86 | + const triggerId = providerConfig.triggerId as string | undefined |
| 87 | + if (!triggerId || triggerId === 'gitlab_webhook') return true |
| 88 | + |
| 89 | + const objectKind = asRecord(body).object_kind as string | undefined |
| 90 | + |
| 91 | + const { isGitLabEventMatch } = await import('@/triggers/gitlab/utils') |
| 92 | + if (!isGitLabEventMatch(triggerId, objectKind || '')) { |
| 93 | + logger.debug( |
| 94 | + `[${requestId}] GitLab event '${objectKind}' does not match trigger ${triggerId}, skipping` |
| 95 | + ) |
| 96 | + return false |
| 97 | + } |
| 98 | + return true |
| 99 | + }, |
| 100 | + |
| 101 | + async formatInput({ body, headers }: FormatInputContext): Promise<FormatInputResult> { |
| 102 | + const b = asRecord(body) |
| 103 | + const eventType = headers['x-gitlab-event'] || '' |
| 104 | + const ref = (b.ref as string) || '' |
| 105 | + const branch = ref.replace('refs/heads/', '') |
| 106 | + return { |
| 107 | + input: { ...b, event_type: eventType, branch }, |
| 108 | + } |
| 109 | + }, |
| 110 | + |
| 111 | + async createSubscription(ctx: SubscriptionContext): Promise<SubscriptionResult | undefined> { |
| 112 | + const config = getProviderConfig(ctx.webhook) |
| 113 | + const accessToken = config.accessToken as string | undefined |
| 114 | + const projectId = config.projectId as string | undefined |
| 115 | + const triggerId = config.triggerId as string | undefined |
| 116 | + |
| 117 | + if (!accessToken) |
| 118 | + throw new Error('GitLab Personal Access Token is required to create the webhook.') |
| 119 | + if (!projectId) throw new Error('GitLab Project ID is required to create the webhook.') |
| 120 | + |
| 121 | + const { getGitLabEventFlags } = await import('@/triggers/gitlab/utils') |
| 122 | + const secretToken = generateId() |
| 123 | + const res = await fetch(gitlabProjectHooksUrl(projectId), { |
| 124 | + method: 'POST', |
| 125 | + headers: { 'PRIVATE-TOKEN': accessToken, 'Content-Type': 'application/json' }, |
| 126 | + body: JSON.stringify({ |
| 127 | + url: getNotificationUrl(ctx.webhook), |
| 128 | + token: secretToken, |
| 129 | + enable_ssl_verification: true, |
| 130 | + ...getGitLabEventFlags(triggerId ?? 'gitlab_webhook'), |
| 131 | + }), |
| 132 | + }) |
| 133 | + |
| 134 | + if (!res.ok) { |
| 135 | + const detail = await res.text().catch(() => '') |
| 136 | + logger.error(`[${ctx.requestId}] Failed to create GitLab webhook (${res.status})`, { detail }) |
| 137 | + if (res.status === 401) |
| 138 | + throw new Error( |
| 139 | + 'GitLab authentication failed. Verify your Personal Access Token has the api scope.' |
| 140 | + ) |
| 141 | + if (res.status === 403) |
| 142 | + throw new Error( |
| 143 | + 'GitLab access denied. You need the Maintainer or Owner role on the project.' |
| 144 | + ) |
| 145 | + if (res.status === 404) throw new Error('GitLab project not found. Verify the Project ID.') |
| 146 | + throw new Error(`Failed to create GitLab webhook: ${res.status}`) |
| 147 | + } |
| 148 | + |
| 149 | + const created = (await res.json().catch(() => ({}))) as { id?: number | string } |
| 150 | + if (created.id === undefined || created.id === null) { |
| 151 | + // The hook was created but we can't read its id — delete it by URL so it |
| 152 | + // is not orphaned in GitLab. |
| 153 | + await cleanupGitLabHookByUrl(projectId, accessToken, getNotificationUrl(ctx.webhook)) |
| 154 | + throw new Error('GitLab webhook created but no hook ID was returned.') |
| 155 | + } |
| 156 | + |
| 157 | + logger.info(`[${ctx.requestId}] Created GitLab webhook ${created.id} for project ${projectId}`) |
| 158 | + return { providerConfigUpdates: { externalId: String(created.id), webhookSecret: secretToken } } |
| 159 | + }, |
| 160 | + |
| 161 | + async deleteSubscription(ctx: DeleteSubscriptionContext): Promise<void> { |
| 162 | + const config = getProviderConfig(ctx.webhook) |
| 163 | + const accessToken = config.accessToken as string | undefined |
| 164 | + const projectId = config.projectId as string | undefined |
| 165 | + const externalId = config.externalId as string | undefined |
| 166 | + |
| 167 | + if (!accessToken || !projectId || !externalId) { |
| 168 | + if (ctx.strict) throw new Error('Missing GitLab credentials or hook ID for webhook deletion.') |
| 169 | + logger.warn( |
| 170 | + `[${ctx.requestId}] Skipping GitLab webhook cleanup — missing token, project, or hook ID` |
| 171 | + ) |
| 172 | + return |
| 173 | + } |
| 174 | + |
| 175 | + const res = await fetch(`${gitlabProjectHooksUrl(projectId)}/${externalId}`, { |
| 176 | + method: 'DELETE', |
| 177 | + headers: { 'PRIVATE-TOKEN': accessToken }, |
| 178 | + }) |
| 179 | + |
| 180 | + if (!res.ok && res.status !== 404) { |
| 181 | + if (ctx.strict) throw new Error(`Failed to delete GitLab webhook: ${res.status}`) |
| 182 | + logger.warn( |
| 183 | + `[${ctx.requestId}] Failed to delete GitLab webhook ${externalId} (non-fatal): ${res.status}` |
| 184 | + ) |
| 185 | + return |
| 186 | + } |
| 187 | + logger.info(`[${ctx.requestId}] Deleted GitLab webhook ${externalId}`) |
| 188 | + }, |
| 189 | +} |
0 commit comments