diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ceff9f..ba34f67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ All notable changes to this project. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) with [Semantic Versioning](https://semver.org/). +## [Unreleased] + +### Security + +- `parse_response()` verifies the signature before it validates the fields. Before the check it reads at most 128 KiB of `Ds_MerchantParameters` and 128 characters of `Ds_Signature`, and rejects JSON nested deeper than 32 levels. Before, an unsigned payload posted to the notification URL reached field validation (an amount such as `1E99999999` raised `decimal.Overflow`), deeply nested JSON could exhaust a small thread stack and crash the process (Python 3.12 and 3.13 with a 1 MiB thread stack), and `Ds_Signature` was normalized whatever its length. + +### Fixed + +- `parse_response()` raises `redsys.exceptions.ValidationError`, a `ValueError`, for any payload that is not a well-formed RedSys result: not a mapping, neither `Ds_MerchantParameters` nor an error code, no `Ds_Signature`, an unsupported `Ds_SignatureVersion`, a `Ds_MerchantParameters` that is not a Base64-encoded JSON object, or a signed field the model rejects. Before, these raised `KeyError`, `TypeError`, `AttributeError`, `RecursionError`, `decimal.Overflow`, `pydantic.ValidationError` or, for a payload with neither field, a `ResponseError` without a code. A signature mismatch still raises `ValueError`. The received fields may come in any mapping (a `dict` or a framework's form data), as `str`, `bytes` or `bytearray`. +- `send()` raises `ValidationError` for an answer that is not JSON, instead of `json.JSONDecodeError`. + ## [2.2.0] - 2026-11-07 ### Added diff --git a/README.md b/README.md index 1e4bef8..fd1ad42 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,7 @@ Fields are validated when the operation method is called, before anything is sig | A field with the wrong type or format, a missing required field, a misspelled or 1.x field name, an unknown currency or transaction type | `pydantic.ValidationError`; `.errors()` lists each field | | A transaction type that contradicts the operation or the redirect connection, a non-HTTPS `endpoint`, an invalid API key or environment | `redsys.exceptions.ValidationError` | | A signature that does not match in `parse_response()` | `ValueError` | +| A payload in `parse_response()` or an answer in `send()` that is not a well-formed RedSys result, for example without a signature or not a Base64-encoded JSON object | `redsys.exceptions.ValidationError` | | RedSys answers with an error code instead of a signed result | `redsys.exceptions.ResponseError`; `.error_code` holds the `SISnnnn` code | | An HTTP error status from RedSys in `send()` | `httpx.HTTPStatusError` | diff --git a/docs/direct-connection.md b/docs/direct-connection.md index 7980a63..cf6494f 100644 --- a/docs/direct-connection.md +++ b/docs/direct-connection.md @@ -156,6 +156,7 @@ The answer is verified and parsed like the redirect notification. Besides the fi | RedSys answers `errorCode` instead of a signed result | `ResponseError`; `.error_code` holds the `SISnnnn` code, plus `http_status`, `http_headers` and `raw_body` after `send()` | | RedSys answers an HTTP error status | `httpx.HTTPStatusError` | | The signature of the answer does not match | `ValueError` | +| The answer is not a well-formed RedSys result, for example not JSON; every case is listed under [Response](redirect-connection.md#response) in the redirect reference | `redsys.exceptions.ValidationError` | `redsys.codes.describe(error.error_code, "en")` gives the meaning of any `SISnnnn` code; [`response-codes.md`](response-codes.md) lists `Ds_Response` and Bizum codes. Common ones in direct integrations: diff --git a/docs/redirect-connection.md b/docs/redirect-connection.md index fac65de..040ee0c 100644 --- a/docs/redirect-connection.md +++ b/docs/redirect-connection.md @@ -102,7 +102,7 @@ Response signatures arrive in URL-safe Base64; verification normalizes both side ## Response -RedSys returns the result in the same three-field envelope, both as a server-to-server POST to `Ds_Merchant_MerchantURL` and through the browser redirect. `client.parse_response(fields)` decodes `Ds_MerchantParameters`, recomputes the signature with the key derived from `Ds_Order`, compares it with `Ds_Signature` and returns a `Response`. A mismatch raises `ValueError`: the fields did not come from RedSys or were altered. +RedSys returns the result in the same three-field envelope, both as a server-to-server POST to `Ds_Merchant_MerchantURL` and through the browser redirect. `client.parse_response(fields)` decodes `Ds_MerchantParameters`, recomputes the signature with the key derived from `Ds_Order`, compares it with `Ds_Signature` and only then validates the fields into a `Response`. A mismatch raises `ValueError`: the fields did not come from RedSys or were altered. A payload that is not a well-formed result raises `redsys.exceptions.ValidationError`, also a `ValueError`: not a mapping, neither `Ds_MerchantParameters` nor an error code, no `Ds_Signature` or one over 128 characters, an unsupported `Ds_SignatureVersion`, a `Ds_MerchantParameters` over 128 KiB or that is not a Base64-encoded JSON object nested at most 32 levels (all checked before the signature), or a signed field the model rejects. An error code without `Ds_MerchantParameters` raises `ResponseError`; it carries no signature, so it does not prove that RedSys sent it. ## Response parameters diff --git a/redsys/clients.py b/redsys/clients.py index 093b384..98f53be 100644 --- a/redsys/clients.py +++ b/redsys/clients.py @@ -11,6 +11,7 @@ """ from base64 import b64decode +from collections.abc import Mapping from hmac import compare_digest from importlib.metadata import PackageNotFoundError, version from logging import getLogger @@ -18,6 +19,8 @@ from urllib.parse import urlsplit from warnings import warn +from pydantic import ValidationError as PydanticValidationError + from redsys import threeds from redsys.api import environments, transactions from redsys.crypto import ( @@ -39,6 +42,7 @@ RedirectPreauthorizationMessage, RefundMessage, Response, + decode_merchant_parameters, ) from redsys.request import ( MERCHANT_PARAMETERS, @@ -63,6 +67,12 @@ def _default_module() -> str: # Seconds; ``send(timeout=...)`` overrides it. DEFAULT_TIMEOUT = 30 +# Real payloads take a few KiB; the caps bound the work done before the signature is checked. +_MAX_MERCHANT_PARAMETERS_LENGTH = 128 * 1024 +_MAX_SIGNATURE_LENGTH = 128 + +_ORDER_WIRE_NAME = Response.model_fields['order'].alias + __all__ = [ 'Client', 'RedirectClient', @@ -93,6 +103,19 @@ def _normalize_signature(signature) -> str: return sub(r'[^a-zA-Z0-9]', '', signature) +def _base64_text(value, name: str, max_length: int) -> bytes: + """A received Base64 field as bytes; Base64 is ASCII, so anything else is malformed.""" + if isinstance(value, (str, bytes, bytearray)) and len(value) > max_length: + raise ValidationError(f'{name} exceeds {max_length} characters.') + if isinstance(value, str) and value.isascii(): + value = value.encode('ascii') + elif isinstance(value, bytearray): + value = bytes(value) + if not isinstance(value, bytes) or not value.isascii(): + raise ValidationError(f'{name} is missing or is not Base64 text.') + return value + + def _resolve_environment(environment: str | None, sandbox: bool | None) -> str: """The environment a client targets; ``sandbox`` means TEST when true and PROD when false.""" implied = None if sandbox is None else environments.TEST if sandbox else environments.PROD @@ -247,27 +270,50 @@ def _build_request( return Request(merchant_parameters, signature, version, sender=sender, endpoint=endpoint) # == Response parsing == - def parse_response(self, payload: dict) -> Response: + def parse_response(self, payload: Mapping) -> Response: """Verify the signature and parse a received payload into a ``Response``. Accepts both the redirect callback form fields and the direct REST JSON - body. Raises ``ValueError`` if the signature does not match (the payload - is not from RedSys or was tampered with), or ``ResponseError`` if RedSys - answered with an error code instead of a signed result. + body. Fields are validated only after the signature matches. Raises + ``ResponseError`` if RedSys answered with an error code instead of a + signed result, ``ValidationError`` if the payload is not a well-formed + RedSys result, and ``ValueError`` if the signature does not match (the + payload is not from RedSys or was tampered with). """ + if not isinstance(payload, Mapping): + raise ValidationError('The payload must be a mapping of the received fields.') if MERCHANT_PARAMETERS not in payload: error_code = payload.get('errorCode') or payload.get('Ds_ErrorCode') + if not error_code: + raise ValidationError(f'The payload carries neither {MERCHANT_PARAMETERS} nor an error code.') raise ResponseError(error_code, payload) - merchant_parameters = payload[MERCHANT_PARAMETERS] - if isinstance(merchant_parameters, str): - merchant_parameters = merchant_parameters.encode('utf-8') + merchant_parameters = _base64_text( + payload[MERCHANT_PARAMETERS], MERCHANT_PARAMETERS, _MAX_MERCHANT_PARAMETERS_LENGTH + ) + signature = _base64_text(payload.get(SIGNATURE), SIGNATURE, _MAX_SIGNATURE_LENGTH) version = payload.get(SIGNATURE_VERSION, DEFAULT_SIGNATURE_VERSION) - response = Response.from_merchant_parameters(merchant_parameters) + if version not in SIGNATURE_VERSIONS: + raise ValidationError(f'{SIGNATURE_VERSION} is not supported.') + try: + fields = decode_merchant_parameters(merchant_parameters) + except ValueError as error: + raise ValidationError(f'{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object: {error}') from error + if not isinstance(fields, dict): + raise ValidationError(f'{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object.') # A signed result always carries Ds_Order; without it, '' makes verification fail. - expected = get_signer(self._secret_key, version).sign(response.get_order() or '', merchant_parameters) - if not compare_digest(_normalize_signature(payload[SIGNATURE]), _normalize_signature(expected)): + order = fields.get(_ORDER_WIRE_NAME) + try: + expected = get_signer(self._secret_key, version).sign( + order if isinstance(order, str) else '', merchant_parameters + ) + except UnicodeEncodeError as error: + raise ValidationError(f'{_ORDER_WIRE_NAME} is not valid text.') from error + if not compare_digest(_normalize_signature(signature), _normalize_signature(expected)): raise ValueError('Signature is not valid.') - return response + try: + return Response._from_fields(fields) + except (PydanticValidationError, ArithmeticError) as error: + raise ValidationError(f'{MERCHANT_PARAMETERS} holds a field that is not valid.') from error class RedirectClient(Client): @@ -430,7 +476,11 @@ def _parse_http_response(self, http_response) -> Response: http_response.raise_for_status() transport = (http_response.status_code, dict(http_response.headers), http_response.text) try: - response = self.parse_response(http_response.json()) + body = http_response.json() + except ValueError as error: + raise ValidationError('The answer is not JSON.') from error + try: + response = self.parse_response(body) except ResponseError as error: error.http_status, error.http_headers, error.raw_body = transport raise diff --git a/redsys/exceptions.py b/redsys/exceptions.py index 48e2617..55f6154 100644 --- a/redsys/exceptions.py +++ b/redsys/exceptions.py @@ -15,7 +15,7 @@ def __init__(self, error_code, payload=None): class ValidationError(RedsysError, ValueError): - """A client option or an operation's fields contradict each other or what RedSys accepts.""" + """Rejected input: a client option or operation fields RedSys does not accept, or a malformed received payload.""" class UnknownParameterWarning(UserWarning): diff --git a/redsys/models.py b/redsys/models.py index bf38fcd..c7a988e 100644 --- a/redsys/models.py +++ b/redsys/models.py @@ -20,7 +20,9 @@ from base64 import b64decode, b64encode from decimal import Decimal +from itertools import accumulate from json import dumps, loads +from operator import sub as subtract from typing import Any from warnings import warn @@ -48,13 +50,35 @@ } +# RedSys payloads nest two or three levels; deeper JSON can exhaust a small thread +# stack inside the C JSON decoder and kill the process. +_MAX_JSON_DEPTH = 32 +_NOT_BRACKETS = bytes(sorted(set(range(256)) - set(b'[]{}'))) +_BRACKET_WEIGHTS = bytes.maketrans(b'[{]}', b'\x02\x02\x00\x00') + + +def _json_depth_exceeds(text: bytes, limit: int) -> bool: + """Whether JSON text nests deeper than ``limit``; brackets inside strings do not count.""" + if text.count(b'[') + text.count(b'{') <= limit: + return False + # Bytes operations only: the text may be attacker-sized, and a byte loop costs ten times more. + outside_strings = b''.join(text.replace(b'\\\\', b'').replace(b'\\"', b'').split(b'"')[::2]) + # Opening brackets weigh 2 and closing ones 0: the running sum minus the position is the depth. + weights = outside_strings.translate(_BRACKET_WEIGHTS, _NOT_BRACKETS) + return max(map(subtract, accumulate(weights), range(1, len(weights) + 1)), default=0) > limit + + def decode_merchant_parameters(data: bytes) -> dict: """Decode a Ds_MerchantParameters string in standard or URL-safe Base64, padded or not. RedSys mixes the forms by signature version (HMAC_SHA512_V2 responses come unpadded). + JSON nested deeper than any RedSys payload raises ``ValueError`` before it is parsed. """ data = data.replace(b'-', b'+').replace(b'_', b'/') - return loads(b64decode(data + b'=' * (-len(data) % 4)).decode('utf-8')) + text = b64decode(data + b'=' * (-len(data) % 4)) + if _json_depth_exceeds(text, _MAX_JSON_DEPTH): + raise ValueError(f'JSON nests deeper than {_MAX_JSON_DEPTH} levels.') + return loads(text.decode('utf-8')) def currency_decimals(currency: int | None) -> int: @@ -487,12 +511,16 @@ class Response(BaseModel): @classmethod def _blank_amount_to_none(cls, value): # Keep the raw integer minor units here; scaling needs the currency and - # is applied in from_merchant_parameters. + # is applied in _from_fields. return None if value in (None, '') else value @classmethod def from_merchant_parameters(cls, merchant_parameters: bytes) -> 'Response': - response = cls.model_validate(decode_merchant_parameters(merchant_parameters)) + return cls._from_fields(decode_merchant_parameters(merchant_parameters)) + + @classmethod + def _from_fields(cls, fields: dict) -> 'Response': + response = cls.model_validate(fields) if response.amount is not None: # scaleb keeps the currency's decimals: 100 EUR minor units read as 1.00, not 1. response.amount = response.amount.scaleb(-currency_decimals(response.currency)) diff --git a/tests/test_parse_response.py b/tests/test_parse_response.py new file mode 100644 index 0000000..f8e72a5 --- /dev/null +++ b/tests/test_parse_response.py @@ -0,0 +1,187 @@ +import os +import sys +from base64 import b64encode +from decimal import Decimal +from json import dumps, loads +from types import MappingProxyType +from unittest import mock + +import httpx +import pytest +from pydantic import ValidationError as PydanticValidationError + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from redsys import clients +from redsys.clients import MERCHANT_PARAMETERS, SIGNATURE, SIGNATURE_VERSION, DirectClient, RedirectClient +from redsys.crypto import HMAC_SHA256_V1, HMAC_SHA512_V2, get_signer +from redsys.exceptions import ResponseError, ValidationError +from redsys.models import _MAX_JSON_DEPTH, Response, _json_depth_exceeds + +SECRET = 'sq7HjrUOBfKmC576ILgskD5srU870gJ7' +ORDER = '000000001' + + +def _client(): + return RedirectClient(SECRET, merchant_code='999008881', terminal=1, sandbox=True) + + +def _encoded(raw: bytes) -> str: + return b64encode(raw).decode('ascii') + + +def _payload(merchant_parameters, signature='x', version=HMAC_SHA512_V2) -> dict: + return {SIGNATURE_VERSION: version, MERCHANT_PARAMETERS: merchant_parameters, SIGNATURE: signature} + + +def _signed(fields: dict, order: str = ORDER, version: str = HMAC_SHA256_V1) -> dict: + merchant_parameters = b64encode(dumps(fields).encode('utf-8')) + signature = get_signer(SECRET, version).sign(order, merchant_parameters) + return _payload(merchant_parameters.decode('ascii'), signature.decode('ascii'), version) + + +def _nested(depth: int): + value: list = [] + for _ in range(depth - 1): + value = [value] + return value + + +_UNSIGNED_FIELDS = _encoded(b'{"Ds_Order": "000000001", "Ds_Response": "0000"}') + +MALFORMED = { + 'not a mapping': [MERCHANT_PARAMETERS], + 'neither parameters nor error code': {}, + 'no signature': {MERCHANT_PARAMETERS: _UNSIGNED_FIELDS}, + 'signature not text': _payload(_UNSIGNED_FIELDS, signature=7), + 'signature too long': _payload(_UNSIGNED_FIELDS, signature='A' * 129), + 'parameters not text': _payload(7), + 'parameters not ascii': _payload('\ud800' + _UNSIGNED_FIELDS), + 'unsupported version': _payload(_UNSIGNED_FIELDS, version='HMAC_MD5_V0'), + 'not base64 json': _payload('AAAA'), + 'not utf-8': _payload(_encoded(b'\xff\xfe')), + 'json array': _payload(_encoded(b'[1, 2]')), + 'order not encodable': _payload(_encoded(b'{"Ds_Order": "\\ud800"}')), + 'nested too deep': _payload(_encoded(dumps({'Ds_Order': ORDER, 'x': _nested(_MAX_JSON_DEPTH)}).encode())), +} + + +@pytest.mark.parametrize('payload', MALFORMED.values(), ids=MALFORMED.keys()) +def test_malformed_payload_raises_validation_error(payload): + with pytest.raises(ValidationError): + _client().parse_response(payload) + + +def test_validation_error_is_a_value_error(): + with pytest.raises(ValueError): + _client().parse_response(_payload('AAAA')) + + +def test_error_payload_still_raises_response_error(): + with pytest.raises(ResponseError): + _client().parse_response({'Ds_ErrorCode': 'SIS0042'}) + + +def test_oversized_parameters_are_rejected_before_decoding(): + payload = _signed({'Ds_Order': ORDER, 'Ds_Response': '0000'}) + with ( + mock.patch.object(clients, '_MAX_MERCHANT_PARAMETERS_LENGTH', len(payload[MERCHANT_PARAMETERS]) - 1), + mock.patch.object(clients, 'decode_merchant_parameters') as decode, + pytest.raises(ValidationError, match='exceeds'), + ): + _client().parse_response(payload) + decode.assert_not_called() + + +def test_parameters_at_the_limit_are_accepted(): + payload = _signed({'Ds_Order': ORDER, 'Ds_Response': '0000'}) + with mock.patch.object(clients, '_MAX_MERCHANT_PARAMETERS_LENGTH', len(payload[MERCHANT_PARAMETERS])): + assert _client().parse_response(payload).is_paid() + + +def test_deep_nesting_is_rejected_before_parsing(): + with ( + mock.patch('redsys.models.loads') as parse, + pytest.raises(ValidationError, match='nests deeper'), + ): + _client().parse_response(MALFORMED['nested too deep']) + parse.assert_not_called() + + +def test_nesting_at_the_limit_is_accepted(): + fields = {'Ds_Order': ORDER, 'Ds_Response': '0000', 'x': _nested(_MAX_JSON_DEPTH - 1)} + assert _client().parse_response(_signed(fields)).is_paid() + + +@pytest.mark.parametrize( + 'text', + [ + '{"a": "[[[[", "b": [1, {"c": "]]]]"}]}', + '{"a": "x\\"[[", "b": "\\\\", "c": [[]], "d": "\\\\\\"]]"}', + '{"Ds_MerchantData": "{\\"cart\\":[{\\"x\\":[1]}]}", "Ds_EMV3DS": {"a": [{"b": 1}]}}', + '[' * 40 + ']' * 40, + '{"a": "' + ']' * 40 + '", "b": ' + '[' * 30 + ']' * 30 + '}', + ], +) +def test_depth_ignores_brackets_inside_strings(text): + def depth(value): + children = value.values() if isinstance(value, dict) else value if isinstance(value, list) else () + return 1 + max(map(depth, children), default=0) if isinstance(value, (dict, list)) else 0 + + actual = depth(loads(text)) + padded = ('[' + text + ',' + ','.join(['[]'] * 40) + ']').encode() + assert _json_depth_exceeds(padded, actual + 1) is False + assert _json_depth_exceeds(padded, actual) is True + + +@pytest.mark.parametrize('amount', ['1E99999999', 'not a number']) +def test_fields_are_not_validated_without_a_matching_signature(amount): + payload = _payload(_encoded(dumps({'Ds_Order': ORDER, 'Ds_Amount': amount}).encode('utf-8'))) + with ( + mock.patch.object(Response, 'model_validate') as validate, + pytest.raises(ValueError, match='Signature is not valid'), + ): + _client().parse_response(payload) + validate.assert_not_called() + + +def test_missing_order_fails_verification(): + with pytest.raises(ValueError, match='Signature is not valid'): + _client().parse_response(_signed({'Ds_Response': '0000'})) + + +def test_signed_invalid_field_raises_validation_error_with_the_cause(): + with pytest.raises(ValidationError) as raised: + _client().parse_response(_signed({'Ds_Order': ORDER, 'Ds_Amount': 'not a number'})) + assert isinstance(raised.value.__cause__, PydanticValidationError) + + +def test_signed_amount_out_of_range_raises_validation_error(): + with pytest.raises(ValidationError): + _client().parse_response(_signed({'Ds_Order': ORDER, 'Ds_Amount': '1E99999999'})) + + +def test_well_formed_signed_payload_parses(): + response = _client().parse_response(_signed({'Ds_Order': ORDER, 'Ds_Response': '0000', 'Ds_Amount': '1056'})) + assert response.is_paid() + assert response.amount == Decimal('10.56') + + +@pytest.mark.parametrize('kind', [bytes, bytearray]) +def test_binary_fields_are_accepted(kind): + payload = _signed({'Ds_Order': ORDER, 'Ds_Response': '0000'}) + payload[MERCHANT_PARAMETERS] = kind(payload[MERCHANT_PARAMETERS].encode()) + payload[SIGNATURE] = kind(payload[SIGNATURE].encode()) + assert _client().parse_response(payload).is_paid() + + +def test_any_mapping_is_accepted(): + assert _client().parse_response(MappingProxyType(_signed({'Ds_Order': ORDER, 'Ds_Response': '0000'}))).is_paid() + + +def test_send_raises_validation_error_for_an_answer_that_is_not_json(): + client = DirectClient(SECRET, merchant_code='999008881', terminal=1, sandbox=True) + request = client.payment(order=ORDER, amount=Decimal('1.00')) + answer = httpx.Response(200, text='busy', request=httpx.Request('POST', request.endpoint)) + with mock.patch('httpx.post', return_value=answer), pytest.raises(ValidationError, match='not JSON'): + request.send()