Fix Insecure Webhooks in Grape
Insecure webhooks in Grape APIs are a prime target for data injection and spoofing. Without cryptographic verification, an attacker can replay captured payloads or forge requests to trigger internal logic, leading to unauthorized state changes. To fix this, you must implement HMAC-SHA256 signature validation to ensure the payload originated from a trusted source and remained untampered during transit.
The Vulnerable Pattern
class WebhookAPI < Grape::API format :json
post ‘/events’ do # VULNERABLE: Directly processing params without origin verification EventProcessor.call(params) status 200 end end
The Secure Implementation
The fix involves three critical steps: 1. Extracting the raw request body before Grape parses it into the params hash, as the signature is calculated against the raw bytes. 2. Re-calculating the HMAC-SHA256 hash using a pre-shared secret known only to the provider and your app. 3. Using Rack::Utils.secure_compare for the string comparison to mitigate timing attacks, which could otherwise leak information about the valid signature byte-by-byte.
class WebhookAPI < Grape::API format :jsonhelpers do def verify_webhook_signature! secret = ENV[‘WEBHOOK_SHARED_SECRET’] signature = request.headers[‘X-Hub-Signature-256’]
error!('Missing signature', 401) if signature.nil? # Read raw body for HMAC calculation payload_body = request.body.read request.body.rewind # Rewind for Grape's internal parser computed_sig = 'sha256=' + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), secret, payload_body) # Use secure_compare to prevent timing attacks unless Rack::Utils.secure_compare(computed_sig, signature) error!('Invalid signature', 401) end endend
post ‘/events’ do verify_webhook_signature! EventProcessor.call(params) status 200 end end
Your Grape API
might be exposed to Insecure Webhooks
74% of Grape apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.