Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |

Expand Down
1 change: 1 addition & 0 deletions docs/direct-connection.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
2 changes: 1 addition & 1 deletion docs/redirect-connection.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
74 changes: 62 additions & 12 deletions redsys/clients.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@
"""

from base64 import b64decode
from collections.abc import Mapping
from hmac import compare_digest
from importlib.metadata import PackageNotFoundError, version
from logging import getLogger
from re import fullmatch, sub
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 (
Expand All @@ -39,6 +42,7 @@
RedirectPreauthorizationMessage,
RefundMessage,
Response,
decode_merchant_parameters,
)
from redsys.request import (
MERCHANT_PARAMETERS,
Expand All @@ -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',
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion redsys/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
34 changes: 31 additions & 3 deletions redsys/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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))
Expand Down
Loading
Loading