```python """退款 Webhook 验签、时间窗与重放防护(仅使用 Python 标准库)。 签名对象始终是收到的原始字节:ASCII(timestamp 原文) + b"." + raw_body, 绝不先解析 JSON 再重新序列化后计算。 """ import hashlib import hmac import json import re import threading _TS_RE = re.compile(r"(?:0|[1-9][0-9]*)") _SIG_RE = re.compile(r"sha256=[0-9a-f]{64}") _MAX_TS_DIGITS = 20 _MAX_EVENT_ID_LEN = 128 def _reject_duplicate_keys(pairs): """object_pairs_hook:任一对象内出现重复键即判为非法内容。""" obj = {} for key, value in pairs: if key in obj: raise ValueError("JSON 对象存在重复键: %r" % (key,)) obj[key] = value return obj def _reject_constant(name): """parse_constant:拒绝 NaN / Infinity / -Infinity 这些非标准字面量。""" raise ValueError("JSON 含非法字面量: %s" % (name,)) def _parse_json_object(raw_body): """严格解析 raw_body:UTF-8 严格解码、顶层必须是对象、拒绝重复键与 NaN/Infinity。""" try: text = raw_body.decode("utf-8", "strict") except UnicodeDecodeError as exc: raise ValueError("raw_body 不是严格 UTF-8") from exc try: payload = json.loads( text, object_pairs_hook=_reject_duplicate_keys, parse_constant=_reject_constant, ) except json.JSONDecodeError as exc: raise ValueError("raw_body 不是合法 JSON: %s" % (exc.msg,)) from exc except RecursionError as exc: raise ValueError("raw_body JSON 嵌套过深") from exc if not isinstance(payload, dict): raise ValueError("JSON 顶层必须是对象") return payload class WebhookVerifier: """支付网关退款通知校验器:HMAC-SHA256 验签 + 时间窗 + event id 重放防护。""" _H_TIMESTAMP = "x-timestamp" _H_EVENT_ID = "x-event-id" _H_SIGNATURE = "x-signature" _PRUNE_MIN = 1024 def __init__(self, secret, tolerance=300): if isinstance(secret, (bytearray, memoryview)): secret = bytes(secret) if not isinstance(secret, bytes) or len(secret) == 0: raise ValueError("secret 必须是非空 bytes") if isinstance(tolerance, bool) or not isinstance(tolerance, int) or tolerance < 0: raise ValueError("tolerance 必须是不小于 0 的整数(布尔值非法)") self._secret = bytes(secret) self._tolerance = tolerance self._lock = threading.Lock() self._seen = {} # event_id -> 成功处理时的 timestamp self._prune_at = self._PRUNE_MIN def verify(self, headers, raw_body, now): timestamp_text, timestamp, event_id, signature = self._check_identity(headers) if isinstance(now, bool) or not isinstance(now, int): raise PermissionError("now 必须是整数 Unix 秒") if isinstance(raw_body, (bytearray, memoryview)): raw_body = bytes(raw_body) if not isinstance(raw_body, bytes): raise PermissionError("raw_body 必须是收到的原始 bytes") # 先身份(签名、时间窗),再解析 JSON;顺序不可颠倒。 self._check_signature(timestamp_text, raw_body, signature) if abs(now - timestamp) > self._tolerance: raise PermissionError("时间戳超出允许的时间窗") # 检查重放、解析 JSON、写入缓存三步在同一把锁内完成, # 保证并发下同一 event id 只有一个请求能通过。 with self._lock: self._prune(now) if event_id in self._seen: raise PermissionError("重放请求:该 event id 已成功处理过") payload = _parse_json_object(raw_body) self._seen[event_id] = timestamp return payload # ------------------------------------------------------------------ 内部实现 def _check_identity(self, headers): """校验并返回 (timestamp 原文, timestamp 整数, event id, signature 原文)。""" if not isinstance(headers, dict): raise PermissionError("headers 必须是字典") found = {} for key, value in headers.items(): if not isinstance(key, str): continue lowered = key.lower() if lowered in (self._H_TIMESTAMP, self._H_EVENT_ID, self._H_SIGNATURE): if lowered in found: raise PermissionError("重复的请求头部: %s" % (key,)) if not isinstance(value, str): raise PermissionError("请求头部取值必须是字符串: %s" % (key,)) found[lowered] = value for name in (self._H_TIMESTAMP, self._H_EVENT_ID, self._H_SIGNATURE): if name not in found: raise PermissionError("缺少必需的请求头部: %s" % (name,)) timestamp_text = found[self._H_TIMESTAMP] event_id = found[self._H_EVENT_ID] signature = found[self._H_SIGNATURE] if not _TS_RE.fullmatch(timestamp_text) or len(timestamp_text) > _MAX_TS_DIGITS: raise PermissionError("X-Timestamp 必须是无符号十进制整数文本") timestamp = int(timestamp_text) if not (1 <= len(event_id) <= _MAX_EVENT_ID_LEN): raise PermissionError("X-Event-Id 必须是非空且不超过 128 字符的字符串") if not _SIG_RE.fullmatch(signature): raise PermissionError("X-Signature 必须是 sha256= 加 64 位小写十六进制") return timestamp_text, timestamp, event_id, signature def _check_signature(self, timestamp_text, raw_body, signature): message = timestamp_text.encode("ascii") + b"." + raw_body expected = ("sha256=" + hmac.new(self._secret, message, hashlib.sha256).hexdigest()).encode("ascii") if not hmac.compare_digest(expected, signature.encode("ascii")): raise PermissionError("签名校验失败") def _prune(self, now): """清理已不可能再次通过时间窗校验的缓存条目(调用方需持有锁)。""" if len(self._seen) < self._prune_at: return tolerance = self._tolerance stale = [eid for eid, ts in self._seen.items() if abs(now - ts) > tolerance] for eid in stale: del self._seen[eid] self._prune_at = max(self._PRUNE_MIN, len(self._seen) * 2) ```