ruby
34 lines · 7 steps
Verifying webhook signatures with Rails routing constraints
A routing constraint validates an HMAC signature before a webhook request ever reaches its controller.
Explained by
highlit
1class WebhookSignatureConstraint
2 def initialize(provider)
3 @provider = provider
4 end
5
6 def matches?(request)
7 signature = request.headers["X-Webhook-Signature"].to_s
8 return false if signature.blank?
9
10 payload = request.raw_post
11 expected = OpenSSL::HMAC.hexdigest(
12 "SHA256",
13 Rails.application.credentials.dig(:webhooks, @provider, :secret),
14 payload
15 )
16
17 ActiveSupport::SecurityUtils.secure_compare("sha256=#{expected}", signature)
18 end
19end
20
21Rails.application.routes.draw do
22 namespace :webhooks do
23 constraints(WebhookSignatureConstraint.new(:stripe)) do
24 post "stripe", to: "stripe#create"
25 end
26
27 constraints(WebhookSignatureConstraint.new(:github)) do
28 post "github", to: "github#create"
29 end
30
31 post "stripe", to: "rejected#unauthorized"
32 post "github", to: "rejected#unauthorized"
33 end
34end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Routing constraints can gate requests on request content, not just path patterns.
- 2Always compare signatures with a constant-time function to defeat timing attacks.
- 3Ordering routes lets a fallback catch requests that fail the constraint.
Related explainers
javascript
const MAX_FILE_SIZE = 5 * 1024 * 1024; const ALLOWED_TYPES = { 'image/jpeg': ['jpg', 'jpeg'],
Validating file uploads by content, not just claims
input-validation
security
magic-bytes
Intermediate
7 steps
ruby
module UniqueJob extend ActiveSupport::Concern class_methods do
Deduplicating Active Job enqueues in Rails
concurrency
idempotency
caching
Advanced
9 steps
ruby
class OrderMailerPreview < ActionMailer::Preview def confirmation OrderMailer.confirmation(sample_order) end
Previewing Rails mailers with sample data
mailer-previews
test-fixtures
in-memory-objects
Beginner
6 steps
python
from fastapi import FastAPI, Request, status from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse
Redacting sensitive fields in FastAPI errors
validation
error-handling
security
Intermediate
7 steps
ruby
def render_table(rows) return "(no data)" if rows.empty? columns = rows.flat_map(&:keys).uniq
Rendering an ASCII table in Ruby
text-formatting
column-alignment
recursion
Intermediate
8 steps
ruby
class ApplicationController < ActionController::Base ALLOWED_REDIRECT_HOSTS = [nil, ENV.fetch("APP_HOST", "app.example.com")].freeze def store_return_to(location = request.fullpath)
Safe post-login redirects in Rails
open-redirect
session
authentication
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/verifying-webhook-signatures-with-rails-routing-constraints-explained-ruby-daa4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.