python-redsys 2.2.0__py3-none-any.whl → 2.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-redsys
3
- Version: 2.2.0
3
+ Version: 2.2.1
4
4
  Summary: A simple, lightweight client to handle payments through the RedSys platform.
5
5
  Author-email: David Díaz <d.diazp@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -161,6 +161,7 @@ Fields are validated when the operation method is called, before anything is sig
161
161
  | 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 |
162
162
  | A transaction type that contradicts the operation or the redirect connection, a non-HTTPS `endpoint`, an invalid API key or environment | `redsys.exceptions.ValidationError` |
163
163
  | A signature that does not match in `parse_response()` | `ValueError` |
164
+ | 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` |
164
165
  | RedSys answers with an error code instead of a signed result | `redsys.exceptions.ResponseError`; `.error_code` holds the `SISnnnn` code |
165
166
  | An HTTP error status from RedSys in `send()` | `httpx.HTTPStatusError` |
166
167
 
@@ -174,7 +175,7 @@ A parameter the library does not model yet can be passed by its wire name (`Ds_M
174
175
 
175
176
  | | |
176
177
  |---|---|
177
- | Version | 2.2.0; 1.x receives fixes until 2026-12-31 ([migration guide](docs/migration-1x-to-2x.md)) |
178
+ | Version | 2.2.1; 1.x receives fixes until 2026-12-31 ([migration guide](docs/migration-1x-to-2x.md)) |
178
179
  | Python | 3.10 to 3.15 |
179
180
  | RedSys documents followed | Redirection guide 4.2, REST guide 4.0.1, Bizum guide 2.6, inSite guide 4.1, PayGold guide 1.8.2, Google Pay guide 1.9, Apple Pay guide 3.2, "Parámetros de entrada y salida" page |
180
181
  | Verified against the RedSys test environment | Redirect in a browser with the 3DS challenge; direct end to end (frictionless and challenged 3DS, 3DSMethod, refund, void, payment cancellation, stored-card merchant-initiated charge), in all three signature versions |
@@ -1,12 +1,12 @@
1
- python_redsys-2.2.0.dist-info/licenses/LICENSE,sha256=qsc7MUj20dcRHbyjIJn2jSbGRMaBOuHk8F9leaomY_4,11360
2
- python_redsys-2.2.0.dist-info/licenses/NOTICE,sha256=6tlv5QuzsbfmGxsQNEcN7Uopzyp7vgD54xb-_L4DGyE,201
1
+ python_redsys-2.2.1.dist-info/licenses/LICENSE,sha256=qsc7MUj20dcRHbyjIJn2jSbGRMaBOuHk8F9leaomY_4,11360
2
+ python_redsys-2.2.1.dist-info/licenses/NOTICE,sha256=6tlv5QuzsbfmGxsQNEcN7Uopzyp7vgD54xb-_L4DGyE,201
3
3
  redsys/__init__.py,sha256=pLpynJ40Qpr4yM9TX8MZ0pTrbl7TkbVp9cQog1NA-hI,605
4
4
  redsys/_code_texts.py,sha256=NLkVpNRNphxWIbvBYBJ96xFwrb_fbioEYXkBfKdKxEI,197037
5
- redsys/clients.py,sha256=mqcSZHeOklXTDxjlpptdGWmlqkB9fwc6rMtImvyv3uc,20266
5
+ redsys/clients.py,sha256=Ic7bpPKGccgXRPa03BvrXGIcKQcesC8YJ_Qf9gjLrjY,22730
6
6
  redsys/codes.py,sha256=wxoV9h85zwNbsRDcZI3gpc9Q3JBSsVuybHeqtg7xrn4,2508
7
7
  redsys/crypto.py,sha256=FJxYzhqarhaIDwFxTlk7JFNOEXM2_AZ1TAh325sHC7k,5438
8
- redsys/exceptions.py,sha256=wPHuuaHvAp9TriOMXnzaFAF3mCAWKQUu7LlWMjUoOk4,763
9
- redsys/models.py,sha256=aIM8q02EQCNizWf6kuPuv8OL3pEiiiUpQUt4lAgnxVQ,27507
8
+ redsys/exceptions.py,sha256=vq_RjtAcRURnLTIfzOPPU2O_97p1MWNWk8zW1WjgKHU,785
9
+ redsys/models.py,sha256=9ph9-pNjF_Ro_zrstK3yD11tqyr5RI249AB2lZow1o4,28898
10
10
  redsys/orders.py,sha256=ryYlu8wnbudQNeaUB1bKXg2WxHTzWjv-h_iu3ZguV60,786
