feat(gitops): add webhook authentication

This commit is contained in:
kiskaadee committed 2026-09-13 03:10:57 -05:00
1 parent 01acdb4f75
commit fa8054aad5
4 files changed
+162 -2

No files matched your search

+6
View File
@@ -46,6 +46,7 @@ in
"authelia/users/kiskaadee/password_hash"
"authelia/users/misa/password_hash"
"authelia/users/valenvg/password_hash"
"gitops/webhook_secret"
] (name: { owner = "kiskaadee"; });
# Generate the unified environment file at runtime in /run/secrets/homeserver.env
@@ -93,6 +94,10 @@ in
path = with pkgs; [ git docker docker-compose python3 coreutils bash openssh ];
environment = {
GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path;
};
serviceConfig = {
Type = "simple";
User = "kiskaadee";
@@ -103,6 +108,7 @@ in
execute-command = "/home/kiskaadee/Core/scripts/gitops_dispatcher.py";
pass-arguments-to-command = [
{ source = "entire-payload"; }
{ source = "header"; name = "X-Gitea-Signature"; }
];
command-working-directory = "/home/kiskaadee/Core";
response-message = "Deployment payload dispatched successfully.";
+4 -2
View File
@@ -33,6 +33,8 @@ learning:
system:
gh_repo_token: ENC[AES256_GCM,data:QAsmG5iQQJ4TUhtrIbkq3wlw4JWbj2tFX6u2BbdB4werXfWyak8sdw==,iv:orGtlDW71QHDRSTED1xNfdOggF61hHsbGztWOUSdY+Y=,tag:4xe1I+hNjxWLc16BW4yTLA==,type:str]
pdf_decrypt_password: ENC[AES256_GCM,data:n3XTANd+PbejUw==,iv:y2VIabyv/DfTgztbjS6M/xIfRNKOL+U+r3eXsal32OQ=,tag:oFpXg2E9dDM5dwkjSZkLgw==,type:str]
gitops:
webhook_secret: ENC[AES256_GCM,data:Kj3d0Repa3OOvjCkW6+kakQEfsCdpdVJQd71Am6zQHBt7QkLtxlnovUmmS+zJ+jChQBbCc9/7LunFvFT2pL36w==,iv:qh1pEIVtvB/fxbMv+a9pworhbXsIpfF5gKWS22Zn0GU=,tag:D4RNXkWhg9l3BJFp7MMloA==,type:str]
sops:
age:
- enc: |
@@ -53,7 +55,7 @@ sops:
yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A==
-----END AGE ENCRYPTED FILE-----
recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg
lastmodified: "2026-09-11T19:59:23Z"
mac: ENC[AES256_GCM,data:BcBncbSLf5CdYQxLn5THA6aMyxqipHpTwTgPOSZXf4B8PwO7yH4J7mL/sKEZ08448nAUaOABOrgFHoLlvVzGrUVJegRC/G9OgFQT8A4v1Dkq0yx0VSplMtf2q4ylyTjLHQb5bd4r4OzfBNFjmruyrZHS3ydxn8gfbgOft50w2vM=,iv:dTzR9j4crCaaG/wjMRxiGjVZMyBNOCN+qKlSN34m0m8=,tag:D8go58ulc1nu5biQWq1TpA==,type:str]
lastmodified: "2026-09-13T08:09:29Z"
mac: ENC[AES256_GCM,data:aP+BwlAIFXxg4gBvgzPOJyqz2AMJjUpMPZhs3sZc6vSmcRU2ARoHNZ4tEaIdGNumtPd++5Xi7a2CVj5rwI9Y/dpouXkdw8p7xNlbmt2d9BbKlXNH8XfDDiDXlKHHdFyI2diX3G62k87CC684oWjIQgf/w3+kuJ+N/ZkbV8N69ZM=,iv:RJaNa76TkY8aIYXRzrqebJiHu6hBow3RYNSo6QP/Zy8=,tag:bAwWKXrH6aQVbkPNMZqgnQ==,type:str]
unencrypted_suffix: _unencrypted
version: 3.13.3
+70
View File
@@ -7,6 +7,8 @@ in ~/Sites (via app.yaml) or data vaults (like ~/Brain), and executes the declar
deployment actions with zero Core restarts.
"""
import hashlib
import hmac
import json
import logging
import os
@@ -18,6 +20,7 @@ from pathlib import Path
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
BRAIN_DIR = Path(os.environ.get("BRAIN_DIR", os.path.expanduser("~/Brain")))
CONFIG_DIR = Path(os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab")))
DEFAULT_SECRET_PATH = Path(os.environ.get("GITOPS_SECRET_FILE", "/run/secrets/gitops/webhook_secret"))
logging.basicConfig(
level=logging.INFO,
@@ -27,6 +30,55 @@ logging.basicConfig(
logger = logging.getLogger("gitops_dispatcher")
def load_webhook_secret(secret_file: Path | None = None) -> bytes:
"""
Load webhook shared secret from projected secret file or environment.
Never hardcoded in code or repository manifests.
"""
path = secret_file or Path(os.environ.get("GITOPS_SECRET_FILE", DEFAULT_SECRET_PATH))
if path.is_file():
try:
return path.read_bytes().strip()
except OSError as e:
logger.error(f"Failed to read webhook secret from {path}: {e}")
return b""
env_secret = os.environ.get("GITOPS_WEBHOOK_SECRET")
if env_secret:
return env_secret.strip().encode("utf-8")
return b""
def verify_signature(raw_body: bytes, signature: str | None, secret: bytes) -> bool:
"""
Verify incoming webhook HMAC-SHA256 signature using constant-time comparison.
Fail-closed: missing signature, malformed signature, empty secret, or mismatch returns False.
"""
if not secret:
logger.error("Authentication failed: Webhook shared secret is empty or missing.")
return False
if not signature or not isinstance(signature, str):
logger.error("Authentication failed: Missing signature header.")
return False
cleaned_signature = signature.strip()
cleaned_signature = cleaned_signature.removeprefix("sha256=")
# SHA256 hex digest is exactly 64 hexadecimal characters
if len(cleaned_signature) != 64 or not all(c in "0123456789abcdefABCDEF" for c in cleaned_signature):
logger.error("Authentication failed: Malformed signature format.")
return False
expected_mac = hmac.new(secret, raw_body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected_mac.lower(), cleaned_signature.lower()):
logger.error("Authentication failed: Signature mismatch.")
return False
return True
def parse_yaml_simple(text: str) -> dict:
"""Lightweight, zero-dependency YAML parser tailored for app.yaml manifests."""
data = {}
@@ -303,6 +355,18 @@ def main():
payload_raw = ""
repo_name = ""
branch = "main"
signature = None
if "--signature" in sys.argv:
sig_idx = sys.argv.index("--signature")
if sig_idx + 1 < len(sys.argv):
signature = sys.argv[sig_idx + 1]
elif len(sys.argv) > 2 and not sys.argv[2].startswith("-"):
signature = sys.argv[2]
elif os.environ.get("HTTP_X_GITEA_SIGNATURE"):
signature = os.environ.get("HTTP_X_GITEA_SIGNATURE")
elif os.environ.get("X_GITEA_SIGNATURE"):
signature = os.environ.get("X_GITEA_SIGNATURE")
# Support CLI arguments for manual trigger: --repo <name> [--branch <branch>]
if "--repo" in sys.argv:
@@ -325,6 +389,12 @@ def main():
logger.error("No webhook payload provided (checked sys.argv and stdin).")
sys.exit(1)
raw_body = payload_raw.encode("utf-8")
secret = load_webhook_secret()
if not verify_signature(raw_body, signature, secret):
logger.error("❌ Webhook authentication failed. Rejecting request.")
sys.exit(1)
try:
payload = json.loads(payload_raw)
repo_name = payload.get("repository", {}).get("name", "")
+82
View File
@@ -141,3 +141,85 @@ def test_resolve_repository_resolves_vault(tmp_path: Path, monkeypatch):
assert gitops_dispatcher.resolve_repository("Brain") == canonical
assert gitops_dispatcher.resolve_repository("brain") == canonical
def test_webhook_verification_valid_signature():
"""Ensure valid HMAC-SHA256 signature passes verification."""
import hashlib
import hmac
secret = b"supersecrettoken123"
body = b'{"repository": {"name": "docs"}, "ref": "refs/heads/main"}'
expected_hex = hmac.new(secret, body, hashlib.sha256).hexdigest()
assert gitops_dispatcher.verify_signature(body, expected_hex, secret) is True
# Support sha256= prefix as well
assert gitops_dispatcher.verify_signature(body, f"sha256={expected_hex}", secret) is True
def test_webhook_verification_invalid_signature():
"""Ensure incorrect signature is rejected."""
secret = b"supersecrettoken123"
body = b'{"repository": {"name": "docs"}}'
bad_sig = "a" * 64
assert gitops_dispatcher.verify_signature(body, bad_sig, secret) is False
def test_webhook_verification_missing_signature():
"""Ensure missing signature header is rejected."""
secret = b"supersecrettoken123"
body = b'{"repository": {"name": "docs"}}'
assert gitops_dispatcher.verify_signature(body, None, secret) is False
assert gitops_dispatcher.verify_signature(body, "", secret) is False
def test_webhook_verification_modified_body():
"""Ensure signature mismatch from tampered body fails verification."""
import hashlib
import hmac
secret = b"supersecrettoken123"
body_original = b'{"repository": {"name": "docs"}}'
sig = hmac.new(secret, body_original, hashlib.sha256).hexdigest()
body_tampered = b'{"repository": {"name": "evil-app"}}'
assert gitops_dispatcher.verify_signature(body_tampered, sig, secret) is False
def test_webhook_verification_modified_signature():
"""Ensure single-character flip in signature fails verification."""
import hashlib
import hmac
secret = b"supersecrettoken123"
body = b'{"repository": {"name": "docs"}}'
sig = list(hmac.new(secret, body, hashlib.sha256).hexdigest())
sig[0] = "0" if sig[0] != "0" else "1"
flipped_sig = "".join(sig)
assert gitops_dispatcher.verify_signature(body, flipped_sig, secret) is False
def test_webhook_verification_empty_secret_fails_closed():
"""Ensure empty or missing shared secret fails closed."""
import hashlib
import hmac
secret = b""
body = b'{"repository": {"name": "docs"}}'
sig = hmac.new(b"somekey", body, hashlib.sha256).hexdigest()
assert gitops_dispatcher.verify_signature(body, sig, secret) is False
def test_webhook_verification_malformed_signature():
"""Ensure non-hex or invalid length signatures fail closed."""
secret = b"supersecrettoken123"
body = b'{"repository": {"name": "docs"}}'
assert gitops_dispatcher.verify_signature(body, "not-a-valid-hex-digest", secret) is False
assert gitops_dispatcher.verify_signature(body, "deadbeef", secret) is False
assert gitops_dispatcher.verify_signature(body, "z" * 64, secret) is False