67 lines
2.2 KiB
Python
67 lines
2.2 KiB
Python
"""Czysta logika webhooka auto-deployu: weryfikacja HMAC + klasyfikacja pusha.
|
|
|
|
Oddzielone od listenera, zeby dalo sie testowac bez serwera HTTP
|
|
(ops/deploy/test/test_autodeploy.py). Format sygnatury Gitei:
|
|
`X-Gitea-Signature` = hex(hmac_sha256(secret, raw_body)).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
from typing import Any
|
|
|
|
ZERO_SHA = "0" * 40
|
|
DEPLOY_MARKER = "[skip deploy]"
|
|
|
|
|
|
def verify_signature(secret: str, signature_header: str, body: bytes) -> bool:
|
|
if not secret or not signature_header:
|
|
return False
|
|
expected = hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
|
|
return hmac.compare_digest(expected, signature_header.strip().lower())
|
|
|
|
|
|
def classify_push(payload: Any, *, repo: str, branch_ref: str) -> dict[str, Any]:
|
|
"""Rozstrzyga payload pusha wzgledem polityki auto-deployu FitOS.
|
|
|
|
Zwrota status: "accepted" | "ignored" | "rejected" (+ powod/pola).
|
|
Twarda zasada: auto-deploy istnieje WYLACZNIE dla repo `repo` — kazde
|
|
inne repo na Gitei jest odrzucane (403), nawet poprawnie podpisane.
|
|
"""
|
|
if not isinstance(payload, dict):
|
|
return {"status": "rejected", "reason": "malformed json"}
|
|
|
|
repo_full = str(((payload.get("repository") or {}).get("full_name")) or "")
|
|
if repo_full != repo:
|
|
return {"status": "rejected", "reason": f"repo {repo_full!r} nie jest {repo!r} — auto-deploy dotyczy wylacznie FitOS"}
|
|
|
|
ref = str(payload.get("ref") or "")
|
|
if ref != branch_ref:
|
|
return {"status": "ignored", "reason": f"ref {ref!r} != {branch_ref!r}"}
|
|
|
|
after = str(payload.get("after") or "")
|
|
if not after or after.lower() == ZERO_SHA:
|
|
return {"status": "ignored", "reason": "usuniecie/gitowka galazie — brak head commita"}
|
|
|
|
commits = payload.get("commits")
|
|
head_msg = ""
|
|
if isinstance(commits, list) and commits:
|
|
head_msg = str((commits[-1] or {}).get("message") or "")
|
|
|
|
return {
|
|
"status": "accepted",
|
|
"sha": after,
|
|
"ref": ref,
|
|
"repo": repo_full,
|
|
"skip_marker": DEPLOY_MARKER in head_msg,
|
|
}
|
|
|
|
|
|
def parse_json(raw: bytes) -> Any:
|
|
try:
|
|
return json.loads(raw.decode("utf-8"))
|
|
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
return None
|