Coverage for fastid / security / webhooks.py: 100%
30 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-10-18 16:37 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-10-18 16:37 +0000
1import hashlib
2import hmac
3import json
4import time
5from typing import Any
7from fastid.database.utils import UUIDv7, uuid
8from fastid.webhooks.config import webhook_settings
9from fastid.webhooks.schemas import SignatureAlgorithm
11HASH_FUNCTIONS = {
12 SignatureAlgorithm.sha256: hashlib.sha256,
13 SignatureAlgorithm.sha512: hashlib.sha512,
14 SignatureAlgorithm.sha1: hashlib.sha1,
15}
18def generate_headers(
19 payload: dict[str, Any],
20 timestamp: int,
21 webhook_id: str,
22 secret_key: str,
23 *,
24 algorithm: SignatureAlgorithm = webhook_settings.signature_algorithm,
25) -> dict[str, str]:
26 signature = generate_signature(payload, webhook_id, timestamp, secret_key, algorithm=algorithm)
27 return {
28 webhook_settings.id_header: webhook_id,
29 webhook_settings.timestamp_header: str(timestamp),
30 webhook_settings.signature_header: signature,
31 }
34def generate_signature(
35 payload: dict[str, Any],
36 webhook_id: str,
37 timestamp: int,
38 secret_key: str,
39 *,
40 algorithm: SignatureAlgorithm = webhook_settings.signature_algorithm,
41) -> str:
42 payload_str = json.dumps(payload, sort_keys=True, separators=(",", ":"))
43 payload_str = f"{webhook_id}.{timestamp}.{payload_str}"
44 hash_func = HASH_FUNCTIONS[algorithm]
45 hmac_obj = hmac.new(key=secret_key.encode(), msg=payload_str.encode(), digestmod=hash_func)
46 return hmac_obj.hexdigest()
49def verify_headers(
50 payload: dict[str, Any],
51 headers: dict[str, str],
52 secret_key: str,
53 tolerance_seconds: int = webhook_settings.tolerance_seconds,
54) -> bool:
55 try:
56 timestamp = int(headers[webhook_settings.timestamp_header])
57 webhook_id = headers[webhook_settings.id_header]
58 received_signature = headers[webhook_settings.signature_header]
59 except (KeyError, ValueError): # pragma: nocover
60 return False
62 if not all([timestamp, webhook_id, received_signature]):
63 return False
65 if not is_timestamp_valid(timestamp, tolerance_seconds):
66 return False
68 expected_signature = generate_signature(payload, webhook_id, timestamp, secret_key)
69 return hmac.compare_digest(received_signature, expected_signature)
72def get_event_id() -> UUIDv7:
73 return uuid()
76def get_webhook_id() -> UUIDv7:
77 return uuid()
80def get_timestamp() -> int:
81 return int(time.time())
84def is_timestamp_valid(timestamp: int, tolerance_seconds: int) -> bool:
85 current_time = int(time.time())
86 return abs(current_time - timestamp) <= tolerance_seconds