Verify Gitea webhooks

Gitea signs a delivery when the webhook has a secret, so you can confirm that it came from your Gitea instance and wasn't changed on the way. X-Gitea-Signature holds the lowercase hex HMAC-SHA256 of the JSON payload, keyed with that secret, and the JSON payload is the raw request body only for a POST with application/json. Gitea's docs give a PHP example rather than an SDK.

The facts

Signature header
X-Gitea-Signature

Also sent: X-Hub-Signature-256, X-Gogs-Signature.

Scheme
HMAC-SHA256
Signed material
{JSON payload}

The raw request body only for POST + application/json. A form delivery's body is payload=<url-encoded JSON> and a GET carries the payload in the query string, but both are still signed over the JSON, so neither signature matches the bytes received. Gitea's docs say "raw request body", which holds only for JSON POSTs.

Legacy signature
X-Hub-Signature

HMAC-SHA1 of the JSON payload with the same secret, sent for compatibility and prefixed sha1=.

What to build
Set the webhook to POST + application/json, then recompute the digest over the raw body and compare
Key
shared secret

Gitea webhook secret

The webhook's Secret, which you set when you create or edit the webhook. It's separate from the optional Authorization header. Keep it in an environment variable, not in source code.

  • Where: the Secret field on the webhook's settings page, at repository, organization, user or system scope.
  • Format: Gitea's docs set no format or prefix.
  • One per webhook: each webhook has its own Secret field, so with several webhooks you need the matching secret for each.
  • No secret: the signature headers still arrive, with empty digests, so reject an empty value.
  • Changing it: Gitea's docs describe no period when the old and new secrets both work.
  • Old examples: some still show a secret field in the JSON body. Current versions don't send it.

Source: Gitea docs ↗

Code

express/src/index.js
javascript
require('dotenv').config({ quiet: true });
const express = require('express');
const crypto = require('crypto');

const app = express();

/**
 * Verify Gitea webhook signature
 * @param {Buffer} rawBody - Raw request body
 * @param {string} signature - X-Gitea-Signature header (bare hex HMAC-SHA256)
 * @param {string} secret - Gitea webhook secret
 * @returns {boolean} - Whether signature is valid
 */
function verifyGiteaWebhook(rawBody, signature, secret) {
  // Gitea sends the header with an empty value when no secret is configured
  if (!signature || !secret) {
    return false;
  }

  const expected = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex');

  // Timing-safe comparison; throws on length mismatch
  try {
    return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
  } catch {
    return false;
  }
}

// Gitea webhook endpoint - configure the webhook as POST + application/json.
// Gitea signs the JSON payload, which is the raw body only for JSON deliveries;
// form-encoded deliveries (payload=<url-encoded JSON>) fail verification.
app.post('/webhooks/gitea',
  express.raw({ type: '*/*' }),
  (req, res) => {
    const signature = req.headers['x-gitea-signature'];
    const event = req.headers['x-gitea-event'];
    const deliveryId = req.headers['x-gitea-delivery'];

    if (!Buffer.isBuffer(req.body) || !verifyGiteaWebhook(req.body, signature, process.env.GITEA_WEBHOOK_SECRET)) {
      console.error('Webhook signature verification failed');
      return res.status(400).send('Invalid signature');
    }

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

    console.log(`Received ${event} event (delivery: ${deliveryId})`);

    switch (event) {
      case 'push':
        console.log(`Push to ${payload.ref}:`, payload.head_commit?.message);
        // Your code: Trigger CI/CD, run tests, deploy, etc.
        break;

      case 'pull_request':
        console.log(`PR #${payload.number} ${action}:`, payload.pull_request?.title);
        // Your code: Run checks, notify reviewers, etc.
        break;

      case 'issues':
        console.log(`Issue #${payload.issue?.number} ${action}:`, payload.issue?.title);
        // Your code: Triage, label, notify, etc.
        break;

      case 'issue_comment':
        console.log(`Comment on #${payload.issue?.number} by ${payload.comment?.user?.login}`);
        // Your code: Bot commands, notifications, etc.
        break;

      case 'create':
        console.log(`Created ${payload.ref_type}:`, payload.ref);
        // Your code: Environment setup, etc.
        break;

      case 'delete':
        console.log(`Deleted ${payload.ref_type}:`, payload.ref);
        // Your code: Cleanup, archive, etc.
        break;

      case 'release':
        console.log(`Release ${action}:`, payload.release?.tag_name);
        // Your code: Deploy, notify, update changelog, etc.
        break;

      default:
        console.log(`Unhandled event: ${event}`);
    }

    res.status(200).send('OK');
  }
);

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

// Export app for testing
module.exports = { app, verifyGiteaWebhook };

