From 218d1a1366d4665b5acbf65c4ce27fd7c0c98b07 Mon Sep 17 00:00:00 2001 From: rainyy21 Date: Wed, 11 Nov 2026 09:50:38 -0500 Subject: [PATCH] added ed webhook to it --- README.MD | 0 app/web/docker-compose.yml | 1 + app/web/watcher_additions.py | 15 ++++++------ app/web/web/app.py | 45 +++++++++++++++++++++++++++++++++--- 4 files changed, 51 insertions(+), 10 deletions(-) create mode 100644 README.MD diff --git a/README.MD b/README.MD new file mode 100644 index 0000000..e69de29 diff --git a/app/web/docker-compose.yml b/app/web/docker-compose.yml index e353b9f..3c91071 100644 --- a/app/web/docker-compose.yml +++ b/app/web/docker-compose.yml @@ -38,6 +38,7 @@ services: REQUESTS_DIR: /data/requests TOKEN_ENVS: GITEA_TOKEN,GITHUB_TOKEN # names only, for the add-repo dropdown SECRET_KEY: ${WEB_SECRET_KEY} + WEBHOOK_SECRET: ${WEBHOOK_SECRET} # same value goes in the GitHub/Gitea webhook settings volumes: # NO docker socket: the website can't run containers, only ask the watcher - ./config:/config:ro diff --git a/app/web/watcher_additions.py b/app/web/watcher_additions.py index d3626f6..c0736a9 100644 --- a/app/web/watcher_additions.py +++ b/app/web/watcher_additions.py @@ -181,13 +181,14 @@ def process_requests(state: dict) -> None: # if repo["paused"]: # continue # -# c) so the website reacts fast: wait in short steps and wake up early -# when a request file shows up. Replace the end-of-round wait with: +# c) so the website and webhooks react fast: wait_for_next_round() already +# wakes up early via has_requests(), but only for the CLI's REQUEST_DIR. +# Make it look at the website's folder too: # -# deadline = time.monotonic() + max(0, CHECK_INTERVAL - elapsed) -# while not STOP.is_set() and time.monotonic() < deadline: -# if any(REQUESTS_DIR.glob("*.json")): -# break -# STOP.wait(2) +# def has_requests() -> bool: +# return any(d.is_dir() and any(d.glob("*.json")) +# for d in (REQUEST_DIR, REQUESTS_DIR)) # +# Only do this together with (a): if nothing deletes the files in +# REQUESTS_DIR, the watcher would wake up every second forever. # (a full round then runs: requests first, then the normal checks) diff --git a/app/web/web/app.py b/app/web/web/app.py index 23b9225..1a537fc 100644 --- a/app/web/web/app.py +++ b/app/web/web/app.py @@ -8,6 +8,8 @@ Runs as its own container. It never touches Docker: it only - WRITES local files (data/local/) -> .env, overrides, etc. """ +import hashlib +import hmac import json import os import re @@ -29,6 +31,7 @@ LOCAL_DIR = Path(os.environ.get("LOCAL_DIR", "data/local")) REQUESTS_DIR = Path(os.environ.get("REQUESTS_DIR", "data/requests")) CHECK_INTERVAL = int(os.environ.get("CHECK_INTERVAL", "300")) TOKEN_ENVS = [t for t in os.environ.get("TOKEN_ENVS", "GITEA_TOKEN,GITHUB_TOKEN").split(",") if t] +WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "") # empty = webhooks turned off MAX_FILE = 256 * 1024 # biggest file the editor will open/save SAFE_REPO = re.compile(r"^[a-z0-9][a-z0-9_-]{0,62}$") # compose project names are lowercase @@ -194,18 +197,21 @@ app.jinja_env.globals["csrf_token"] = csrf_token @app.before_request def check_csrf(): - if request.method == "POST": + # webhooks can't send our token; they're checked by their HMAC signature instead + if request.method == "POST" and not request.path.startswith("/webhook/"): sent = request.form.get("csrf") or request.headers.get("X-CSRF-Token") or "" - if not secrets.compare_digest(sent, session.get("csrf", "")): + expected = session.get("csrf", "") + if not expected or not secrets.compare_digest(sent, expected): # no session = no token = reject abort(400, "invalid or missing CSRF token: reload the page and try again") @app.errorhandler(400) +@app.errorhandler(403) @app.errorhandler(404) @app.errorhandler(413) @app.errorhandler(415) def api_errors(e): - if request.path.startswith("/api/"): + if request.path.startswith(("/api/", "/webhook/")): return jsonify(error=e.description), e.code return e @@ -407,5 +413,38 @@ def save_file(name: str, filename: str): return jsonify(ok=True, missing_env=missing_env(name), shadows_git=shadows) + +# ---------- webhooks (GitHub / Gitea call this on every push) ---------- + +def valid_signature(body: bytes) -> bool: + """GitHub sends X-Hub-Signature-256: sha256=, Gitea sends X-Gitea-Signature: .""" + if not WEBHOOK_SECRET: + return False + expected = hmac.new(WEBHOOK_SECRET.encode(), body, hashlib.sha256).hexdigest() + sent = (request.headers.get("X-Hub-Signature-256", "").removeprefix("sha256=") + or request.headers.get("X-Gitea-Signature", "")) + return bool(sent) and hmac.compare_digest(sent, expected) + + +@app.post("/webhook/") +def webhook(name: str): + if not valid_signature(request.get_data()): # before get_repo, so strangers can't probe repo names + abort(403, "bad or missing signature") + repo = get_repo(name) + event = request.headers.get("X-GitHub-Event") or request.headers.get("X-Gitea-Event") + if event == "ping": + return jsonify(ok=True, msg="pong") + if event != "push": + return jsonify(ok=True, ignored=f"event {event}") + ref = (request.get_json(silent=True) or {}).get("ref", "") + if ref != f"refs/heads/{repo['branch']}": + return jsonify(ok=True, ignored=f"push to {ref}") + if repo["paused"]: + return jsonify(ok=True, ignored="paused") + if name not in pending_requests(): # 5 quick pushes = 1 deploy + queue_request("deploy", name) + return jsonify(ok=True, queued="deploy"), 202 + + if __name__ == "__main__": app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))