11
11
  redsys/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
12
12
  redsys/request.py,sha256=5SxS3s2URXS_dVk5HaYO-o9tyw4PkWwsKKaQC9J-5GY,2356
@@ -28,7 +28,7 @@ redsys/api/sca.py,sha256=521jL7B_GZF-gymx3xDpEJCYhZVu5NSPM51TGEt0J34,1039
28
28
  redsys/api/secure_payment.py,sha256=QxzhFMLHbCQdb1-J9kbfuWq4rp6URPUrY1yVMZ3Kv3c,403
29
29
  redsys/api/transactions.py,sha256=PMDMlsrxgjoWUOZLpi2BsJK1Mrdvc0Ihjdz1icodvKE,2146
30
30
  redsys/api/xpay.py,sha256=KRojPBEkS3yhvrVJCUBP_8L8gxfVImS13tbmESe46ew,693
31
- python_redsys-2.2.0.dist-info/METADATA,sha256=wOUEzK-ejf_xMs4wUtlkO7gGBHOnALKPdRI9hbelHUg,9904
32
- python_redsys-2.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
33
- python_redsys-2.2.0.dist-info/top_level.txt,sha256=79TrHj--FP5SDyZO42-NUsiYJmHiQX42txZigHOqghY,7
34
- python_redsys-2.2.0.dist-info/RECORD,,
31
+ python_redsys-2.2.1.dist-info/METADATA,sha256=DKHnz3ArgjN_-tU3HIKUKrC7tMgT4D3ERwbTj52USi8,10112
32
+ python_redsys-2.2.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
33
+ python_redsys-2.2.1.dist-info/top_level.txt,sha256=79TrHj--FP5SDyZO42-NUsiYJmHiQX42txZigHOqghY,7
34
+ python_redsys-2.2.1.dist-info/RECORD,,
redsys/clients.py CHANGED
@@ -11,6 +11,7 @@ ends in ``send()``. ``parse_response()`` verifies and parses a received result.
11
11
  """
12
12
 
13
13
  from base64 import b64decode
14
+ from collections.abc import Mapping
14
15
  from hmac import compare_digest
15
16
  from importlib.metadata import PackageNotFoundError, version
16
17
  from logging import getLogger
@@ -18,6 +19,8 @@ from re import fullmatch, sub
18
19
  from urllib.parse import urlsplit
19
20
  from warnings import warn
20
21
 
22
+ from pydantic import ValidationError as PydanticValidationError
23
+
21
24
  from redsys import threeds
22
25
  from redsys.api import environments, transactions
23
26
  from redsys.crypto import (
@@ -39,6 +42,7 @@ from redsys.models import (
39
42
  RedirectPreauthorizationMessage,
40
43
  RefundMessage,
41
44
  Response,
45
+ decode_merchant_parameters,
42
46
  )
43
47
  from redsys.request import (
44
48
  MERCHANT_PARAMETERS,
@@ -63,6 +67,12 @@ DEFAULT_MODULE = _default_module()
63
67
  # Seconds; ``send(timeout=...)`` overrides it.
64
68
  DEFAULT_TIMEOUT = 30
65
69
 
70
+ # Real payloads take a few KiB; the caps bound the work done before the signature is checked.
71
+ _MAX_MERCHANT_PARAMETERS_LENGTH = 128 * 1024
72
+ _MAX_SIGNATURE_LENGTH = 128
73
+
74
+ _ORDER_WIRE_NAME = Response.model_fields['order'].alias
75
+
66
76
  __all__ = [
67
77
  'Client',
68
78
  'RedirectClient',
@@ -93,6 +103,19 @@ def _normalize_signature(signature) -> str:
93
103
  return sub(r'[^a-zA-Z0-9]', '', signature)
94
104
 
95
105
 
106
+ def _base64_text(value, name: str, max_length: int) -> bytes:
107
+ """A received Base64 field as bytes; Base64 is ASCII, so anything else is malformed."""
108
+ if isinstance(value, (str, bytes, bytearray)) and len(value) > max_length:
109
+ raise ValidationError(f'{name} exceeds {max_length} characters.')
110
+ if isinstance(value, str) and value.isascii():
111
+ value = value.encode('ascii')
112
+ elif isinstance(value, bytearray):
113
+ value = bytes(value)
114
+ if not isinstance(value, bytes) or not value.isascii():
115
+ raise ValidationError(f'{name} is missing or is not Base64 text.')
116
+ return value
117
+
118
+
96
119
  def _resolve_environment(environment: str | None, sandbox: bool | None) -> str:
97
120
  """The environment a client targets; ``sandbox`` means TEST when true and PROD when false."""
98
121
  implied = None if sandbox is None else environments.TEST if sandbox else environments.PROD
@@ -247,27 +270,50 @@ class Client:
247
270
  return Request(merchant_parameters, signature, version, sender=sender, endpoint=endpoint)
248
271
 
249
272
  # == Response parsing ==
250
- def parse_response(self, payload: dict) -> Response:
273
+ def parse_response(self, payload: Mapping) -> Response:
251
274
  """Verify the signature and parse a received payload into a ``Response``.
