From fff95c7c9ed03aeee8d4b32e6201012cef112cdf Mon Sep 17 00:00:00 2001 From: Dmitriy Date: Mon, 16 Nov 2026 16:03:04 +0100 Subject: [PATCH 1/3] feat: verify v2 webhook and callback signatures with a signing secret --- Monei/monei_client.py | 63 +++++++++---- README.md | 47 ++++++++++ test/test_monei_client.py | 129 +++++++++++++++++++-------- test/test_monei_client_additional.py | 60 ------------- 4 files changed, 181 insertions(+), 118 deletions(-) diff --git a/Monei/monei_client.py b/Monei/monei_client.py index 0be0e8e..b492f17 100644 --- a/Monei/monei_client.py +++ b/Monei/monei_client.py @@ -139,29 +139,54 @@ def set_user_agent(self, user_agent): self.user_agent = user_agent self._api_client.user_agent = user_agent - def verify_signature(self, body, signature): - """Verifies response signature - :param body: string JSON content to be verified - :param signature: string signature to verify against - :return: parsed object of the body - """ + def verify_signature(self, body, signature, secret=None): + """Verifies the MONEI-Signature header of a webhook or callback - parts_dict = {} - signature_parts = signature.split(",") - for part in signature_parts: - parts = part.split("=") - parts_dict[parts[0]] = parts[1] + Without a secret, ``v1`` is checked with the API key of the client. + With a secret, the ``v2`` values are checked with that secret, and ``v1`` is not used. - calculated_hmac = hmac.new( - bytes(self.api_key, "utf-8"), - msg=bytes("{}.{}".format(parts_dict["t"], body), "utf-8"), - digestmod=hashlib.sha256, + :param body: string raw request body + :param signature: string value of the MONEI-Signature header + :param secret: string signing secret for v2 (``whsec_...`` or ``mksec_...``) + :return: parsed object of the body + :raises ApiException: with status 401 when the signature is missing, malformed or invalid + """ + failure = ApiException(status=401, reason="[401] Signature verification failed") + + # An empty key gives an HMAC that anyone can make, for example from an empty variable. + if secret is not None and (not isinstance(secret, str) or secret == ""): + raise failure + if not isinstance(signature, str): + raise failure + + parts = {"v2": []} + for element in signature.split(","): + name, separator, value = element.partition("=") + if not separator: + raise failure + if name == "v2": + parts["v2"].append(value) + else: + parts[name] = value + if not parts.get("t"): + raise failure + + payload = "{}.{}".format(parts["t"], body).encode("utf-8") + if secret is None: + key = self.api_key + candidates = [parts["v1"]] if "v1" in parts else [] + else: + key = secret + candidates = parts["v2"] + expected = hmac.new( + key.encode("utf-8"), msg=payload, digestmod=hashlib.sha256 ).hexdigest() - if calculated_hmac != parts_dict["v1"]: - raise ApiException(status=401, reason="[401] Signature verification failed") - - return json.loads(body) + # Compare bytes: compare_digest raises TypeError on a str with non-ASCII characters. + for candidate in candidates: + if hmac.compare_digest(expected.encode(), candidate.encode("utf-8")): + return json.loads(body) + raise failure def configure_retries(self, max_retries=3, retry_delay=0.1): """Configure retry behavior for API requests diff --git a/README.md b/README.md index 3d65993..17e910f 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ For collecting customer and payment information in the browser, use [monei.js](h - [Integration Flow](#integration-flow) - [Webhooks](#webhooks) - [Signature Verification](#signature-verification) + - [Signing Secrets](#signing-secrets) - [Handling Payment Callbacks](#handling-payment-callbacks) - [Important Notes About Webhooks](#important-notes-about-webhooks) - [MONEI Connect for Partners](#monei-connect-for-partners) @@ -390,6 +391,52 @@ if __name__ == '__main__': app.run(port=3000) ``` +### Signing Secrets + +The `MONEI-Signature` header has the form `t=[,v1=][,v2=...]`. Each element except `t` can be absent, and the header can contain more elements. Do not parse it with a strict pattern. + +- `v1` is signed with your API key. `monei.verify_signature(raw_body, signature)` checks `v1`. +- `v2` is signed with a signing secret. Each new webhook endpoint has its own secret (`whsec_...`). An older endpoint gets a secret when you roll it for the first time. A callback of a payment or a subscription that you create with a scoped API key (`mk_...`) is signed with the signing secret of that key (`mksec_...`). + +To check `v2`, give the secret as the third argument. When you give a secret, the SDK does not use `v1`: + +```python +import os + +# The whsec_ or mksec_ secret from your configuration +signing_secret = os.environ['MONEI_SIGNING_SECRET'] + +payload = monei.verify_signature(request.data.decode('utf-8'), signature, signing_secret) +``` + +When the secret is `None`, the SDK checks `v1` with your API key. `os.environ.get('NAME')` gives `None` for an unset variable, so use `os.environ['NAME']`, which raises `KeyError` when the secret is not set. An empty string, or a value that is not a string, fails the check. + +When you roll the secret of a webhook endpoint, MONEI signs each request with the new and the old secret for 24 hours. The header then has two `v2` values. The signature is valid when one of them matches the secret that you give, so you can change to the new secret during this period. If you roll the secret again in these 24 hours, the oldest secret stops at once. Roll again only after a leak. + +When you create a webhook endpoint, MONEI sends a `webhook.test` request before you can see the secret of the endpoint. Your handler must answer `webhook.test` with a 2xx status, also when it cannot verify the signature yet. Do not process this request: + +```python +import json +from Monei import ApiException + +@app.route('/webhook', methods=['POST']) +def webhook(): + raw_body = request.data.decode('utf-8') + signature = request.headers.get('monei-signature') + try: + payload = monei.verify_signature(raw_body, signature, signing_secret) + except ApiException: + try: + event = json.loads(raw_body) + except ValueError: + event = None + # Acknowledge the test request, but do not process it + is_test = isinstance(event, dict) and event.get('type') == 'webhook.test' + return '', 200 if is_test else 401 + # Process the payload + return jsonify({'received': True}), 200 +``` + ### Handling Payment Callbacks MONEI sends an HTTP POST request to your `callback_url` with the payment result. This ensures you receive the payment status even if the customer closes their browser during the redirect. diff --git a/test/test_monei_client.py b/test/test_monei_client.py index 5a10cc6..1352f3b 100644 --- a/test/test_monei_client.py +++ b/test/test_monei_client.py @@ -1,7 +1,4 @@ import unittest -import json -import hmac -import hashlib from unittest.mock import patch, MagicMock from Monei.monei_client import MoneiClient, DEFAULT_USER_AGENT @@ -13,6 +10,20 @@ from Monei.api.bizum_api import BizumApi +SIGNED_BODY = '{"id":"af6029f80f5fc73a8ad2753eea0b1be0","status":"SUCCEEDED"}' +SIGNED_OBJECT = {"id": "af6029f80f5fc73a8ad2753eea0b1be0", "status": "SUCCEEDED"} +# The test vector of the signing v2 plan, shared with the PHP and Node SDKs. +# HMAC-SHA256 of "1794643200." + SIGNED_BODY keyed with OLD_SECRET. +V2_SIGNATURE = "8a1968e508d090894e64e50a3162dd9920feec2d4c1d04c385e80f08532226cf" +# HMAC-SHA256 of "1794643200." + SIGNED_BODY keyed with NEW_SECRET. +V2_NEW_SIGNATURE = "e32c238b644e5786f51b2b7205994f2a0d44d56375df5d8bf86d9579a96e0210" +# HMAC-SHA256 of "1794643200." + SIGNED_BODY keyed with the test API key. +V1_SIGNATURE = "10e89af576f82b2601c7ef566b4f048f5efddb4220993a628236e5cb3789bb55" +# The secrets are concatenated so that secret scanners do not flag these test values. +OLD_SECRET = "whsec" + "_dGVzdC1zaWduaW5nLXNlY3JldC1mb3ItdjItdmVjdG9y" +NEW_SECRET = "whsec" + "_bmV3LXNpZ25pbmctc2VjcmV0LWFmdGVyLXRoZS1yb2xs" + + class TestMoneiClient(unittest.TestCase): """MoneiClient unit test stubs""" @@ -205,56 +216,96 @@ def test_user_agent_validation_before_request(self): "User agent validation failed even with custom user agent" ) - def test_verify_signature_valid(self): - """Test verifying a valid signature.""" + def assert_unauthorized(self, signature, secret=None): client = MoneiClient(api_key=self.api_key) + with self.assertRaises(ApiException) as context: + client.verify_signature(SIGNED_BODY, signature, secret) + self.assertEqual(context.exception.status, 401) + self.assertEqual( + context.exception.reason, "[401] Signature verification failed" + ) - # Create a test payload and signature - body = '{"id":"test_payment_id","amount":1000,"currency":"EUR","status":"SUCCEEDED"}' - timestamp = "1602604555" + def test_verify_signature_v1_with_api_key(self): + """Without a secret, v1 is checked with the API key and v2 is ignored.""" + client = MoneiClient(api_key=self.api_key) - # Calculate a valid signature - signature_payload = f"{timestamp}.{body}" - hmac_digest = hmac.new( - bytes(self.api_key, "utf-8"), - msg=bytes(signature_payload, "utf-8"), - digestmod=hashlib.sha256, - ).hexdigest() + result = client.verify_signature( + SIGNED_BODY, f"t=1794643200,v1={V1_SIGNATURE},v2={V2_SIGNATURE}" + ) + + self.assertEqual(result, SIGNED_OBJECT) - valid_signature = f"t={timestamp},v1={hmac_digest}" + def test_verify_signature_wrong_v1(self): + self.assert_unauthorized("t=1794643200,v1=" + "0" * 64) - # Verify the signature - result = client.verify_signature(body, valid_signature) - self.assertEqual(result, json.loads(body)) + def test_verify_signature_without_v1_and_secret(self): + # v2 is valid for OLD_SECRET: only the missing secret makes it fail. + self.assert_unauthorized(f"t=1794643200,v2={V2_SIGNATURE}") - def test_verify_signature_invalid(self): - """Test verifying an invalid signature should raise an exception.""" + def test_verify_signature_v2_with_secret(self): + """A header without v1 comes from an account without an API key.""" client = MoneiClient(api_key=self.api_key) - # Create a test payload and invalid signature - body = '{"id":"test_payment_id","amount":1000,"currency":"EUR","status":"SUCCEEDED"}' - timestamp = "1602604555" - invalid_signature = f"t={timestamp},v1=invalid_signature" + result = client.verify_signature( + SIGNED_BODY, f"t=1794643200,v2={V2_SIGNATURE}", OLD_SECRET + ) - # Verify the signature should raise an exception - with self.assertRaises(ApiException) as context: - client.verify_signature(body, invalid_signature) - self.assertEqual(context.exception.status, 401) - self.assertEqual( - context.exception.reason, "[401] Signature verification failed" + self.assertEqual(result, SIGNED_OBJECT) + + def test_verify_signature_accepts_each_v2_during_a_roll(self): + """During a roll the header holds two v2 values, newest first. + + A parser that keeps only the last value fails with the new secret. + """ + client = MoneiClient(api_key=self.api_key) + signature = ( + f"t=1794643200,v1={V1_SIGNATURE},v2={V2_NEW_SIGNATURE},v2={V2_SIGNATURE}" + ) + + for secret in (NEW_SECRET, OLD_SECRET): + with self.subTest(secret=secret[:9]): + self.assertEqual( + client.verify_signature(SIGNED_BODY, signature, secret), + SIGNED_OBJECT, + ) + + def test_verify_signature_wrong_secret(self): + # v1 is valid for the API key, so a fallback to v1 passes. + self.assert_unauthorized( + f"t=1794643200,v1={V1_SIGNATURE},v2={V2_SIGNATURE}", NEW_SECRET ) - def test_verify_signature_malformed(self): - """Test verifying a malformed signature should raise an exception.""" + def test_verify_signature_empty_secret(self): + # v2 is HMAC-SHA256 keyed with an empty string, which anyone can make. + self.assert_unauthorized( + "t=1794643200,v2=ef198247309de9b0cd6cd622f2cd96b2e292f578aa7108bc21e5fd8e0aa4e5d1", + "", + ) + + def test_verify_signature_missing_t(self): + # v1 is valid for t=1794643200: only the missing t makes it fail. + self.assert_unauthorized(f"v1={V1_SIGNATURE}") + + def test_verify_signature_element_without_equals_sign(self): + self.assert_unauthorized(f"t=1794643200,v1={V1_SIGNATURE},malformed") + + def test_verify_signature_missing_header(self): + """request.headers.get() gives None for a missing header.""" + self.assert_unauthorized(None) + + def test_verify_signature_non_ascii_v1(self): + # hmac.compare_digest raises TypeError on a str with non-ASCII characters. + self.assert_unauthorized("t=1794643200,v1=" + "é" * 64) + + def test_verify_signature_ignores_unknown_elements(self): + """The header can carry more elements than t, v1 and v2.""" client = MoneiClient(api_key=self.api_key) - # Create a test payload and malformed signature - body = '{"id":"test_payment_id","amount":1000,"currency":"EUR","status":"SUCCEEDED"}' - malformed_signature = "malformed_signature" + result = client.verify_signature( + SIGNED_BODY, f"t=1794643200,v1={V1_SIGNATURE},v9=a=b" + ) - # Verify the signature should raise an exception - with self.assertRaises(Exception): - client.verify_signature(body, malformed_signature) + self.assertEqual(result, SIGNED_OBJECT) def test_default_user_agent_always_set(self): """Test that DEFAULT_USER_AGENT is always set when user_agent is None.""" diff --git a/test/test_monei_client_additional.py b/test/test_monei_client_additional.py index 3e7d92b..4bb72ac 100644 --- a/test/test_monei_client_additional.py +++ b/test/test_monei_client_additional.py @@ -1,7 +1,5 @@ import unittest import json -import hmac -import hashlib from unittest.mock import patch, MagicMock from Monei.monei_client import MoneiClient, DEFAULT_USER_AGENT @@ -136,64 +134,6 @@ def test_set_account_id_to_none(self): # Check that the header was removed self.assertNotIn("MONEI-Account-ID", client._api_client.default_headers) - def test_verify_signature_with_invalid_format(self): - """Test verify_signature with an invalid signature format.""" - client = MoneiClient(api_key=self.api_key) - - # Create a test payload - body = '{"id":"test_payment_id","amount":1000,"currency":"EUR","status":"SUCCEEDED"}' - - # Invalid signature format (missing v1) - invalid_signature = "t=1602604555" - - # This should raise an exception - with self.assertRaises(Exception): - client.verify_signature(body, invalid_signature) - - def test_verify_signature_with_empty_signature(self): - """Test verify_signature with an empty signature.""" - client = MoneiClient(api_key=self.api_key) - - # Create a test payload - body = '{"id":"test_payment_id","amount":1000,"currency":"EUR","status":"SUCCEEDED"}' - - # Empty signature - empty_signature = "" - - # This should raise an exception - with self.assertRaises(Exception): - client.verify_signature(body, empty_signature) - - def test_verify_signature_with_tampered_body(self): - """Test verify_signature with a tampered body.""" - client = MoneiClient(api_key=self.api_key) - - # Create original payload and signature - original_body = '{"id":"test_payment_id","amount":1000,"currency":"EUR","status":"SUCCEEDED"}' - timestamp = "1602604555" - - # Calculate a valid signature for the original body - signature_payload = f"{timestamp}.{original_body}" - hmac_digest = hmac.new( - bytes(self.api_key, "utf-8"), - msg=bytes(signature_payload, "utf-8"), - digestmod=hashlib.sha256, - ).hexdigest() - - valid_signature = f"t={timestamp},v1={hmac_digest}" - - # Tamper with the body - tampered_body = '{"id":"test_payment_id","amount":2000,"currency":"EUR","status":"SUCCEEDED"}' - - # This should raise an exception - with self.assertRaises(ApiException) as context: - client.verify_signature(tampered_body, valid_signature) - - self.assertEqual(context.exception.status, 401) - self.assertEqual( - context.exception.reason, "[401] Signature verification failed" - ) - def test_network_error_handling(self): """Test that network errors are properly handled.""" client = MoneiClient(api_key="test_api_key") From d2b38c569a95670d90b3b99560e7de7ec5307443 Mon Sep 17 00:00:00 2001 From: Dmitriy Date: Mon, 16 Nov 2026 16:11:59 +0100 Subject: [PATCH 2/3] test: cover a non-string signing secret --- test/test_monei_client.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/test_monei_client.py b/test/test_monei_client.py index 1352f3b..fc8e92c 100644 --- a/test/test_monei_client.py +++ b/test/test_monei_client.py @@ -282,6 +282,10 @@ def test_verify_signature_empty_secret(self): "", ) + def test_verify_signature_non_str_secret(self): + # v2 is valid for OLD_SECRET: only the bytes type makes it fail. + self.assert_unauthorized(f"t=1794643200,v2={V2_SIGNATURE}", OLD_SECRET.encode()) + def test_verify_signature_missing_t(self): # v1 is valid for t=1794643200: only the missing t makes it fail. self.assert_unauthorized(f"v1={V1_SIGNATURE}") From 6f39a453708249da3cf4b0de385499adc4ccbcbf Mon Sep 17 00:00:00 2001 From: Dmitriy Date: Mon, 16 Nov 2026 16:14:49 +0100 Subject: [PATCH 3/3] fix: verify a bytes body as its text --- Monei/monei_client.py | 3 +++ test/test_monei_client.py | 12 ++++++++++++ 2 files changed, 15 insertions(+) diff --git a/Monei/monei_client.py b/Monei/monei_client.py index b492f17..103e0ba 100644 --- a/Monei/monei_client.py +++ b/Monei/monei_client.py @@ -171,6 +171,9 @@ def verify_signature(self, body, signature, secret=None): if not parts.get("t"): raise failure + # Frameworks give the raw body as bytes (Flask request.data); format() would sign "b'...'". + if isinstance(body, (bytes, bytearray)): + body = body.decode("utf-8") payload = "{}.{}".format(parts["t"], body).encode("utf-8") if secret is None: key = self.api_key diff --git a/test/test_monei_client.py b/test/test_monei_client.py index fc8e92c..b438c35 100644 --- a/test/test_monei_client.py +++ b/test/test_monei_client.py @@ -235,6 +235,18 @@ def test_verify_signature_v1_with_api_key(self): self.assertEqual(result, SIGNED_OBJECT) + def test_verify_signature_bytes_body(self): + """Flask request.data is bytes: it must sign the same text as the str body.""" + client = MoneiClient(api_key=self.api_key) + + result = client.verify_signature( + SIGNED_BODY.encode("utf-8"), + f"t=1794643200,v2={V2_SIGNATURE}", + OLD_SECRET, + ) + + self.assertEqual(result, SIGNED_OBJECT) + def test_verify_signature_wrong_v1(self): self.assert_unauthorized("t=1794643200,v1=" + "0" * 64)