jamframe 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
jamframe/webhooks.py ADDED
@@ -0,0 +1,194 @@
1
+ """Verify the signature of webhook deliveries.
2
+
3
+ Every delivery carries ``X-Webhook-Signature: t=<unix seconds>,v1=<hex>``,
4
+ where ``v1`` is the HMAC-SHA256 of ``f"{t}.{raw body}"`` keyed with the
5
+ subscription's signing secret (``wh_sec_…``, shown once when you subscribe or
6
+ rotate). Always verify the **raw** request bytes: re-serialised JSON has
7
+ different bytes.
8
+
9
+ >>> event = construct_event(request.get_data(), request.headers, secret)
10
+ >>> if event["type"] == "render.completed": ...
11
+
12
+ The ``webhookUrl`` callback of a single render request is *not* signed; this
13
+ module is for subscription deliveries.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import hmac
20
+ import json
21
+ import re
22
+ import time
23
+ from typing import List, Mapping, Optional, Sequence, Tuple, Union, cast
24
+
25
+ from .errors import WebhookSignatureError
26
+ from .types import WebhookEvent
27
+
28
+ SIGNATURE_HEADER = "X-Webhook-Signature"
29
+ TIMESTAMP_HEADER = "X-Webhook-Timestamp"
30
+ EVENT_HEADER = "X-Webhook-Event"
31
+ DELIVERY_HEADER = "X-Webhook-Delivery"
32
+ """Unique per subscription and event, unchanged across retries: deduplicate on it."""
33
+
34
+ DEFAULT_TOLERANCE = 300
35
+ """Seconds a signature stays valid either side of now (replay protection)."""
36
+
37
+ Payload = Union[bytes, bytearray, memoryview, str]
38
+ HeaderInput = Union[str, Mapping[str, str], None]
39
+ Secrets = Union[str, Sequence[str]]
40
+
41
+
42
+ # Unix seconds: ASCII digits only (``int()`` would also take "+1", "1_000" or
43
+ # other scripts' digits), and short enough to compare with ``time.time()``
44
+ # (a 400-digit value would raise OverflowError there).
45
+ _TIMESTAMP = re.compile(r"[0-9]{1,15}")
46
+ # A hex HMAC-SHA256; anything else can't match, and stays out of compare_digest.
47
+ _SIGNATURE = re.compile(r"[0-9a-fA-F]{64}")
48
+
49
+
50
+ def _raw(payload: Payload) -> bytes:
51
+ if isinstance(payload, str):
52
+ return payload.encode("utf-8")
53
+ if isinstance(payload, (bytes, bytearray, memoryview)):
54
+ return bytes(payload)
55
+ # A TypeError, not WebhookSignatureError, so verify_signature doesn't turn
56
+ # the mistake into a silent False: parsed JSON can't be verified.
57
+ raise TypeError(
58
+ "Pass the raw request body (bytes or str, e.g. request.get_data()), not parsed JSON: "
59
+ "re-serialised JSON has different bytes"
60
+ )
61
+
62
+
63
+ def _header_text(value: object) -> str:
64
+ if isinstance(value, (list, tuple)):
65
+ value = value[0] if value else ""
66
+ if isinstance(value, (bytes, bytearray)):
67
+ return bytes(value).decode("latin-1")
68
+ return value if isinstance(value, str) else ""
69
+
70
+
71
+ def _signature_header(header: HeaderInput) -> str:
72
+ """Accept the header's value, or the request's headers (any mapping, any case)."""
73
+ if header is None:
74
+ return ""
75
+ if isinstance(header, (str, bytes, bytearray)):
76
+ return _header_text(header)
77
+ wanted = SIGNATURE_HEADER.lower()
78
+ for key, value in header.items():
79
+ if isinstance(key, str) and key.lower() == wanted:
80
+ return _header_text(value)
81
+ return ""
82
+
83
+
84
+ def parse_signature_header(header: str) -> Tuple[Optional[int], List[str]]:
85
+ """``t=…,v1=…[,v1=…]`` -> (timestamp, signatures)."""
86
+ timestamp: Optional[int] = None
87
+ signatures: List[str] = []
88
+ for part in header.split(","):
89
+ key, sep, value = part.strip().partition("=")
90
+ if not sep:
91
+ continue
92
+ if key == "t":
93
+ if not _TIMESTAMP.fullmatch(value.strip()):
94
+ return None, []
95
+ timestamp = int(value.strip())
96
+ elif key == "v1" and value.strip():
97
+ signatures.append(value.strip().lower())
98
+ return timestamp, signatures
99
+
100
+
101
+ def compute_signature(payload: Payload, timestamp: int, secret: str) -> str:
102
+ """The ``v1`` value for ``payload`` signed at ``timestamp`` (for tests and fixtures)."""
103
+ signed = f"{timestamp}.".encode("utf-8") + _raw(payload)
104
+ return hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest()
105
+
106
+
107
+ def sign_header(payload: Payload, secret: str, timestamp: Optional[int] = None) -> str:
108
+ """A complete ``X-Webhook-Signature`` value, e.g. to test your own endpoint."""
109
+ t = int(time.time()) if timestamp is None else timestamp
110
+ return f"t={t},v1={compute_signature(payload, t, secret)}"
111
+
112
+
113
+ def _problem(
114
+ payload: Payload, header: HeaderInput, secret: Secrets, tolerance: Optional[float], now: Optional[float]
115
+ ) -> Optional[str]:
116
+ raw = _raw(payload)
117
+ value = _signature_header(header)
118
+ if not value:
119
+ return f"Missing {SIGNATURE_HEADER} header"
120
+ given: Sequence[object] = [secret] if isinstance(secret, str) else list(secret or [])
121
+ secrets = [s for s in given if isinstance(s, str) and s]
122
+ if not secrets:
123
+ return "No signing secret given"
124
+ timestamp, parsed = parse_signature_header(value)
125
+ signatures = [s for s in parsed if _SIGNATURE.fullmatch(s)]
126
+ if timestamp is None or not signatures:
127
+ return f"Malformed {SIGNATURE_HEADER} header"
128
+ current = time.time() if now is None else now
129
+ # `not (age <= tolerance)` so a NaN tolerance or clock refuses the delivery.
130
+ if tolerance is not None and not abs(current - timestamp) <= tolerance:
131
+ return f"Signature timestamp is outside the {tolerance:g} s tolerance"
132
+ for candidate in secrets:
133
+ expected = compute_signature(raw, timestamp, candidate).encode("ascii")
134
+ for signature in signatures:
135
+ if hmac.compare_digest(expected, signature.encode("ascii")):
136
+ return None
137
+ return "No signature matches the payload"
138
+
139
+
140
+ def verify_signature(
141
+ payload: Payload,
142
+ header: HeaderInput,
143
+ secret: Secrets,
144
+ *,
145
+ tolerance: Optional[float] = DEFAULT_TOLERANCE,
146
+ now: Optional[float] = None,
147
+ ) -> bool:
148
+ """``True`` when ``header`` is a valid, fresh signature of ``payload``.
149
+
150
+ ``payload`` is the raw body (bytes or str). ``header`` is the
151
+ ``X-Webhook-Signature`` value or the request's headers. ``secret`` may be
152
+ a list (e.g. the old and new secret while you rotate). ``tolerance`` is
153
+ in seconds (``None`` skips the freshness check; don't, outside tests).
154
+ """
155
+ return _problem(payload, header, secret, tolerance, now) is None
156
+
157
+
158
+ def construct_event(
159
+ payload: Payload,
160
+ header: HeaderInput,
161
+ secret: Secrets,
162
+ *,
163
+ tolerance: Optional[float] = DEFAULT_TOLERANCE,
164
+ now: Optional[float] = None,
165
+ ) -> WebhookEvent:
166
+ """Verify, then parse the delivery: ``{ id, type, createdAt, data }``.
167
+
168
+ Raises :class:`~jamframe.errors.WebhookSignatureError` when the signature
169
+ is missing, stale or wrong, or the body isn't an event.
170
+ """
171
+ problem = _problem(payload, header, secret, tolerance, now)
172
+ if problem:
173
+ raise WebhookSignatureError(problem)
174
+ try:
175
+ event = json.loads(_raw(payload).decode("utf-8"))
176
+ except (UnicodeDecodeError, ValueError) as exc:
177
+ raise WebhookSignatureError("The payload isn't JSON") from exc
178
+ if not isinstance(event, dict) or not isinstance(event.get("type"), str) or "data" not in event:
179
+ raise WebhookSignatureError("The payload isn't a webhook event")
180
+ return cast(WebhookEvent, event)
181
+
182
+
183
+ __all__ = [
184
+ "DEFAULT_TOLERANCE",
185
+ "DELIVERY_HEADER",
186
+ "EVENT_HEADER",
187
+ "SIGNATURE_HEADER",
188
+ "TIMESTAMP_HEADER",
189
+ "compute_signature",
190
+ "construct_event",
191
+ "parse_signature_header",
192
+ "sign_header",
193
+ "verify_signature",
194
+ ]