#!/usr/bin/env python3
"""GitHub-style raw-body HMAC example; credentials are supplied only by the operator."""
import hashlib
import hmac
import os
import re
import sys
from pathlib import Path

def valid_signature(secret, body, signature):
    if not isinstance(signature, str):
        return False
    if not re.fullmatch(r"sha256=[a-f0-9]{64}", signature):
        return False
    expected = "sha256=" + hmac.new(secret, body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(signature, expected)

def main():
    # Restrict request size at the HTTP boundary before reading the body.
    body = Path(sys.argv[1]).read_bytes()
    if len(body) > 1024 * 1024:
        raise ValueError("example body limit exceeded")
    secret = os.environ["WEBHOOK_TEST_SECRET"].encode("utf-8")
    if len(secret) < 16:
        raise ValueError("use a randomly generated secret, at least 16 bytes")
    signature = os.environ.get("WEBHOOK_TEST_SIGNATURE", "")
    accepted = valid_signature(secret, body, signature)
    # A real receiver also persists provider delivery IDs for idempotency.
    # GitHub's HMAC does not sign a caller-invented timestamp header.
    print("signature accepted" if accepted else "signature rejected")
    return 0 if accepted else 1

if __name__ == "__main__":
    try:
        sys.exit(main())
    except (ValueError, KeyError, IndexError, OSError) as error:
        print(type(error).__name__, file=sys.stderr)
        sys.exit(2)
