How do you verify a GitHub webhook signature?
AdvancedConceptTesting, services & metrics
Answer
GitHub sends X-Hub-Signature-256: sha256=<hex>, an HMAC-SHA256 of the raw body using the shared secret. Compute it over the raw bytes (not re-serialized JSON) and compare in constant time.
import hashlib, hmac
@app.post("/webhook")
def webhook():
sig = request.headers.get("X-Hub-Signature-256", "")
expected = "sha256=" + hmac.new(SECRET.encode(), request.get_data(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(sig, expected):
abort(401)
event = request.headers["X-GitHub-Event"]
...
return "", 204
== leaks timing information; compare_digest does not. Also dedupe on X-GitHub-Delivery, since GitHub can redeliver.
More on Testing, services & metrics
Why should automation scripts have tests at all?BeginnerHow does pytest discover and run tests?BeginnerWhy does pytest use plain `assert` instead of `assertEqual`?BeginnerWhat are pytest fixtures, and what scopes exist?IntermediateWhat built-in fixtures do you use most?IntermediateHow does `@pytest.mark.parametrize` work?Beginner