// Start server only when run directly (not when imported for testing)
if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/gitea`);
  });
}
nextjs/app/webhooks/gitea/route.ts
typescript
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

/**
 * Verify Gitea webhook signature (X-Gitea-Signature: bare hex HMAC-SHA256)
 */
function verifyGiteaWebhook(rawBody: string, signature: string | null, secret: string | undefined): boolean {
  // Gitea sends the header with an empty value when no secret is configured
  if (!signature || !secret) {
    return false;
  }

  const expected = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex');

  try {
    return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
  } catch {
    return false;
  }
}

export async function POST(request: NextRequest) {
  // Raw body. Gitea signs the JSON payload, which matches the body only for
  // POST + application/json; form-encoded deliveries fail verification.
  const body = await request.text();
  const signature = request.headers.get('x-gitea-signature');
  const event = request.headers.get('x-gitea-event');
  const deliveryId = request.headers.get('x-gitea-delivery');

  if (!verifyGiteaWebhook(body, signature, process.env.GITEA_WEBHOOK_SECRET)) {
    console.error('Webhook signature verification failed');
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  // Parse after verification
  let payload;
  try {
    payload = JSON.parse(body);
  } catch {
    return NextResponse.json({ error: 'Invalid payload' }, { status: 400 });
  }
  const action = payload.action;

  console.log(`Received ${event} event (delivery: ${deliveryId})`);

  switch (event) {
    case 'push':
      console.log(`Push to ${payload.ref}:`, payload.head_commit?.message);
      // Your code: Trigger CI/CD, run tests, deploy, etc.
      break;

    case 'pull_request':
      console.log(`PR #${payload.number} ${action}:`, payload.pull_request?.title);
      // Your code: Run checks, notify reviewers, etc.
      break;

    case 'issues':
      console.log(`Issue #${payload.issue?.number} ${action}:`, payload.issue?.title);
      // Your code: Triage, label, notify, etc.
      break;

    case 'issue_comment':
      console.log(`Comment on #${payload.issue?.number} by ${payload.comment?.user?.login}`);
      // Your code: Bot commands, notifications, etc.
      break;

    case 'create':
      console.log(`Created ${payload.ref_type}:`, payload.ref);
      // Your code: Environment setup, etc.
      break;

    case 'delete':
      console.log(`Deleted ${payload.ref_type}:`, payload.ref);
      // Your code: Cleanup, archive, etc.
      break;

    case 'release':
      console.log(`Release ${action}:`, payload.release?.tag_name);
      // Your code: Deploy, notify, update changelog, etc.
      break;

    default:
      console.log(`Unhandled event: ${event}`);
  }

  return NextResponse.json({ received: true });
}
fastapi/main.py
python
import os
import hmac
import hashlib
import json
from dotenv import load_dotenv
from fastapi import FastAPI, Request, HTTPException

load_dotenv()

app = FastAPI()


def verify_gitea_webhook(raw_body: bytes, signature: str | None, secret: str | None) -> bool:
    """Verify Gitea webhook signature (X-Gitea-Signature: bare hex HMAC-SHA256)."""
    # Gitea sends the header with an empty value when no secret is configured
    if not signature or not secret:
        return False

    expected = hmac.new(
        secret.encode("utf-8"),
        raw_body,
        hashlib.sha256
    ).hexdigest()

    # Use timing-safe comparison
    return hmac.compare_digest(signature.encode(), expected.encode())


@app.post("/webhooks/gitea")
async def gitea_webhook(request: Request):
    # Raw body for signature verification. Gitea signs the JSON payload, which
    # matches the body only for POST + application/json; form deliveries fail.
    raw_body = await request.body()
    signature = request.headers.get("x-gitea-signature")
    event = request.headers.get("x-gitea-event")
    delivery_id = request.headers.get("x-gitea-delivery")

    if not verify_gitea_webhook(raw_body, signature, os.environ.get("GITEA_WEBHOOK_SECRET")):
        raise HTTPException(status_code=400, detail="Invalid signature")

    try:
        payload = json.loads(raw_body)
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid payload")
    action = payload.get("action")

    print(f"Received {event} event (delivery: {delivery_id})")

    if event == "push":
        head_commit = payload.get("head_commit") or {}
        print(f"Push to {payload.get('ref')}: {head_commit.get('message')}")
        # Your code: Trigger CI/CD, run tests, deploy, etc.

    elif event == "pull_request":
        pr = payload.get("pull_request") or {}
        print(f"PR #{payload.get('number')} {action}: {pr.get('title')}")
        # Your code: Run checks, notify reviewers, etc.

    elif event == "issues":
        issue = payload.get("issue") or {}
        print(f"Issue #{issue.get('number')} {action}: {issue.get('title')}")
        # Your code: Triage, label, notify, etc.

    elif event == "issue_comment":
        issue = payload.get("issue") or {}
        comment = payload.get("comment") or {}
        print(f"Comment on #{issue.get('number')} by {(comment.get('user') or {}).get('login')}")
        # Your code: Bot commands, notifications, etc.

    elif event == "create":
        print(f"Created {payload.get('ref_type')}: {payload.get('ref')}")
        # Your code: Environment setup, etc.

    elif event == "delete":
        print(f"Deleted {payload.get('ref_type')}: {payload.get('ref')}")
        # Your code: Cleanup, archive, etc.

    elif event == "release":
        release = payload.get("release") or {}
        print(f"Release {action}: {release.get('tag_name')}")
        # Your code: Deploy, notify, update changelog, etc.

    else:
        print(f"Unhandled event: {event}")

    return {"received": True}


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


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

From hookdeck/webhook-skills ↗

Or install the Gitea webhooks skill:

npx skills add hookdeck/webhook-skills --skill gitea-webhooks

Common failures

Form or GET delivery

Gitea's docs say the raw request body is signed, but its sender signs the JSON payload for every delivery. A form body is payload=<url-encoded JSON> and a GET uses the query string, so a raw-body check fails. Set the webhook to POST and application/json.

No secret on the webhook

With no secret, Gitea still sends the signature headers, but with empty digests. Set a secret, and reject an empty value rather than treating it as a match.

Body changed before verification

Verify before JSON parsing or any other change to the body. Middleware that parses the request and serializes it again produces different bytes.

Wrong header format

X-Gitea-Signature is bare lowercase hex with no prefix. X-Hub-Signature-256 is the same digest with sha256=, and X-Hub-Signature uses SHA-1 with sha1=.

From Hookdeck's Gitea guide

Let Event Gateway verify Gitea signatures.

Event Gateway verifies the signature on each Gitea POST + application/json delivery before it reaches your service, then queues it and retries failures on your schedule.

Not affiliated with Gitea. Facts are compiled from public sources and linked inline.