Supporting "push to deploy" across multiple Git hosts sounds like a weekend feature: expose POST /api/webhooks/:id, check a signature header, parse the JSON body, and kick off a build.

Then the edge cases start piling up:

  • Gitea and Forgejo send X-GitHub-Event headers alongside their own headers—so checking GitHub first breaks signature verification for Gitea.
  • GitLab does not sign payloads with HMAC at all; it sends the raw shared secret in X-Gitlab-Token, where a naive === or length check leaks secret bytes and length via timing.
  • Returning 401 immediately when a webhook ID does not exist lets an attacker enumerate valid hook URLs by response latency.
  • Provider retries or captured payloads can trigger duplicate builds unless delivery IDs and timestamps are checked properly.

This is the design behind Git push webhook verification in Nitrobase (services/git/webhooks.ts and features/git/webhook.server.ts).

Nitrobase has only recently launched and is still in Beta. Its webhook pipeline does not replace a full WAF or API gateway, and it intentionally stays lightweight for a self-hosted control plane. Its goal is narrower: verify push events from GitHub, GitLab, Gitea, Forgejo, and custom CI scripts cleanly without timing leaks, replay bugs, or build storms.

1. Provider matching order matters (Gitea sends X-GitHub-* headers)

Each Git host signs and formats push webhooks slightly differently:

Provider Detection header Auth mechanism Replay ID header
Gitea / Forgejo X-Gitea-Event or X-Forgejo-Event Raw hex HMAC-SHA256 of body (X-Forgejo-Signature / X-Gitea-Signature) X-Forgejo-Delivery / X-Gitea-Delivery
GitLab X-Gitlab-Event Raw shared secret (X-Gitlab-Token) X-Gitlab-Event-UUID / Idempotency-Key
GitHub X-GitHub-Event (and not Gitea/Forgejo) sha256=<hex> HMAC-SHA256 of body (X-Hub-Signature-256) X-GitHub-Delivery
Generic HMAC (CI/scripts) X-Nitrobase-Signature sha256=<hex> = HMAC-SHA256(secret, "<timestamp>.<body>") + timestamp window X-Nitrobase-Delivery

Because Gitea and Forgejo include X-GitHub-Event for backwards compatibility, Nitrobase evaluates providers in strict specificity order ([gitea, gitlab, github, generic]) and explicitly excludes Gitea/Forgejo headers inside github.matches. Without that ordering, a valid Forgejo webhook gets routed to the GitHub verifier and rejected because its signature lacks the sha256= prefix.

2. Constant-time comparison without length leaks

Node's crypto.timingSafeEqual(a, b) throws a RangeError if the two buffers have different lengths. A common workaround is:

if (a.length !== b.length) return false; // Leaks expected secret length! return timingSafeEqual(Buffer.from(a), Buffer.from(b)); 

For GitLab's X-Gitlab-Token (where the header is the shared secret) or malformed signature headers, returning early on length mismatch leaks length information.

Nitrobase's safeEqual(a, b) hashes both strings into fixed 32-byte SHA-256 digests before comparing:

export function safeEqual(a: string, b: string): boolean { const left = createHash("sha256").update(a, "utf8").digest(); const right = createHash("sha256").update(b, "utf8").digest(); return timingSafeEqual(left, right) && a.length === b.length; } 

Both inputs always run through a fixed-length digest comparison regardless of how short or long the attacker's header is.

3. Closing timing oracles on unknown webhook URLs

Even with constant-time signature checks, an endpoint can still leak which webhook IDs exist if invalid URLs bail out early:

POST /api/webhooks/<hookId> │ ├── Rate limit: per-IP bucket (only when IP known) + per-hook bucket ├── Body cap: readBody(request, WEBHOOK_MAX_BODY_BYTES) -> 413 if oversized │ ├── Unknown hookId OR unknown provider? │ ├─ Run dummy DB lookup (apps.id = NO_APP) │ ├─ Run dummy provider.verify() with randomBytes(32) secret │ └─ Return 401 │ └── Known hookId + bad signature? ├─ Fire rejected(...) log ASYNCHRONOUSLY (never await before response!) └─ Return identical 401 

Three small details keep that boundary tight:

  1. Opaque hook IDs: webhookId is a random 24-byte base64url token (32 chars), never derived from app.id, and secrets are 32 random bytes stored encrypted at rest.
  2. Equal work on misses: When a hookId is unknown or lacks a recognized provider header, Nitrobase still runs a database lookup and a real HMAC verification against a random 32-byte secret before returning 401.
  3. Async rejection logging: When a real hook fails signature verification, recording the rejection row runs fire-and-forget (void rejected(...)) so a valid hook with a bad signature responds just as fast as a nonexistent hook.

And notice the rate-limiter detail: Nitrobase tracks separate byIp and byHook buckets, and if proxy headers do not provide a client IP (ip === null), it applies only byHook—never lumping every sender into one shared "unknown" IP bucket that one noisy caller could exhaust for everyone.

4. Replay protection, timestamp skew, and build coalescing

Passing signature verification only proves the sender knew the secret at some point in time. Before queueing a Docker build, handleGitWebhook checks three more things:

  • Signed timestamp tolerance (Generic HMAC): The timestamp is concatenated directly into the signed buffer ("<timestamp>.<body>"), and skew (Math.abs(now / 1000 - timestamp) > toleranceSeconds) is checked after signature verification so unsigned requests cannot probe server time.
  • Two-layer delivery deduplication: Every verified delivery ID is checked against an in-memory cache (seenDelivery) and backed by a partial unique Postgres index on (app_id, provider, delivery_id) WHERE delivery_id IS NOT NULL. Replayed or retried deliveries return 202 { ok: true, status: "duplicate" } without triggering a second build.
  • Branch/delete filtering and coalescing: Non-push events, tag pushes (!ref.startsWith("refs/heads/")), branch deletions (deleted: true or 40-zero after SHA), and pushes to other branches are recorded as ignored. When multiple pushes arrive rapidly for the tracked branch, enqueueBuild coalesces them so superseded deliveries do not stack redundant builds.

What webhook verification still does not protect against

Signature and delivery-ID verification confirm that the Git host sent a specific push payload once. They do not verify GPG commit signatures, stop a compromised developer account from pushing malicious code to the tracked branch, or prevent a missing X-GitHub-Delivery header on custom scripts that omit X-Nitrobase-Delivery (though Generic HMAC still bounds replays via its signed timestamp window).

My checklist for Git push webhook endpoints

  • [ ] Read the raw body bytes (with a strict byte cap) and verify the HMAC against the raw buffer—never re-serialized JSON
  • [ ] Check Gitea/Forgejo headers before GitHub so compatibility headers do not misroute verification
  • [ ] Compare secrets and signatures in constant time via fixed-length SHA-256 digests so length never leaks
  • [ ] Do equivalent DB + HMAC work on unknown hook IDs and log rejections asynchronously to avoid timing oracles
  • [ ] Never fall back to a shared "unknown" IP rate-limit bucket when proxy IP headers are absent
  • [ ] Deduplicate provider delivery IDs in Postgres (partial unique index) and coalesce rapid pushes before building

Most webhook bugs are invisible on the happy path. Handling header quirks, constant-time comparisons, timing parity, and replay deduplication up front keeps push-to-deploy boring even when exposed to the public internet.

Nitrobase source code: https://github.com/AydenGroup/nitrobase