fix: Mercado Pago's signed notifications verify with a pasted secret and close formats
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 2m43s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 54s
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 2m43s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 54s
Production refused every notification, all current-format (data.id, type), signed and fresh, though the event and the secret looked right. The secret is now trimmed (a space or line break pasted into the stack changes every HMAC), and a few close variants of the signed text are tried besides the documented one (without the request id, the id's own case, the id from the body); each still needs the secret. The one that matched, and whether the secret was trimmed, go to the audit log so the real format can be settled. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -47,7 +47,13 @@ class MercadoPagoPayment:
|
||||
def __init__(self, access_token=None, webhook_secret=None, notification_url=None,
|
||||
transport=None, clock=time.time):
|
||||
self.access_token = access_token or os.environ.get('MP_ACCESS_TOKEN', '')
|
||||
self.webhook_secret = (webhook_secret or os.environ.get('MP_WEBHOOK_SECRET', '')).encode()
|
||||
# Trimmed: a space or line break pasted with the secret into the stack
|
||||
# changes every HMAC, and Mercado Pago's own secret has none.
|
||||
raw_secret = webhook_secret or os.environ.get('MP_WEBHOOK_SECRET', '')
|
||||
self.webhook_secret = raw_secret.strip().encode()
|
||||
self.secret_was_trimmed = raw_secret != raw_secret.strip()
|
||||
# Which signed text matched the last notification verified (see verify).
|
||||
self.last_signature = None
|
||||
self.notification_url = notification_url or os.environ.get('MP_NOTIFICATION_URL', '')
|
||||
if not self.access_token or not self.webhook_secret:
|
||||
raise RuntimeError('Mercado Pago needs MP_ACCESS_TOKEN and MP_WEBHOOK_SECRET')
|
||||
@@ -128,6 +134,12 @@ class MercadoPagoPayment:
|
||||
# Webhooks ------------------------------------------------------------
|
||||
|
||||
def verify(self, headers: Mapping[str, str], body: bytes, query: Mapping[str, str] | None = None) -> bool:
|
||||
"""The notification is Mercado Pago's when its x-signature is the HMAC of
|
||||
the documented text (id, request-id, ts) under our secret. A few close
|
||||
variants of that text are also tried, each still needing the secret, so
|
||||
a format that differs from the documentation is accepted and named in
|
||||
self.last_signature rather than silently refused."""
|
||||
self.last_signature = None
|
||||
signature = headers.get('x-signature') or ''
|
||||
parts = dict(part.strip().split('=', 1) for part in signature.split(',') if '=' in part)
|
||||
ts, supplied = parts.get('ts', ''), parts.get('v1', '')
|
||||
@@ -135,18 +147,28 @@ class MercadoPagoPayment:
|
||||
return False
|
||||
if abs(self.clock() - int(ts[:10])) > MAX_SIGNATURE_AGE:
|
||||
return False
|
||||
data_id = (query or {}).get('data.id', '')
|
||||
if data_id.isalnum():
|
||||
data_id = data_id.lower()
|
||||
manifest = ''
|
||||
if data_id:
|
||||
manifest += f'id:{data_id};'
|
||||
request_id = headers.get('x-request-id') or ''
|
||||
if request_id:
|
||||
manifest += f'request-id:{request_id};'
|
||||
manifest += f'ts:{ts};'
|
||||
expected = hmac.new(self.webhook_secret, manifest.encode(), hashlib.sha256).hexdigest()
|
||||
return hmac.compare_digest(expected, supplied.lower())
|
||||
query_id = (query or {}).get('data.id', '')
|
||||
try:
|
||||
body_id = str(((json.loads(body) or {}).get('data') or {}).get('id') or '')
|
||||
except (ValueError, AttributeError):
|
||||
body_id = ''
|
||||
|
||||
def text(data_id, with_request=True):
|
||||
manifest = f'id:{data_id};' if data_id else ''
|
||||
if with_request and request_id:
|
||||
manifest += f'request-id:{request_id};'
|
||||
return manifest + f'ts:{ts};'
|
||||
|
||||
lowered = query_id.lower() if query_id.isalnum() else query_id
|
||||
variants = [('documentado', text(lowered)), ('sem request-id', text(lowered, False)),
|
||||
('id sem minúsculas', text(query_id)), ('id do corpo', text(body_id))]
|
||||
for name, manifest in variants:
|
||||
expected = hmac.new(self.webhook_secret, manifest.encode(), hashlib.sha256).hexdigest()
|
||||
if hmac.compare_digest(expected, supplied.lower()):
|
||||
self.last_signature = name
|
||||
return True
|
||||
return False
|
||||
|
||||
def parse(self, body: bytes, query: Mapping[str, str] | None = None) -> PaymentEvent | None:
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user