Repository navigation
feat: verify v2 webhook and callback signatures with a signing secret #17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -139,29 +139,57 @@ 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 | ||||||||||||||||||
|
|
||||||||||||||||||
| # 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") | ||||||||||||||||||
|
dnevzorov marked this conversation as resolved.
Resolved
|
||||||||||||||||||
| if secret is None: | ||||||||||||||||||
| key = self.api_key | ||||||||||||||||||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Pre-existing (not from this PR): an empty API key makes
Generated by Claude Code
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||||||||||||||||||
| 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() | ||||||||||||||||||
|
Comment on lines
+184
to
186
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Optional (non-blocking, your call): with no secret and no API key, this raises
Suggested change
Generated by Claude Code
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||||||||||||||||||
|
|
||||||||||||||||||
| 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 | ||||||||||||||||||
|
|
||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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=<timestamp>[,v1=<hex>][,v2=<hex>...]`. 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'] | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Document a bootstrap configuration before requiring the secret. For a new endpoint, Line 416 says the secret is unavailable until the handler acknowledges Show an explicit bootstrap configuration that acknowledges only
|
||
|
|
||
| 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 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Skip verified If a Add a
|
||
| 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. | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.