# Verify GitLab webhooks

GitLab signs a delivery when the webhook has a signing token, so you can confirm that it came from GitLab and wasn't changed on the way. It follows the Standard Webhooks spec: `webhook-signature` holds `v1,` and a base64 HMAC-SHA256 over the message ID, the timestamp and the raw body. The older secret token isn't a signature: GitLab sends it as plain text in `X-Gitlab-Token` and doesn't recommend it for new webhooks. Both are optional, so a webhook with neither has nothing to verify, and self-managed instances before GitLab 19.0 only have the secret token.

Agent skill: `npx skills add hookdeck/webhook-skills --skill gitlab-webhooks` ([details](https://hookdeck.com/webhooks/gitlab/skill))

> Independent reference generated from hookdeck/webhook-registry (commit a24c8d9, 19 Nov 2026). [GitLab's official docs](https://docs.gitlab.com/user/project/integrations/webhooks/).

[Overview](https://hookdeck.com/webhooks/gitlab) · [Webhook events (27)](https://hookdeck.com/webhooks/gitlab/events) · [MCP events](https://hookdeck.com/webhooks/gitlab/mcp-events) · [Verify signatures](https://hookdeck.com/webhooks/gitlab/verify) · [Production guide](https://hookdeck.com/webhooks/gitlab/guide-auto-disabling-duplicates-retries-timeouts) · [Agent skill](https://hookdeck.com/webhooks/gitlab/skill)

## The facts

| Fact | Value | Source |
|---|---|---|
| Signature header | `webhook-signature` Also sent: webhook-id, webhook-timestamp. | [GitLab docs](https://docs.gitlab.com/user/project/integrations/webhooks/#signing-tokens) |
| Scheme | `HMAC-SHA256` | [GitLab docs](https://docs.gitlab.com/user/project/integrations/webhooks/#signing-tokens) |
| Signed material | `{webhook-id}.{webhook-timestamp}.{raw body}` The webhook-id header, a literal dot, the webhook-timestamp header, a literal dot, then the raw JSON body as sent. GitLab's docs write this as {message_id}.{timestamp}.{body}. | [GitLab docs](https://docs.gitlab.com/user/project/integrations/webhooks/#signing-tokens) |
| Send timestamp | `webhook-timestamp` | [GitLab docs](https://docs.gitlab.com/user/project/integrations/webhooks/#signing-tokens) |
| Legacy signature | `X-Gitlab-Token` A secret token sent as plain text when one is configured, not a signature, so it doesn't protect the body. | [GitLab docs](https://docs.gitlab.com/user/project/integrations/webhooks/#delivery-headers) |
| What to build | `Recompute a digest over the timestamp and raw body, and compare` | [GitLab docs](https://docs.gitlab.com/user/project/integrations/webhooks/#signing-tokens) |
| Key | `shared secret` | [GitLab docs](https://docs.gitlab.com/user/project/integrations/webhooks/#signing-tokens) |

## GitLab webhook secret

GitLab generates the signing token for you when you set up the webhook, and shows it once. It's separate from the older secret token, which you type yourself. Keep it in an environment variable, not in source code.

- Where to find it: under Settings > Webhooks in a project or group, select Generate signing token on the webhook. Copy it straight away.
- Format: `whsec_` followed by base64, encoding a 32-byte key. Strip `whsec_` and base64-decode the rest to get the HMAC key.
- One per webhook: each webhook has its own token, so with several webhooks you need the matching token for each.
- Lost or replaced: GitLab shows the token once and its API never returns it. The API's update endpoint accepts a new one as `signing_token`. GitLab's docs describe no period when an old and a new token both work.
- Migrating from a secret token: set both tokens on the webhook, verify `webhook-signature` when it's present and fall back to `X-Gitlab-Token` otherwise, then remove the secret token.
- Versions: signing tokens arrived in GitLab 19.0 and became generally available in 19.1. Self-managed instances on earlier versions only have the secret token.

Source: [GitLab docs](https://docs.gitlab.com/user/project/integrations/webhooks/#create-a-webhook)

## Code

### Express

From [webhook-skills: skills/gitlab-webhooks/examples/express/src/index.js](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/gitlab-webhooks/examples/express/src/index.js)

```javascript
// Generated with: gitlab-webhooks skill
// https://github.com/hookdeck/webhook-skills

const express = require('express');
const crypto = require('crypto');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

// GitLab (19.0+) offers two ways to authenticate a webhook, and both can be
// configured on the same webhook:
// - Signing token (recommended): Standard Webhooks HMAC-SHA256 signature in
//   the webhook-signature header.
// - Secret token (legacy, "not recommended" by GitLab): the plain-text token
//   sent back in the X-Gitlab-Token header.
// https://docs.gitlab.com/user/project/integrations/webhooks/#signing-tokens

// GitLab says to check that webhook-timestamp is "recent" but gives no window.
// The Standard Webhooks spec asks for "some allowable tolerance"; 5 minutes is
// the default in the Standard Webhooks reference libraries.
const TIMESTAMP_TOLERANCE_SECONDS = 5 * 60;

// Signed content is "{webhook-id}.{webhook-timestamp}.{raw body}". The key is
// the signing token with the whsec_ prefix stripped, then base64-decoded.
function computeGitLabSignature(signingToken, webhookId, webhookTimestamp, rawBody) {
  const key = Buffer.from(signingToken.replace(/^whsec_/, ''), 'base64');
  const digest = crypto
    .createHmac('sha256', key)
    .update(`${webhookId}.${webhookTimestamp}.`)
    .update(rawBody)
    .digest('base64');
  return `v1,${digest}`;
}

function verifyGitLabSignature(rawBody, headers, signingToken) {
  const webhookId = headers['webhook-id'];
  const webhookTimestamp = headers['webhook-timestamp'];
  const signatureHeader = headers['webhook-signature'];
  if (!signingToken || !webhookId || !webhookTimestamp || !signatureHeader) {
    return false;
  }

  // Reject stale or future timestamps to limit replay
  const timestamp = Number(webhookTimestamp);
  const now = Math.floor(Date.now() / 1000);
  if (!Number.isInteger(timestamp) || Math.abs(now - timestamp) > TIMESTAMP_TOLERANCE_SECONDS) {
    return false;
  }

  const expected = Buffer.from(
    computeGitLabSignature(signingToken, webhookId, webhookTimestamp, rawBody)
  );
  // The header is a space-separated list of "v1,<base64>" signatures
  return signatureHeader.split(' ').some((signature) => {
    const received = Buffer.from(signature);
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}

// Legacy secret token: compare X-Gitlab-Token with the configured token
function verifyGitLabToken(tokenHeader, secret) {
  if (!tokenHeader || !secret) {
    return false;
  }

  // Use timing-safe comparison to prevent timing attacks
  try {
    return crypto.timingSafeEqual(
      Buffer.from(tokenHeader),
      Buffer.from(secret)
    );
  } catch (error) {
    // Buffers must be same length for timingSafeEqual
    // Different lengths = not equal
    return false;
  }
}

// GitLab's migration advice: verify the signature when webhook-signature is
// present, and fall back to the secret token otherwise. A request that carries
// a signature must pass the signature check; it never falls back.
function verifyGitLabWebhook(rawBody, headers) {
  const signingToken = process.env.GITLAB_WEBHOOK_SIGNING_TOKEN;
  if (signingToken && headers['webhook-signature']) {
    return verifyGitLabSignature(rawBody, headers, signingToken);
  }
  return verifyGitLabToken(headers['x-gitlab-token'], process.env.GITLAB_WEBHOOK_TOKEN);
}

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// GitLab webhook endpoint
app.post('/webhooks/gitlab',
  // Raw body: the signature covers the exact bytes GitLab sent.
  express.raw({ type: 'application/json', limit: '25mb' }), // GitLab can send large payloads
  (req, res) => {
    const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);

    // Extract headers
    const event = req.headers['x-gitlab-event'];
    const instance = req.headers['x-gitlab-instance'];
    const webhookUUID = req.headers['x-gitlab-webhook-uuid'];
    const eventUUID = req.headers['x-gitlab-event-uuid'];

    // Verify signature (or legacy token) before parsing
    if (!verifyGitLabWebhook(rawBody, req.headers)) {
      console.error(`GitLab webhook verification failed from ${instance}`);
      return res.status(401).send('Unauthorized');
    }

    let payload;
    try {
      payload = JSON.parse(rawBody.toString('utf8'));
    } catch {
      return res.status(400).send('Invalid JSON');
    }

    console.log(`✓ Verified GitLab webhook from ${instance}`);
    console.log(`  Event: ${event} (UUID: ${eventUUID})`);
    console.log(`  Webhook UUID: ${webhookUUID}`);

    // Handle different event types based on object_kind
    const { object_kind, project, user_name, user_username } = payload;

    switch (object_kind) {
      case 'push': {
        const { ref, before, after, total_commits_count } = payload;
        const branch = ref?.replace('refs/heads/', '');
        console.log(`📤 Push to ${branch} by ${user_name}:`);
        console.log(`   ${total_commits_count || 0} commits (${before?.slice(0, 8) || 'unknown'}...${after?.slice(0, 8) || 'unknown'})`);
        break;
      }

      case 'tag_push': {
        const { ref, before, after } = payload;
        const tag = ref?.replace('refs/tags/', '');
        if (before === '0000000000000000000000000000000000000000') {
          console.log(`🏷️  New tag created: ${tag} by ${user_name}`);
        } else {
          console.log(`🏷️  Tag deleted: ${tag} by ${user_name}`);
        }
        break;
      }

      case 'merge_request': {
        const { object_attributes } = payload;
        const { iid, title, state, action, source_branch, target_branch } = object_attributes || {};
        console.log(`🔀 Merge Request !${iid} ${action}: ${title}`);
        console.log(`   ${source_branch} → ${target_branch} (${state})`);
        break;
      }

      case 'issue':
      case 'work_item': {
        const { object_attributes } = payload;
        const { iid, title, state, action } = object_attributes || {};
        console.log(`📋 Issue #${iid} ${action}: ${title}`);
        console.log(`   State: ${state}`);
        break;
      }

      case 'note': {
        const { object_attributes, merge_request, issue, commit } = payload;
        const { noteable_type, note } = object_attributes || {};
        if (merge_request) {
          console.log(`💬 Comment on MR !${merge_request.iid} by ${user_name}`);
        } else if (issue) {
          console.log(`💬 Comment on Issue #${issue.iid} by ${user_name}`);
        } else if (commit) {
          console.log(`💬 Comment on commit ${commit.id.slice(0, 8)} by ${user_name}`);
        }
        console.log(`   "${note?.slice(0, 50)}${note?.length > 50 ? '...' : ''}"`);
        break;
      }

      case 'pipeline': {
        const { object_attributes } = payload;
        const { id, ref, status, duration, created_at } = object_attributes || {};
        console.log(`🔄 Pipeline #${id} ${status} for ${ref}`);
        if (duration) {
          console.log(`   Duration: ${duration}s`);
        }
        break;
      }

      case 'build': { // Job events
        const { build_name, build_stage, build_status, build_duration } = payload;
        console.log(`🔨 Job "${build_name}" ${build_status} in stage ${build_stage}`);
        if (build_duration) {
          console.log(`   Duration: ${build_duration}s`);
        }
        break;
      }

      case 'wiki_page': {
        const { object_attributes } = payload;
        const { title, action, slug } = object_attributes || {};
        console.log(`📖 Wiki page ${action}: ${title}`);
        console.log(`   Slug: ${slug}`);
        break;
      }

      case 'deployment': {
        const { status, environment, deployable_url } = payload;
        console.log(`🚀 Deployment to ${environment}: ${status}`);
        if (deployable_url) {
          console.log(`   URL: ${deployable_url}`);
        }
        break;
      }

      case 'release': {
        const { action, name, tag, description } = payload;
        console.log(`📦 Release ${action}: ${name} (${tag})`);
        if (description) {
          console.log(`   ${description.slice(0, 100)}${description.length > 100 ? '...' : ''}`);
        }
        break;
      }

      default:
        console.log(`❓ Received ${object_kind || event} event`);
        console.log(`   Project: ${project?.name} (${project?.path_with_namespace})`);
    }

    // Always return success to GitLab
    res.json({
      received: true,
      event: object_kind || event,
      project: project?.path_with_namespace
    });
  }
);

// 404 handler
app.use((req, res) => {
  res.status(404).json({ error: 'Not found' });
});

// Error handler
app.use((err, req, res, next) => {
  console.error('Error:', err);
  res.status(500).json({ error: 'Internal server error' });
});

// Start server
const server = app.listen(PORT, () => {
  console.log(`GitLab webhook server listening on port ${PORT}`);
  console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/gitlab`);
  if (!process.env.GITLAB_WEBHOOK_SIGNING_TOKEN && !process.env.GITLAB_WEBHOOK_TOKEN) {
    console.warn('⚠️  Warning: set GITLAB_WEBHOOK_SIGNING_TOKEN (or legacy GITLAB_WEBHOOK_TOKEN)');
  }
});

// For testing
module.exports = {
  app,
  server,
  computeGitLabSignature,
  verifyGitLabSignature,
  verifyGitLabToken,
  verifyGitLabWebhook,
};
```

### Next.js

From [webhook-skills: skills/gitlab-webhooks/examples/nextjs/app/webhooks/gitlab/route.ts](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/gitlab-webhooks/examples/nextjs/app/webhooks/gitlab/route.ts)

```typescript
// Generated with: gitlab-webhooks skill
// https://github.com/hookdeck/webhook-skills

import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

// GitLab webhook event types
interface GitLabWebhookBase {
  object_kind: string;
  event_name?: string;
  user_id?: number;
  user_name?: string;
  user_username?: string;
  user_email?: string;
  user_avatar?: string;
  project_id?: number;
  project?: {
    id: number;
    name: string;
    description?: string;
    web_url: string;
    avatar_url?: string;
    git_ssh_url: string;
    git_http_url: string;
    namespace: string;
    path_with_namespace: string;
    default_branch: string;
  };
}

interface PushEvent extends GitLabWebhookBase {
  object_kind: 'push';
  before: string;
  after: string;
  ref: string;
  checkout_sha?: string;
  total_commits_count: number;
  commits?: Array<{
    id: string;
    message: string;
    timestamp: string;
    url: string;
    author: {
      name: string;
      email: string;
    };
  }>;
}

interface MergeRequestEvent extends GitLabWebhookBase {
  object_kind: 'merge_request';
  object_attributes: {
    id: number;
    iid: number;
    title: string;
    state: string;
    action: string;
    source_branch: string;
    target_branch: string;
    description?: string;
    url: string;
  };
}

interface IssueEvent extends GitLabWebhookBase {
  object_kind: 'issue' | 'work_item';
  object_attributes: {
    id: number;
    iid: number;
    title: string;
    state: string;
    action: string;
    description?: string;
    url: string;
  };
}

interface PipelineEvent extends GitLabWebhookBase {
  object_kind: 'pipeline';
  object_attributes: {
    id: number;
    ref: string;
    tag: boolean;
    sha: string;
    before_sha: string;
    status: string;
    detailed_status: string;
    duration?: number;
    created_at: string;
    finished_at?: string;
  };
}

// Type guard functions
function isPushEvent(payload: any): payload is PushEvent {
  return payload.object_kind === 'push';
}

function isMergeRequestEvent(payload: any): payload is MergeRequestEvent {
  return payload.object_kind === 'merge_request';
}

function isIssueEvent(payload: any): payload is IssueEvent {
  return payload.object_kind === 'issue' || payload.object_kind === 'work_item';
}

function isPipelineEvent(payload: any): payload is PipelineEvent {
  return payload.object_kind === 'pipeline';
}

// GitLab (19.0+) offers two ways to authenticate a webhook, and both can be
// configured on the same webhook:
// - Signing token (recommended): Standard Webhooks HMAC-SHA256 signature in
//   the webhook-signature header.
// - Secret token (legacy, "not recommended" by GitLab): the plain-text token
//   sent back in the X-Gitlab-Token header.
// https://docs.gitlab.com/user/project/integrations/webhooks/#signing-tokens

// GitLab says to check that webhook-timestamp is "recent" but gives no window.
// The Standard Webhooks spec asks for "some allowable tolerance"; 5 minutes is
// the default in the Standard Webhooks reference libraries.
const TIMESTAMP_TOLERANCE_SECONDS = 5 * 60;

// Signed content is "{webhook-id}.{webhook-timestamp}.{raw body}". The key is
// the signing token with the whsec_ prefix stripped, then base64-decoded.
function computeGitLabSignature(
  signingToken: string,
  webhookId: string,
  webhookTimestamp: string,
  rawBody: Buffer
): string {
  const key = Buffer.from(signingToken.replace(/^whsec_/, ''), 'base64');
  const digest = crypto
    .createHmac('sha256', key)
    .update(`${webhookId}.${webhookTimestamp}.`)
    .update(rawBody)
    .digest('base64');
  return `v1,${digest}`;
}

function verifyGitLabSignature(rawBody: Buffer, headers: Headers, signingToken: string): boolean {
  const webhookId = headers.get('webhook-id');
  const webhookTimestamp = headers.get('webhook-timestamp');
  const signatureHeader = headers.get('webhook-signature');
  if (!signingToken || !webhookId || !webhookTimestamp || !signatureHeader) {
    return false;
  }

  // Reject stale or future timestamps to limit replay
  const timestamp = Number(webhookTimestamp);
  const now = Math.floor(Date.now() / 1000);
  if (!Number.isInteger(timestamp) || Math.abs(now - timestamp) > TIMESTAMP_TOLERANCE_SECONDS) {
    return false;
  }

  const expected = Buffer.from(
    computeGitLabSignature(signingToken, webhookId, webhookTimestamp, rawBody)
  );
  // The header is a space-separated list of "v1,<base64>" signatures
  return signatureHeader.split(' ').some((signature) => {
    const received = Buffer.from(signature);
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}

// Legacy secret token: compare X-Gitlab-Token with the configured token
function verifyGitLabToken(tokenHeader: string | null, secret: string | undefined): boolean {
  if (!tokenHeader || !secret) {
    return false;
  }

  // Use timing-safe comparison to prevent timing attacks
  try {
    return crypto.timingSafeEqual(
      Buffer.from(tokenHeader),
      Buffer.from(secret)
    );
  } catch (error) {
    // Buffers must be same length for timingSafeEqual
    // Different lengths = not equal
    return false;
  }
}

// GitLab's migration advice: verify the signature when webhook-signature is
// present, and fall back to the secret token otherwise. A request that carries
// a signature must pass the signature check; it never falls back.
function verifyGitLabWebhook(rawBody: Buffer, headers: Headers): boolean {
  const signingToken = process.env.GITLAB_WEBHOOK_SIGNING_TOKEN;
  if (signingToken && headers.get('webhook-signature')) {
    return verifyGitLabSignature(rawBody, headers, signingToken);
  }
  return verifyGitLabToken(headers.get('x-gitlab-token'), process.env.GITLAB_WEBHOOK_TOKEN);
}

export async function POST(request: NextRequest) {
  // Raw body: the signature covers the exact bytes GitLab sent
  const rawBody = Buffer.from(await request.arrayBuffer());

  // Get headers directly from request
  const event = request.headers.get('x-gitlab-event');
  const instance = request.headers.get('x-gitlab-instance');
  const webhookUUID = request.headers.get('x-gitlab-webhook-uuid');
  const eventUUID = request.headers.get('x-gitlab-event-uuid');

  // Verify signature (or legacy token) before parsing
  if (!verifyGitLabWebhook(rawBody, request.headers)) {
    console.error(`GitLab webhook verification failed from ${instance}`);
    return new NextResponse('Unauthorized', { status: 401 });
  }

  console.log(`✓ Verified GitLab webhook from ${instance}`);
  console.log(`  Event: ${event} (UUID: ${eventUUID})`);
  console.log(`  Webhook UUID: ${webhookUUID}`);

  // Parse body
  let payload: GitLabWebhookBase;
  try {
    payload = JSON.parse(rawBody.toString('utf8'));
  } catch (error) {
    console.error('Failed to parse JSON:', error);
    return new NextResponse('Invalid JSON', { status: 400 });
  }

  const { project, user_name } = payload;

  // Handle different event types
  if (isPushEvent(payload)) {
    const { ref, before, after, total_commits_count } = payload;
    const branch = ref?.replace('refs/heads/', '');
    console.log(`📤 Push to ${branch} by ${user_name}:`);
    console.log(`   ${total_commits_count || 0} commits (${before?.slice(0, 8) || 'unknown'}...${after?.slice(0, 8) || 'unknown'})`);
  } else if (isMergeRequestEvent(payload)) {
    const { object_attributes } = payload;
    const { iid, title, state, action, source_branch, target_branch } = object_attributes;
    console.log(`🔀 Merge Request !${iid} ${action}: ${title}`);
    console.log(`   ${source_branch} → ${target_branch} (${state})`);
  } else if (isIssueEvent(payload)) {
    const { object_attributes } = payload;
    const { iid, title, state, action } = object_attributes;
    console.log(`📋 Issue #${iid} ${action}: ${title}`);
    console.log(`   State: ${state}`);
  } else if (isPipelineEvent(payload)) {
    const { object_attributes } = payload;
    const { id, ref, status, duration } = object_attributes;
    console.log(`🔄 Pipeline #${id} ${status} for ${ref}`);
    if (duration) {
      console.log(`   Duration: ${duration}s`);
    }
  } else {
    // Handle other event types
    switch (payload.object_kind) {
      case 'tag_push': {
        const pushPayload = payload as any;
        const tag = pushPayload.ref?.replace('refs/tags/', '');
        if (pushPayload.before === '0000000000000000000000000000000000000000') {
          console.log(`🏷️  New tag created: ${tag} by ${user_name}`);
        } else {
          console.log(`🏷️  Tag deleted: ${tag} by ${user_name}`);
        }
        break;
      }
      case 'note': {
        const notePayload = payload as any;
        const { object_attributes, merge_request, issue } = notePayload;
        if (merge_request) {
          console.log(`💬 Comment on MR !${merge_request.iid} by ${user_name}`);
        } else if (issue) {
          console.log(`💬 Comment on Issue #${issue.iid} by ${user_name}`);
        }
        console.log(`   "${object_attributes?.note?.slice(0, 50)}..."`);
        break;
      }
      case 'build': {
        const buildPayload = payload as any;
        const { build_name, build_stage, build_status, build_duration } = buildPayload;
        console.log(`🔨 Job "${build_name}" ${build_status} in stage ${build_stage}`);
        if (build_duration) {
          console.log(`   Duration: ${build_duration}s`);
        }
        break;
      }
      case 'wiki_page': {
        const wikiPayload = payload as any;
        const { title, action, slug } = wikiPayload.object_attributes || {};
        console.log(`📖 Wiki page ${action}: ${title}`);
        console.log(`   Slug: ${slug}`);
        break;
      }
      case 'deployment': {
        const deployPayload = payload as any;
        const { status, environment } = deployPayload;
        console.log(`🚀 Deployment to ${environment}: ${status}`);
        break;
      }
      case 'release': {
        const releasePayload = payload as any;
        const { action, name, tag } = releasePayload;
        console.log(`📦 Release ${action}: ${name} (${tag})`);
        break;
      }
      default:
        console.log(`❓ Received ${payload.object_kind || event} event`);
        console.log(`   Project: ${project?.name} (${project?.path_with_namespace})`);
    }
  }

  // Return success response
  return NextResponse.json({
    received: true,
    event: payload.object_kind || event,
    project: project?.path_with_namespace
  });
}

// Health check endpoint
export async function GET() {
  return NextResponse.json({ status: 'ok' });
}
```

### FastAPI

From [webhook-skills: skills/gitlab-webhooks/examples/fastapi/main.py](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/gitlab-webhooks/examples/fastapi/main.py)

```python
# Generated with: gitlab-webhooks skill
# https://github.com/hookdeck/webhook-skills

from fastapi import FastAPI, Request, Header, HTTPException
from fastapi.responses import JSONResponse
from typing import Optional, Dict, Any
import base64
import hashlib
import hmac
import secrets
import os
import time
import logging
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Create FastAPI app
app = FastAPI(title="GitLab Webhook Handler")

# GitLab (19.0+) offers two ways to authenticate a webhook, and both can be
# configured on the same webhook:
# - Signing token (recommended): Standard Webhooks HMAC-SHA256 signature in
#   the webhook-signature header.
# - Secret token (legacy, "not recommended" by GitLab): the plain-text token
#   sent back in the X-Gitlab-Token header.
# https://docs.gitlab.com/user/project/integrations/webhooks/#signing-tokens

# GitLab says to check that webhook-timestamp is "recent" but gives no window.
# The Standard Webhooks spec asks for "some allowable tolerance"; 5 minutes is
# the default in the Standard Webhooks reference libraries.
TIMESTAMP_TOLERANCE_SECONDS = 5 * 60


def compute_gitlab_signature(
    signing_token: str, webhook_id: str, webhook_timestamp: str, raw_body: bytes
) -> str:
    """Signed content is "{webhook-id}.{webhook-timestamp}.{raw body}". The key is
    the signing token with the whsec_ prefix stripped, then base64-decoded."""
    key = base64.b64decode(signing_token.removeprefix("whsec_"))
    message = f"{webhook_id}.{webhook_timestamp}.".encode("utf-8") + raw_body
    digest = hmac.new(key, message, hashlib.sha256).digest()
    return "v1," + base64.b64encode(digest).decode("utf-8")


def verify_gitlab_signature(raw_body: bytes, headers, signing_token: Optional[str]) -> bool:
    """Verify a GitLab signing-token (Standard Webhooks) signature."""
    webhook_id = headers.get("webhook-id")
    webhook_timestamp = headers.get("webhook-timestamp")
    signature_header = headers.get("webhook-signature")
    if not (signing_token and webhook_id and webhook_timestamp and signature_header):
        return False

    # Reject stale or future timestamps to limit replay
    try:
        timestamp = int(webhook_timestamp)
    except ValueError:
        return False
    if abs(int(time.time()) - timestamp) > TIMESTAMP_TOLERANCE_SECONDS:
        return False

    expected = compute_gitlab_signature(signing_token, webhook_id, webhook_timestamp, raw_body)
    # The header is a space-separated list of "v1,<base64>" signatures
    return any(hmac.compare_digest(expected, sig) for sig in signature_header.split(" "))


def verify_gitlab_token(token_header: Optional[str], secret: Optional[str]) -> bool:
    """Legacy secret token: compare X-Gitlab-Token using timing-safe comparison"""
    if not token_header or not secret:
        return False

    # Use timing-safe comparison to prevent timing attacks
    return secrets.compare_digest(token_header, secret)


def verify_gitlab_webhook(raw_body: bytes, headers) -> bool:
    """GitLab's migration advice: verify the signature when webhook-signature is
    present, and fall back to the secret token otherwise. A request that carries
    a signature must pass the signature check; it never falls back."""
    signing_token = os.getenv("GITLAB_WEBHOOK_SIGNING_TOKEN")
    if signing_token and headers.get("webhook-signature"):
        return verify_gitlab_signature(raw_body, headers, signing_token)
    return verify_gitlab_token(headers.get("x-gitlab-token"), os.getenv("GITLAB_WEBHOOK_TOKEN"))


# Health check endpoint
@app.get("/health")
async def health():
    return {"status": "ok"}


# GitLab webhook endpoint
@app.post("/webhooks/gitlab")
async def handle_gitlab_webhook(
    request: Request,
    x_gitlab_event: Optional[str] = Header(None),
    x_gitlab_instance: Optional[str] = Header(None),
    x_gitlab_webhook_uuid: Optional[str] = Header(None),
    x_gitlab_event_uuid: Optional[str] = Header(None),
):
    # Raw body: the signature covers the exact bytes GitLab sent
    raw_body = await request.body()

    # Verify signature (or legacy token) before parsing
    if not verify_gitlab_webhook(raw_body, request.headers):
        logger.error(f"GitLab webhook verification failed from {x_gitlab_instance}")
        raise HTTPException(status_code=401, detail="Unauthorized")

    logger.info(f"✓ Verified GitLab webhook from {x_gitlab_instance}")
    logger.info(f"  Event: {x_gitlab_event} (UUID: {x_gitlab_event_uuid})")
    logger.info(f"  Webhook UUID: {x_gitlab_webhook_uuid}")

    # Parse JSON body
    try:
        payload = await request.json()
    except Exception as e:
        logger.error(f"Failed to parse JSON: {e}")
        raise HTTPException(status_code=400, detail="Invalid JSON")

    # Extract common fields
    object_kind = payload.get("object_kind")
    project = payload.get("project", {})
    user_name = payload.get("user_name")

    # Handle different event types
    if object_kind == "push":
        ref = payload.get("ref", "")
        branch = ref.replace("refs/heads/", "")
        before = payload.get("before", "")[:8]
        after = payload.get("after", "")[:8]
        total_commits = payload.get("total_commits_count", 0)
        logger.info(f"📤 Push to {branch} by {user_name}:")
        logger.info(f"   {total_commits} commits ({before}...{after})")

    elif object_kind == "tag_push":
        ref = payload.get("ref", "")
        tag = ref.replace("refs/tags/", "")
        before = payload.get("before", "")
        if before == "0000000000000000000000000000000000000000":
            logger.info(f"🏷️  New tag created: {tag} by {user_name}")
        else:
            logger.info(f"🏷️  Tag deleted: {tag} by {user_name}")

    elif object_kind == "merge_request":
        attrs = payload.get("object_attributes", {})
        iid = attrs.get("iid")
        title = attrs.get("title")
        state = attrs.get("state")
        action = attrs.get("action")
        source_branch = attrs.get("source_branch")
        target_branch = attrs.get("target_branch")
        logger.info(f"🔀 Merge Request !{iid} {action}: {title}")
        logger.info(f"   {source_branch} → {target_branch} ({state})")

    elif object_kind in ["issue", "work_item"]:
        attrs = payload.get("object_attributes", {})
        iid = attrs.get("iid")
        title = attrs.get("title")
        state = attrs.get("state")
        action = attrs.get("action")
        logger.info(f"📋 Issue #{iid} {action}: {title}")
        logger.info(f"   State: {state}")

    elif object_kind == "note":
        attrs = payload.get("object_attributes", {})
        note = attrs.get("note", "")[:50]
        merge_request = payload.get("merge_request")
        issue = payload.get("issue")
        commit = payload.get("commit")

        if merge_request:
            logger.info(f"💬 Comment on MR !{merge_request.get('iid')} by {user_name}")
        elif issue:
            logger.info(f"💬 Comment on Issue #{issue.get('iid')} by {user_name}")
        elif commit:
            logger.info(f"💬 Comment on commit {commit.get('id', '')[:8]} by {user_name}")
        logger.info(f"   \"{note}{'...' if len(attrs.get('note', '')) > 50 else ''}\"")

    elif object_kind == "pipeline":
        attrs = payload.get("object_attributes", {})
        id = attrs.get("id")
        ref = attrs.get("ref")
        status = attrs.get("status")
        duration = attrs.get("duration")
        logger.info(f"🔄 Pipeline #{id} {status} for {ref}")
        if duration:
            logger.info(f"   Duration: {duration}s")

    elif object_kind == "build":  # Job events
        build_name = payload.get("build_name")
        build_stage = payload.get("build_stage")
        build_status = payload.get("build_status")
        build_duration = payload.get("build_duration")
        logger.info(f"🔨 Job \"{build_name}\" {build_status} in stage {build_stage}")
        if build_duration:
            logger.info(f"   Duration: {build_duration}s")

    elif object_kind == "wiki_page":
        attrs = payload.get("object_attributes", {})
        title = attrs.get("title")
        action = attrs.get("action")
        slug = attrs.get("slug")
        logger.info(f"📖 Wiki page {action}: {title}")
        logger.info(f"   Slug: {slug}")

    elif object_kind == "deployment":
        status = payload.get("status")
        environment = payload.get("environment")
        deployable_url = payload.get("deployable_url")
        logger.info(f"🚀 Deployment to {environment}: {status}")
        if deployable_url:
            logger.info(f"   URL: {deployable_url}")

    elif object_kind == "release":
        action = payload.get("action")
        name = payload.get("name")
        tag = payload.get("tag")
        description = payload.get("description", "")
        logger.info(f"📦 Release {action}: {name} ({tag})")
        if description:
            desc_preview = description[:100]
            logger.info(f"   {desc_preview}{'...' if len(description) > 100 else ''}")

    else:
        logger.info(f"❓ Received {object_kind or x_gitlab_event} event")
        logger.info(f"   Project: {project.get('name')} ({project.get('path_with_namespace')})")

    # Return success response
    return JSONResponse(content={
        "received": True,
        "event": object_kind or x_gitlab_event,
        "project": project.get("path_with_namespace")
    })


# Error handler
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        status_code=exc.status_code,
        content={"error": exc.detail}
    )


# Main entry point
if __name__ == "__main__":
    import uvicorn
    port = int(os.getenv("PORT", 3000))

    logger.info(f"GitLab webhook server starting on port {port}")
    logger.info(f"Webhook endpoint: POST http://localhost:{port}/webhooks/gitlab")

    if not os.getenv("GITLAB_WEBHOOK_SIGNING_TOKEN") and not os.getenv("GITLAB_WEBHOOK_TOKEN"):
        logger.warning("⚠️  Warning: set GITLAB_WEBHOOK_SIGNING_TOKEN (or legacy GITLAB_WEBHOOK_TOKEN)")

    uvicorn.run(app, host="0.0.0.0", port=port)
```

Or install the GitLab webhooks skill: `npx skills add hookdeck/webhook-skills --skill gitlab-webhooks`

## Common failures

- **No signing token on the webhook.** GitLab only sends webhook-signature if the webhook has a signing token. If the header is missing, generate one, or check the instance runs GitLab 19.0 or later. X-Gitlab-Token on its own is the secret token, and it has to be compared, not verified as a signature.
- **Signing token used as the key.** The key isn't the token string. Strip the whsec_ prefix and base64-decode the rest, then compute the HMAC with those bytes.
- **Body changed before verification.** The signature covers the raw JSON body. Body parsers and proxies that re-serialize it break the match, so verify the bytes as they arrived.
- **Header compared as one value.** webhook-signature is a space-separated list of signatures. GitLab sends one today and says this might change, so split on spaces and accept a match on any entry.

From [Hookdeck's GitLab guide](https://hookdeck.com/webhooks/gitlab/guide-auto-disabling-duplicates-retries-timeouts).

---

Not affiliated with GitLab. Facts are compiled from public sources and linked inline. [View as JSON](https://hookdeck.com/webhooks/gitlab.json) · [Report a correction](https://hookdeck.com/contact)