252
275
 
253
276
  Accepts both the redirect callback form fields and the direct REST JSON
254
- body. Raises ``ValueError`` if the signature does not match (the payload
255
- is not from RedSys or was tampered with), or ``ResponseError`` if RedSys
256
- answered with an error code instead of a signed result.
277
+ body. Fields are validated only after the signature matches. Raises
278
+ ``ResponseError`` if RedSys answered with an error code instead of a
279
+ signed result, ``ValidationError`` if the payload is not a well-formed
280
+ RedSys result, and ``ValueError`` if the signature does not match (the
281
+ payload is not from RedSys or was tampered with).
257
282
  """
283
+ if not isinstance(payload, Mapping):
284
+ raise ValidationError('The payload must be a mapping of the received fields.')
258
285
  if MERCHANT_PARAMETERS not in payload:
259
286
  error_code = payload.get('errorCode') or payload.get('Ds_ErrorCode')
287
+ if not error_code:
288
+ raise ValidationError(f'The payload carries neither {MERCHANT_PARAMETERS} nor an error code.')
260
289
  raise ResponseError(error_code, payload)
261
- merchant_parameters = payload[MERCHANT_PARAMETERS]
262
- if isinstance(merchant_parameters, str):
263
- merchant_parameters = merchant_parameters.encode('utf-8')
290
+ merchant_parameters = _base64_text(
291
+ payload[MERCHANT_PARAMETERS], MERCHANT_PARAMETERS, _MAX_MERCHANT_PARAMETERS_LENGTH
292
+ )
293
+ signature = _base64_text(payload.get(SIGNATURE), SIGNATURE, _MAX_SIGNATURE_LENGTH)
264
294
  version = payload.get(SIGNATURE_VERSION, DEFAULT_SIGNATURE_VERSION)
265
- response = Response.from_merchant_parameters(merchant_parameters)
295
+ if version not in SIGNATURE_VERSIONS:
296
+ raise ValidationError(f'{SIGNATURE_VERSION} is not supported.')
297
+ try:
298
+ fields = decode_merchant_parameters(merchant_parameters)
299
+ except ValueError as error:
300
+ raise ValidationError(f'{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object: {error}') from error
301
+ if not isinstance(fields, dict):
302
+ raise ValidationError(f'{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object.')
266
303
  # A signed result always carries Ds_Order; without it, '' makes verification fail.
267
- expected = get_signer(self._secret_key, version).sign(response.get_order() or '', merchant_parameters)
268
- if not compare_digest(_normalize_signature(payload[SIGNATURE]), _normalize_signature(expected)):
304
+ order = fields.get(_ORDER_WIRE_NAME)
305
+ try:
306
+ expected = get_signer(self._secret_key, version).sign(
307
+ order if isinstance(order, str) else '', merchant_parameters
308
+ )
309
+ except UnicodeEncodeError as error:
310
+ raise ValidationError(f'{_ORDER_WIRE_NAME} is not valid text.') from error
311
+ if not compare_digest(_normalize_signature(signature), _normalize_signature(expected)):
269
312
  raise ValueError('Signature is not valid.')
270
- return response
313
+ try:
314
+ return Response._from_fields(fields)
315
+ except (PydanticValidationError, ArithmeticError) as error:
316
+ raise ValidationError(f'{MERCHANT_PARAMETERS} holds a field that is not valid.') from error
271
317
 
272
318
 
273
319
  class RedirectClient(Client):
@@ -430,7 +476,11 @@ class _DirectBase(Client):
430
476
  http_response.raise_for_status()
431
477
  transport = (http_response.status_code, dict(http_response.headers), http_response.text)
432
478
  try:
433
- response = self.parse_response(http_response.json())
479
+ body = http_response.json()
480
+ except ValueError as error:
481
+ raise ValidationError('The answer is not JSON.') from error
482
+ try:
483
+ response = self.parse_response(body)
434
484
  except ResponseError as error:
435
485
  error.http_status, error.http_headers, error.raw_body = transport
436
486
  raise
redsys/exceptions.py CHANGED
@@ -15,7 +15,7 @@ class ResponseError(RedsysError):
15
15
 
16
16
 
17
17
  class ValidationError(RedsysError, ValueError):
18
- """A client option or an operation's fields contradict each other or what RedSys accepts."""
18
+ """Rejected input: a client option or operation fields RedSys does not accept, or a malformed received payload."""
19
19
 
