Skip to content

MT-22022: Add webhook signature verification helper#130

Open
Rabsztok wants to merge 1 commit into
mainfrom
MT-22022-webhook-signature-verification
Open

MT-22022: Add webhook signature verification helper#130
Rabsztok wants to merge 1 commit into
mainfrom
MT-22022-webhook-signature-verification

Conversation

@Rabsztok
Copy link
Copy Markdown

@Rabsztok Rabsztok commented May 20, 2026

Motivation

Expose a helper so Node.js users don't have to re-implement Mailtrap's HMAC-SHA256 webhook signature check on every receiver.

Changes

  • verifyWebhookSignature(payload, signature, signingSecret) exported from the package root. HMAC-SHA256 over the raw body, constant-time compare via crypto.timingSafeEqual. Accepts payload as string | Buffer. Returns false (never throws) on empty / wrong-length / non-hex / wrong-type inputs.
  • src/__tests__/lib/webhooks/verify-signature.test.ts pins the cross-SDK fixture (payload + signing_secret + expected digest) shared verbatim across all six official Mailtrap SDKs to guarantee byte-for-byte parity.
  • examples/webhooks/verify-signature.ts — runnable usage snippet.
  • README — new "Verifying webhook signatures" subsection.

How to test

CI runs jest, eslint, and tsc. Manually:

yarn ts-node examples/webhooks/verify-signature.ts

The script should exit 0 with no output.

Companion PRs

Coordinated rollout across all six official SDKs (same algorithm, same shared fixture):

Summary by CodeRabbit

Release Notes

  • New Features

    • Added webhook signature verification functionality to validate and authenticate incoming Mailtrap webhooks using HMAC-SHA256 signing.
  • Documentation

    • Updated README with a new "Verifying webhook signatures" section, including usage examples and supported functionality reference.
  • Tests

    • Added comprehensive test suite covering signature validation scenarios, including edge cases and error handling.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 20, 2026

Warning

Rate limit exceeded

@Rabsztok has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 23 minutes and 3 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: bb020b01-f69f-4356-a6e6-67a17f68da2e

📥 Commits

Reviewing files that changed from the base of the PR and between 2bad438 and eaab34a.

📒 Files selected for processing (5)
  • README.md
  • examples/webhooks/verify-signature.ts
  • src/__tests__/lib/webhooks/verify-signature.test.ts
  • src/index.ts
  • src/lib/webhooks/verify-signature.ts
📝 Walkthrough

Walkthrough

This PR adds webhook signature verification to the Mailtrap SDK. A new verifyWebhookSignature function validates HMAC-SHA256 signatures using constant-time comparison, handles malformed inputs gracefully without throwing, and is exported as part of the public API. Tests, documentation, and examples are included.

Changes

Webhook Signature Verification Feature

Layer / File(s) Summary
Core webhook signature verification implementation
src/lib/webhooks/verify-signature.ts
verifyWebhookSignature function computes HMAC-SHA256 over the raw payload using the signing secret, decodes the provided signature from hex, and performs constant-time comparison via timingSafeEqual. Input validation rejects malformed types, lengths, and non-hex signatures; all errors return false instead of throwing.
Module export and public API
src/index.ts
verifyWebhookSignature is imported and re-exported from the main SDK entry point, making it publicly available alongside MailtrapClient and MailtrapTransport.
Comprehensive test coverage
src/__tests__/lib/webhooks/verify-signature.test.ts
Jest test suite uses a cross-SDK HMAC fixture and validates correct signature verification, rejection of wrong secrets and tampered payloads, non-throwing behavior on invalid signatures, empty inputs, and equivalence between string and Buffer payloads.
Documentation and usage examples
README.md, examples/webhooks/verify-signature.ts
README describes HMAC-SHA256 signing and the non-throwing false return behavior; example script demonstrates end-to-end verification with correct signature/secret and graceful failure on malformed inputs.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

feature request

Suggested reviewers

  • IgorDobryn
  • mklocek
  • VladimirTaytor

Poem

🐰 A signature arrives, wrapped in hex—
We hash and compare, no errors vex!
Constant-time guards from timing attacks,
Your webhooks now verified, no looking back! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding a webhook signature verification helper function to the package.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description is comprehensive and follows the template structure with clear Motivation, Changes, and How to test sections.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch MT-22022-webhook-signature-verification

Warning

Review ran into problems

🔥 Problems

Stopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a @coderabbit review after the pipeline has finished.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Rabsztok
Copy link
Copy Markdown
Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 20, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/lib/webhooks/verify-signature.ts`:
- Around line 50-52: The payload-type check in verifySignature (the function
handling parameters payload, signature, secret) currently allows empty
strings/Buffers; update the guard so that it also rejects empty payloads by
returning false when payload is an empty string (payload.length === 0) or an
empty Buffer (payload.length === 0) in addition to the existing
typeof/Buffer.isBuffer checks; keep the existing type check logic but add the
emptiness condition so empty inputs explicitly return false.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9d01f3a3-563c-4243-8f35-779cff4476d0

📥 Commits

Reviewing files that changed from the base of the PR and between 9a8e14f and 2bad438.

📒 Files selected for processing (5)
  • README.md
  • examples/webhooks/verify-signature.ts
  • src/__tests__/lib/webhooks/verify-signature.test.ts
  • src/index.ts
  • src/lib/webhooks/verify-signature.ts

Comment thread src/lib/webhooks/verify-signature.ts
Add `verifyWebhookSignature(payload, signature, signingSecret)` exported
from the package root for verifying Mailtrap webhook signatures using
HMAC-SHA256 over the raw request body with constant-time hex comparison
via `crypto.timingSafeEqual`.

Returns false (no throw) for missing/empty/malformed/wrong-length
signatures so a single guard at the request handler covers every bad-input
case. Accepts `string | Buffer` payloads; signed input must be the raw
body bytes — the README and example warn against `express.json()` and show
the `express.raw({type: 'application/json'})` pattern.

Includes the shared cross-SDK test fixture (payload + secret + expected
signature) that all six Mailtrap SDKs use to stay byte-for-byte
compatible, plus a runnable Express receiver example and README
subsection.

See https://railsware.atlassian.net/browse/MT-22022
@Rabsztok Rabsztok force-pushed the MT-22022-webhook-signature-verification branch from 2bad438 to eaab34a Compare May 20, 2026 14:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant