From 0218f119aafa3ac38895500fedaacda939949e34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Fri, 2 Oct 2026 15:43:34 -0300 Subject: [PATCH] fix: Mercado Pago's signed notifications verify with a pasted secret and close formats 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 --- app/api/payments.py | 4 ++++ app/mercadopago.py | 46 +++++++++++++++++++++++++++++---------- tests/test_mercadopago.py | 18 +++++++++++++++ 3 files changed, 56 insertions(+), 12 deletions(-) diff --git a/app/api/payments.py b/app/api/payments.py index 4eb8f76..46286be 100644 --- a/app/api/payments.py +++ b/app/api/payments.py @@ -43,6 +43,10 @@ async def webhook(request: Request): age=signature_age(request.headers.get('x-signature', ''))) raise HTTPException(403, 'Invalid signature') + if getattr(payment, 'last_signature', 'documentado') not in (None, 'documentado') or getattr(payment, 'secret_was_trimmed', False): + # Genuine, but not quite as documented: say how, so it can be settled. + audit('payment_webhook_signature', variant=payment.last_signature, + secret_trimmed=getattr(payment, 'secret_was_trimmed', False)) event = payment.parse(body, query) if event is None: # Verified, so genuinely from the provider, but not about a payment. diff --git a/app/mercadopago.py b/app/mercadopago.py index 3dd6dc6..ef2be3d 100644 --- a/app/mercadopago.py +++ b/app/mercadopago.py @@ -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: diff --git a/tests/test_mercadopago.py b/tests/test_mercadopago.py index 90f9ebf..9e92c33 100644 --- a/tests/test_mercadopago.py +++ b/tests/test_mercadopago.py @@ -62,6 +62,24 @@ class MercadoPagoTests(unittest.TestCase): 'x-request-id': 'req-1'}, b'{}', {'data.id': '123456'})) self.assertFalse(self.mp.verify({}, b'{}', {'data.id': '123456'})) + def test_a_secret_pasted_with_spaces_still_verifies(self): + mp = MercadoPagoPayment('TEST-token', SECRET + ' \n', 'https://dtf.example/api/payments/webhook', + transport=httpx.MockTransport(lambda r: httpx.Response(200)), clock=lambda: NOW) + headers = {'x-signature': signature('123456', 'req-1', NOW), 'x-request-id': 'req-1'} + self.assertTrue(mp.verify(headers, b'{}', {'data.id': '123456'})) + self.assertTrue(mp.secret_was_trimmed) + self.assertEqual(mp.last_signature, 'documentado') + + def test_close_variants_of_the_signed_text_are_named(self): + # Signed without the request id, though the header came. + headers = {'x-signature': signature('123456', None, NOW), 'x-request-id': 'req-1'} + self.assertTrue(self.mp.verify(headers, b'{}', {'data.id': '123456'})) + self.assertEqual(self.mp.last_signature, 'sem request-id') + # Still the secret's: another secret matches no variant. + forged = {'x-signature': signature('123456', None, NOW, 'other'), 'x-request-id': 'req-1'} + self.assertFalse(self.mp.verify(forged, b'{}', {'data.id': '123456'})) + self.assertIsNone(self.mp.last_signature) + def test_absent_values_are_left_out_and_alphanumeric_ids_lowercased(self): self.assertTrue(self.mp.verify({'x-signature': signature('abc123', None, NOW)}, b'{}', {'data.id': 'ABC123'}))