From 85deb8934b609eba450d6ab48c42160cbc4ab2b6 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 22:11:24 -0400 Subject: [PATCH] Fix GitLab webhook integration updates (#13764) * fix GitLab webhook integration updates * support shared GitLab webhook credentials --- .../github/server/tasks/GitHubWebhookTask.ts | 1 + plugins/gitlab/server/GitLabIssueProvider.ts | 48 +++++++++++++---- plugins/gitlab/server/api/gitlab.ts | 51 ++++++++++++++----- .../gitlab/server/tasks/GitLabWebhookTask.ts | 4 +- server/types.ts | 2 + server/utils/BaseIssueProvider.ts | 3 ++ 6 files changed, 84 insertions(+), 25 deletions(-) diff --git a/plugins/github/server/tasks/GitHubWebhookTask.ts b/plugins/github/server/tasks/GitHubWebhookTask.ts index 912413abae..d2bfc77fd5 100644 --- a/plugins/github/server/tasks/GitHubWebhookTask.ts +++ b/plugins/github/server/tasks/GitHubWebhookTask.ts @@ -21,6 +21,7 @@ export default class GitHubWebhookTask extends BaseTask { await plugin.value.handleWebhook({ headers, payload, + teamId: null, }); } } diff --git a/plugins/gitlab/server/GitLabIssueProvider.ts b/plugins/gitlab/server/GitLabIssueProvider.ts index a297947ed1..f5225eb626 100644 --- a/plugins/gitlab/server/GitLabIssueProvider.ts +++ b/plugins/gitlab/server/GitLabIssueProvider.ts @@ -79,9 +79,11 @@ export class GitLabIssueProvider extends BaseIssueProvider { async handleWebhook({ payload, headers, + teamId, }: { payload: Record; headers: Record; + teamId: string | null | undefined; }) { const hookId = headers["x-gitlab-webhook-uuid"] as string; const typedPayload = payload as GitLabWebhookPayload; @@ -94,35 +96,44 @@ export class GitLabIssueProvider extends BaseIssueProvider { return; } + if (teamId === undefined) { + Logger.warn(`Received GitLab webhook without authorization scope`); + return; + } + switch (eventName) { case "project_update": case "project_transfer": case "project_rename": - await this.updateProject(typedPayload); + await this.updateProject(typedPayload, teamId); break; case "repository_update": - await this.createProject(typedPayload); + await this.createProject(typedPayload, teamId); break; case "project_destroy": - await this.destroyProject(typedPayload); + await this.destroyProject(typedPayload, teamId); break; case "group_rename": case "user_rename": - await this.updateNamespace(typedPayload); + await this.updateNamespace(typedPayload, teamId); break; case "user_destroy": case "group_destroy": - await this.destroyNamespace(typedPayload); + await this.destroyNamespace(typedPayload, teamId); break; default: break; } } - private async updateNamespace(payload: GitLabWebhookPayload) { + private async updateNamespace( + payload: GitLabWebhookPayload, + teamId: string | null + ) { const name = payload.old_full_path ?? payload.old_username; const where = { service: IntegrationService.GitLab, + ...(teamId ? { teamId } : {}), [Op.and]: sequelize.literal(`"issueSources"::jsonb @> :jsonCondition`), }; const jsonCondition = JSON.stringify([{ owner: { name } }]); @@ -166,7 +177,10 @@ export class GitLabIssueProvider extends BaseIssueProvider { }); } - private async destroyNamespace(payload: GitLabWebhookPayload) { + private async destroyNamespace( + payload: GitLabWebhookPayload, + teamId: string | null + ) { if (!payload.user_id && !payload.full_path) { Logger.warn( `GitLab namespace_destroy event without user_id or full_path` @@ -177,6 +191,7 @@ export class GitLabIssueProvider extends BaseIssueProvider { let replacements = {}; const whereCondition: WhereOptions = { service: IntegrationService.GitLab, + ...(teamId ? { teamId } : {}), ...(payload.user_id && { "settings.gitlab.installation.account.id": payload.user_id, }), @@ -224,11 +239,15 @@ export class GitLabIssueProvider extends BaseIssueProvider { }); } - private async destroyProject(payload: GitLabWebhookPayload) { + private async destroyProject( + payload: GitLabWebhookPayload, + teamId: string | null + ) { await sequelize.transaction(async (transaction) => { const integrations = await Integration.findAll({ where: { service: IntegrationService.GitLab, + ...(teamId ? { teamId } : {}), [Op.and]: sequelize.where( sequelize.literal(`"issueSources"::jsonb @> :projectJson`), Op.eq, @@ -260,7 +279,10 @@ export class GitLabIssueProvider extends BaseIssueProvider { }); } - private async createProject(payload: GitLabWebhookPayload) { + private async createProject( + payload: GitLabWebhookPayload, + teamId: string | null + ) { const createEvent = payload.changes?.some((p: { before: string }) => /^0{40}$/.test(p.before) ); @@ -278,9 +300,11 @@ export class GitLabIssueProvider extends BaseIssueProvider { const integration = (await Integration.findOne({ where: { service: IntegrationService.GitLab, + ...(teamId ? { teamId } : {}), "settings.gitlab.installation.account.id": payload.user_id, }, lock: transaction.LOCK.UPDATE, + transaction, })) as Integration; if (!integration) { @@ -306,7 +330,10 @@ export class GitLabIssueProvider extends BaseIssueProvider { }); } - private async updateProject(payload: GitLabWebhookPayload) { + private async updateProject( + payload: GitLabWebhookPayload, + teamId: string | null + ) { if (!payload.name || !payload.path_with_namespace) { return; } @@ -317,6 +344,7 @@ export class GitLabIssueProvider extends BaseIssueProvider { const integrations = await Integration.findAll({ where: { service: IntegrationService.GitLab, + ...(teamId ? { teamId } : {}), [Op.and]: sequelize.where( sequelize.literal(`"issueSources"::jsonb @> :projectJson`), Op.eq, diff --git a/plugins/gitlab/server/api/gitlab.ts b/plugins/gitlab/server/api/gitlab.ts index fb50b85b17..051ffe9f97 100644 --- a/plugins/gitlab/server/api/gitlab.ts +++ b/plugins/gitlab/server/api/gitlab.ts @@ -12,6 +12,7 @@ import validateWebhook from "@server/middlewares/validateWebhook"; import { IntegrationAuthentication, Integration } from "@server/models"; import { authorize } from "@server/policies"; import type { APIContext } from "@server/types"; +import { safeEqual } from "@server/utils/crypto"; import { generateOAuthStateNonce, verifyOAuthStateNonce, @@ -27,6 +28,11 @@ import * as T from "./schema"; const router = new Router(); +function getGitLabWebhookToken(ctx: APIContext): string | undefined { + const signatureHeader = ctx.request.headers["x-gitlab-token"]; + return Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader; +} + router.post( "gitlab.connect", auth(), @@ -307,7 +313,7 @@ router.post( // Self-hosted instances store their client secret in the database, // use the X-Gitlab-Instance header to find the matching integration. if (instanceUrl && instanceUrl !== "https://gitlab.com") { - const integration = await Integration.findOne({ + const integrations = await Integration.findAll({ where: { service: IntegrationService.GitLab, settings: { gitlab: { url: instanceUrl } }, @@ -320,29 +326,46 @@ router.post( }, ], }); - if (integration) { - return integration.authentication.clientSecret ?? undefined; + const token = getGitLabWebhookToken(ctx); + const teamIds = new Set(); + let clientSecret: string | undefined; + + for (const integration of integrations) { + const candidateSecret = integration.authentication.clientSecret; + + if (!candidateSecret || !safeEqual(candidateSecret, token)) { + continue; + } + + clientSecret = candidateSecret; + teamIds.add(integration.teamId); } + + if (clientSecret) { + ctx.state.webhookTeamIds = [...teamIds]; + } + + return clientSecret; } // Default GitLab.com instance uses the env secret return env.GITLAB_CLIENT_SECRET; }, - getSignatureFromHeader: (ctx) => { - const { headers } = ctx.request; - const signatureHeader = headers["x-gitlab-token"]; - return Array.isArray(signatureHeader) - ? signatureHeader[0] - : signatureHeader; - }, + getSignatureFromHeader: getGitLabWebhookToken, }), async (ctx: APIContext) => { const { headers, body } = ctx.request; + const teamIds: Array = ctx.state.webhookTeamIds ?? [null]; - await new GitLabWebhookTask().schedule({ - payload: body, - headers, - }); + await Promise.all( + teamIds.map((teamId) => + new GitLabWebhookTask().schedule({ + payload: body, + headers, + teamId, + }) + ) + ); ctx.status = 202; } diff --git a/plugins/gitlab/server/tasks/GitLabWebhookTask.ts b/plugins/gitlab/server/tasks/GitLabWebhookTask.ts index 1b54eca230..f90e257f83 100644 --- a/plugins/gitlab/server/tasks/GitLabWebhookTask.ts +++ b/plugins/gitlab/server/tasks/GitLabWebhookTask.ts @@ -5,10 +5,11 @@ import { Hook, PluginManager } from "@server/utils/PluginManager"; type Props = { headers: Record; payload: Record; + teamId: string | null; }; export default class GitLabWebhookTask extends BaseTask { - public async perform({ headers, payload }: Props): Promise { + public async perform({ headers, payload, teamId }: Props): Promise { const plugins = PluginManager.getHooks(Hook.IssueProvider); const plugin = plugins.find( (p) => p.value.service === IntegrationService.GitLab @@ -21,6 +22,7 @@ export default class GitLabWebhookTask extends BaseTask { await plugin.value.handleWebhook({ headers, payload, + teamId, }); } } diff --git a/server/types.ts b/server/types.ts index adad7772a5..43a9d4b141 100644 --- a/server/types.ts +++ b/server/types.ts @@ -74,6 +74,8 @@ export type AppState = { auth: Authentication | Record; transaction: Transaction; pagination: Pagination; + /** The teams authorized to receive an inbound webhook. */ + webhookTeamIds?: string[]; oauthClient?: OAuthClient; oauthIntent?: OAuthIntent; oauthState?: OAuthState; diff --git a/server/utils/BaseIssueProvider.ts b/server/utils/BaseIssueProvider.ts index 273c9b0cfd..49bdc7aaf2 100644 --- a/server/utils/BaseIssueProvider.ts +++ b/server/utils/BaseIssueProvider.ts @@ -19,8 +19,11 @@ export abstract class BaseIssueProvider { abstract handleWebhook({ payload, headers, + teamId, }: { payload: Record; headers: Record; + /** The authorized team, or null for a provider-wide webhook secret. */ + teamId: string | null; }): Promise; }