Interview Prep/Python for DevOps/Testing, services & metrics

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.

All Python for DevOps questions Roadmap: Python for automation

More on Testing, services & metrics