20
20
 
21
21
  class UnknownParameterWarning(UserWarning):
redsys/models.py CHANGED
@@ -20,7 +20,9 @@ dict with ``model_validate``. Field constraints follow these RedSys documents:
20
20
 
21
21
  from base64 import b64decode, b64encode
22
22
  from decimal import Decimal
23
+ from itertools import accumulate
23
24
  from json import dumps, loads
25
+ from operator import sub as subtract
24
26
  from typing import Any
25
27
  from warnings import warn
26
28
 
@@ -48,13 +50,35 @@ _LEGACY_FIELDS: dict[str, str] = {
48
50
  }
49
51
 
50
52
 
53
+ # RedSys payloads nest two or three levels; deeper JSON can exhaust a small thread
54
+ # stack inside the C JSON decoder and kill the process.
55
+ _MAX_JSON_DEPTH = 32
56
+ _NOT_BRACKETS = bytes(sorted(set(range(256)) - set(b'[]{}')))
57
+ _BRACKET_WEIGHTS = bytes.maketrans(b'[{]}', b'\x02\x02\x00\x00')
58
+
59
+
60
+ def _json_depth_exceeds(text: bytes, limit: int) -> bool:
61
+ """Whether JSON text nests deeper than ``limit``; brackets inside strings do not count."""
62
+ if text.count(b'[') + text.count(b'{') <= limit:
63
+ return False
64
+ # Bytes operations only: the text may be attacker-sized, and a byte loop costs ten times more.
65
+ outside_strings = b''.join(text.replace(b'\\\\', b'').replace(b'\\"', b'').split(b'"')[::2])
66
+ # Opening brackets weigh 2 and closing ones 0: the running sum minus the position is the depth.
67
+ weights = outside_strings.translate(_BRACKET_WEIGHTS, _NOT_BRACKETS)
68
+ return max(map(subtract, accumulate(weights), range(1, len(weights) + 1)), default=0) > limit
69
+
70
+
51
71
  def decode_merchant_parameters(data: bytes) -> dict:
52
72
  """Decode a Ds_MerchantParameters string in standard or URL-safe Base64, padded or not.
53
73
 
54
74
  RedSys mixes the forms by signature version (HMAC_SHA512_V2 responses come unpadded).
75
+ JSON nested deeper than any RedSys payload raises ``ValueError`` before it is parsed.
55
76
  """
56
77
  data = data.replace(b'-', b'+').replace(b'_', b'/')
57
- return loads(b64decode(data + b'=' * (-len(data) % 4)).decode('utf-8'))
78
+ text = b64decode(data + b'=' * (-len(data) % 4))
79
+ if _json_depth_exceeds(text, _MAX_JSON_DEPTH):
80
+ raise ValueError(f'JSON nests deeper than {_MAX_JSON_DEPTH} levels.')
81
+ return loads(text.decode('utf-8'))
58
82
 
59
83
 
60
84
  def currency_decimals(currency: int | None) -> int:
@@ -487,12 +511,16 @@ class Response(BaseModel):
487
511
  @classmethod
488
512
  def _blank_amount_to_none(cls, value):
489
513
  # Keep the raw integer minor units here; scaling needs the currency and
490
- # is applied in from_merchant_parameters.
514
+ # is applied in _from_fields.
491
515
  return None if value in (None, '') else value
492
516
 
493
517
  @classmethod
494
518
  def from_merchant_parameters(cls, merchant_parameters: bytes) -> 'Response':
495
- response = cls.model_validate(decode_merchant_parameters(merchant_parameters))
519
+ return cls._from_fields(decode_merchant_parameters(merchant_parameters))
520
+
521
+ @classmethod
522
+ def _from_fields(cls, fields: dict) -> 'Response':
523
+ response = cls.model_validate(fields)
496
524
  if response.amount is not None:
497
525
  # scaleb keeps the currency's decimals: 100 EUR minor units read as 1.00, not 1.
498
526
  response.amount = response.amount.scaleb(-currency_decimals(response.currency))