A secure, zero-dependency python github webhook listener lets your VPS pull and deploy code within seconds of a git push without opening SSH ports to external CI runners or installing a heavyweight framework. Whenever a team ships updates to a self-hosted app, static site, or microservice stack, polling GitHub on a cron timer wastes bandwidth and delays releases, while exposing an unverified HTTP endpoint invites arbitrary code execution from spoofed POST requests. Built for Linux and macOS hosts running Python 3.10+, the listener below uses only the Python standard library to validate GitHub’s X-Hub-Signature-256 header with constant-time HMAC-SHA256 comparison, filter push events to a specific branch (such as refs/heads/main), run a single-threaded deploy lock so overlapping pushes never collide, support a synthetic --dry-run verification test, and run cleanly under systemd behind Nginx.
Key Takeaways & Script Specs
- Runtime & Dependencies: Python 3.10+ standard library only (
hmac,hashlib,http.server,subprocess,threading). - Security Model: Mandatory
X-Hub-Signature-256verification viahmac.compare_digest(), 1 MB payload cap, and localhost-only binding (127.0.0.1). - Execution Time: Returns HTTP 202 Accepted to GitHub in under 15 ms while running your deploy script asynchronously under a mutex lock.
- Safety Controls: Branch allowlisting,
shell=Falsefixed deploy script execution, and a built-in--dry-runHMAC self-test flag.
Table of Contents
Why Naive Webhook Receivers Get Exploited or Time Out
Many quick-start webhook snippets on the internet make two dangerous mistakes. First, they skip signature verification or compare hex digests with Python’s == operator. As emphasized in the official GitHub Validating Webhook Deliveries documentation, standard equality operators short-circuit on the first mismatched byte, leaking timing side-channel information. Using Python’s hmac.compare_digest() function alongside hashlib.sha256 eliminates timing leaks completely.
Second, naive listeners execute git pull and docker compose up -d --build synchronously inside the HTTP request handler. GitHub expects a webhook response within 10 seconds; if a container build takes 45 seconds, GitHub marks the delivery as timed out and retries—triggering duplicate concurrent deploys. Our listener validates the signature, spawns a non-blocking worker thread protected by a mutex lock, and immediately returns HTTP 202 Accepted.
Architecture and Verification Flow
Every incoming POST request passes through four strict validation gates before touching your deployment script:
+-------------------------------------------------------------------+
| 1. Nginx TLS Reverse Proxy (:443) -> 127.0.0.1:9000/webhook |
|---|
|
v
+-------------------------------------------------------------------+
| 2. Read Raw UTF-8 Body (Cap <= 1 MB) & Verify X-Hub-Signature-256|
| - Compute sha256=HMAC(secret, raw_body) |
| - Constant-time check via hmac.compare_digest() -> 403 on fail|
+---------------------------------+---------------------------------+
| (Valid Signature)
v
+-------------------------------------------------------------------+
| 3. Filter Event & Branch |
| - X-GitHub-Event == "ping" -> 200 OK |
| - X-GitHub-Event == "push" and ref == "refs/heads/main" |
+---------------------------------+---------------------------------+
| (Match)
v
+-------------------------------------------------------------------+
| 4. Return 202 Accepted & Run Deploy Script Under Threading Lock |
+-------------------------------------------------------------------+
Pairing this lightweight listener with GitHub Actions CI/CD pipelines gives you full control over self-hosted deployments: GitHub Actions runs your unit tests and pushes the release tag, while your VPS pulls and restarts services locally without storing SSH private keys in GitHub Secrets. After deployment, your Docker health check script verifies that the updated containers pass live application probes.
Comparing Self-Hosted Auto-Deploy Patterns in 2027
Before deploying a webhook daemon, compare how the four common auto-deploy mechanisms trade off network exposure, dependencies, and speed.
| Deploy Pattern | Open SSH Required | External Dependencies | Latency After Push | Timing-Safe Auth |
|---|---|---|---|---|
| GitHub Actions SSH Action | Yes (port 22 exposed) | SSH key in Secrets | 10–30 seconds | Key-based SSH |
Cron git pull Loop | No | None | 1–5 minutes | N/A (polling) |
| Self-Hosted Actions Runner | No (outbound poll) | .NET Runner (~300 MB) | 2–5 seconds | GitHub Runner Token |
| Python Webhook Listener | No (HTTPS 443 only) | Zero (Python stdlib) | < 1 second | HMAC-SHA256 |
Because the Python listener requires zero third-party packages and consumes roughly 15 MB of RAM at rest, it fits comfortably on minimal $4–$6 cloud nodes alongside an Nginx log analyzer script and an SSL certificate expiry monitor script.
Prerequisites and Secret Setup
Create a dedicated directory and generate a cryptographically random 32-byte webhook secret using Python’s secrets module. Store that secret in a 0600 environment file so it never appears in shell history or process listings:
sudo mkdir -p /opt/github-webhook
sudo chown "$USER":"$USER" /opt/github-webhook
cd /opt/github-webhook
SECRET=$(python3 -c 'import secrets; print(secrets.token_hex(32))')
cat <<EOF > /opt/github-webhook/.env
GITHUB_WEBHOOK_SECRET=${SECRET}
TARGET_REF=refs/heads/main
DEPLOY_SCRIPT=/opt/github-webhook/deploy.sh
LISTEN_HOST=127.0.0.1
LISTEN_PORT=9000
EOF
chmod 600 /opt/github-webhook/.env
echo "Copy this secret into GitHub Repo -> Settings -> Webhooks:"
echo "${SECRET}"
Next, create an executable /opt/github-webhook/deploy.sh script tailored to your repository (for example, pulling main and restarting your Compose stack).
Complete Production Python GitHub Webhook Listener
Save the following zero-dependency script as /opt/github-webhook/webhook_listener.py. It validates raw UTF-8 request bodies against X-Hub-Signature-256, serializes concurrent deploy runs with a non-blocking queue/lock, and includes a --dry-run flag that signs a synthetic payload and runs end-to-end verification locally.
#!/usr/bin/env python3
"""
Production Python GitHub Webhook Listener (2027)
Zero-dependency HTTP listener that verifies GitHub X-Hub-Signature-256
headers with hmac.compare_digest(), filters branches, and runs deploys safely.
"""
import argparse
import hashlib
import hmac
import json
import logging
import os
import subprocess
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Optional
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
stream=sys.stdout,
)
logger = logging.getLogger("github_webhook")
MAX_BODY_BYTES = 1024 * 1024 # 1 MB safety cap
DEPLOY_LOCK = threading.Lock()
def verify_signature(payload_body: bytes, secret: str, signature_header: Optional[str]) -> bool:
"""Validate GitHub HMAC-SHA256 signature in constant time."""
if not signature_header or not signature_header.startswith("sha256="):
return False
digest = hmac.new(
secret.encode("utf-8"),
msg=payload_body,
digestmod=hashlib.sha256,
).hexdigest()
expected = f"sha256={digest}"
return hmac.compare_digest(expected, signature_header)
def run_deploy_async(deploy_script: Path, delivery_id: str, dry_run: bool) -> None:
"""Execute the fixed deploy script under a mutex lock."""
def _worker() -> None:
if not DEPLOY_LOCK.acquire(blocking=False):
logger.warning(
"Delivery %s skipped: another deployment is currently running.",
delivery_id,
)
return
try:
if dry_run:
logger.info(
"[DRY-RUN] Would execute %s for delivery %s",
deploy_script,
delivery_id,
)
return
logger.info("Starting deploy %s (delivery=%s)", deploy_script, delivery_id)
proc = subprocess.run(
[str(deploy_script)],
capture_output=True,
text=True,
timeout=300,
check=False,
)
if proc.returncode == 0:
logger.info("Deploy succeeded (delivery=%s).", delivery_id)
else:
logger.error(
"Deploy failed (exit=%d, delivery=%s): %s",
proc.returncode,
delivery_id,
proc.stderr.strip()[-400:],
)
except subprocess.TimeoutExpired:
logger.error("Deploy timed out after 300s (delivery=%s).", delivery_id)
finally:
DEPLOY_LOCK.release()
threading.Thread(target=_worker, daemon=True).start()
class WebhookHandler(BaseHTTPRequestHandler):
secret: str = ""
target_ref: str = "refs/heads/main"
deploy_script: Path = Path("/opt/github-webhook/deploy.sh")
dry_run: bool = False
def log_message(self, format: str, *args) -> None:
"""Route BaseHTTPRequestHandler logs through Python logging."""
logger.info("%s - %s", self.address_string(), format % args)
def _send_json(self, status_code: int, payload: dict) -> None:
body = json.dumps(payload).encode("utf-8")
self.send_response(status_code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self) -> None:
if self.path.rstrip("/") != "/webhook":
self._send_json(404, {"error": "Not found"})
return
try:
content_length = int(self.headers.get("Content-Length", "0"))
except ValueError:
self._send_json(400, {"error": "Invalid Content-Length"})
return
if content_length <= 0 or content_length > MAX_BODY_BYTES:
self._send_json(413, {"error": "Payload missing or exceeds 1 MB limit"})
return
raw_body = self.rfile.read(content_length)
sig_header = self.headers.get("X-Hub-Signature-256")
if not verify_signature(raw_body, self.secret, sig_header):
logger.warning("Rejected request with invalid signature from %s", self.client_address[0])
self._send_json(403, {"error": "Invalid signature"})
return
event = self.headers.get("X-GitHub-Event", "")
delivery_id = self.headers.get("X-GitHub-Delivery", "unknown")
if event == "ping":
self._send_json(200, {"status": "pong", "delivery": delivery_id})
return
if event != "push":
self._send_json(200, {"status": "ignored", "event": event})
return
try:
data = json.loads(raw_body.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError):
self._send_json(400, {"error": "Malformed JSON payload"})
return
ref = data.get("ref", "")
if ref != self.target_ref:
self._send_json(200, {"status": "ignored", "ref": ref})
return
run_deploy_async(self.deploy_script, delivery_id, self.dry_run)
self._send_json(202, {"status": "accepted", "delivery": delivery_id, "ref": ref})
def run_dry_run_self_test(secret: str, target_ref: str, deploy_script: Path) -> int:
"""Sign a synthetic push payload and verify HMAC + script path checks."""
sample = json.dumps({"ref": target_ref, "after": "0000000"}).encode("utf-8")
sig = "sha256=" + hmac.new(secret.encode("utf-8"), sample, hashlib.sha256).hexdigest()
valid = verify_signature(sample, secret, sig)
tampered = verify_signature(sample + b" ", secret, sig)
logger.info("[DRY-RUN] Valid HMAC check: %s | Tampered check: %s", valid, tampered)
logger.info(
"[DRY-RUN] Target ref=%s | Deploy script=%s (exists=%s)",
target_ref,
deploy_script,
deploy_script.is_file(),
)
return 0 if (valid and not tampered) else 1
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Verify GitHub HMAC-SHA256 webhooks and trigger deployments."
)
parser.add_argument(
"--host",
default=os.getenv("LISTEN_HOST", "127.0.0.1"),
help="Bind address (default: 127.0.0.1)",
)
parser.add_argument(
"--port",
type=int,
default=int(os.getenv("LISTEN_PORT", "9000")),
help="Listen port (default: 9000)",
)
parser.add_argument(
"--ref",
default=os.getenv("TARGET_REF", "refs/heads/main"),
help="Git ref to deploy on push (default: refs/heads/main)",
)
parser.add_argument(
"--deploy-script",
default=os.getenv("DEPLOY_SCRIPT", "/opt/github-webhook/deploy.sh"),
help="Executable script invoked on matching push",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Run a synthetic HMAC-SHA256 self-test and exit without starting HTTP server",
)
return parser.parse_args()
def main() -> int:
args = parse_args()
secret = os.getenv("GITHUB_WEBHOOK_SECRET", "")
if not secret:
logger.critical("GITHUB_WEBHOOK_SECRET environment variable is required.")
return 1
deploy_path = Path(args.deploy_script)
if args.dry_run:
return run_dry_run_self_test(secret, args.ref, deploy_path)
if not deploy_path.is_file():
logger.critical("Deploy script not found: %s", deploy_path)
return 1
WebhookHandler.secret = secret
WebhookHandler.target_ref = args.ref
WebhookHandler.deploy_script = deploy_path
WebhookHandler.dry_run = False
server = ThreadingHTTPServer((args.host, args.port), WebhookHandler)
logger.info("Listening on http://%s:%d/webhook (ref=%s)", args.host, args.port, args.ref)
try:
server.serve_forever()
except KeyboardInterrupt:
logger.info("Shutting down webhook listener.")
server.server_close()
return 0
if name == "main":
sys.exit(main())
Run the built-in --dry-run self-test to verify HMAC-SHA256 signing and tamper rejection before starting the daemon:
chmod +x /opt/github-webhook/webhook_listener.py
set -a && source /opt/github-webhook/.env && set +a
python3 /opt/github-webhook/webhook_listener.py --dry-run
Running Under Systemd Behind an Nginx TLS Proxy
Never expose Python’s http.server directly to the public internet without TLS. Keep the listener bound to 127.0.0.1:9000 under a systemd unit, and terminate HTTPS on port 443 with Nginx:
sudo tee /etc/systemd/system/github-webhook.service >/dev/null <<'EOF'
[Unit]
Description=GitHub HMAC-SHA256 Webhook Deploy Listener
After=network-online.target
[Service]
Type=simple
WorkingDirectory=/opt/github-webhook
EnvironmentFile=/opt/github-webhook/.env
ExecStart=/usr/bin/python3 /opt/github-webhook/webhook_listener.py
Restart=always
RestartSec=5
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now github-webhook
In your Nginx server block, proxy /webhook directly to http://127.0.0.1:9000/webhook without buffering or modifying the request body.
Troubleshooting and Security Hardening
Watch out for these three common production pitfalls when configuring GitHub webhooks behind reverse proxies:
- Body Modification Breaking Signatures: HMAC-SHA256 is computed over the exact raw bytes sent by GitHub. Never parse and re-serialize JSON before calling
verify_signature(), and ensure your reverse proxy does not alter body encoding. - Content Type Setting in GitHub: In GitHub Repository Settings → Webhooks, set Content type to
application/json(notapplication/x-www-form-urlencoded) so the listener parses the JSON payload cleanly. - Payload Size and Non-Root Execution: Keep
MAX_BODY_BYTEScapped at 1 MB and rungithub-webhook.serviceas a dedicated deploy user that owns only the target repository directory—never asroot.
Frequently Asked Questions
Why must I use hmac.compare_digest() instead of == for GitHub webhooks?
Standard string equality (==) returns false as soon as the first mismatched byte is found, which leaks timing differences to attackers. hmac.compare_digest() runs in constant time across the full string length.
Why does the listener return HTTP 202 before the deploy finishes?
GitHub enforces a 10-second delivery timeout on webhook requests. Returning 202 Accepted immediately and running the deploy script asynchronously under a mutex lock prevents timeouts and duplicate retries.
What happens if two pushes arrive while a deploy is already running?
Because DEPLOY_LOCK.acquire(blocking=False) is non-blocking, overlapping deliveries are safely skipped and logged rather than corrupting your working directory with concurrent git pull commands.
Does this Python GitHub webhook listener require Flask or FastAPI?
No. It uses Python’s built-in ThreadingHTTPServer, hmac, hashlib, and subprocess modules, so there are zero pip packages or virtual environments to maintain.
How do I test signature verification locally without pushing to GitHub?
Run python3 webhook_listener.py –dry-run after sourcing your .env file. It signs a synthetic JSON payload with your secret and verifies both valid acceptance and tampered-payload rejection.
Can I deploy a branch other than main?
Yes. Set TARGET_REF=refs/heads/production (or any branch ref) in your .env file or pass –ref on the command line.