python-redsys 2.2.0__tar.gz → 2.2.1__tar.gz

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.
Files changed (55) hide show
  1. {python_redsys-2.2.0/python_redsys.egg-info → python_redsys-2.2.1}/PKG-INFO +3 -2
  2. {python_redsys-2.2.0 → python_redsys-2.2.1}/README.md +2 -1
  3. {python_redsys-2.2.0 → python_redsys-2.2.1}/pyproject.toml +1 -1
  4. {python_redsys-2.2.0 → python_redsys-2.2.1/python_redsys.egg-info}/PKG-INFO +3 -2
  5. {python_redsys-2.2.0 → python_redsys-2.2.1}/python_redsys.egg-info/SOURCES.txt +1 -0
  6. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/clients.py +62 -12
  7. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/exceptions.py +1 -1
  8. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/models.py +31 -3
  9. python_redsys-2.2.1/tests/test_parse_response.py +187 -0
  10. {python_redsys-2.2.0 → python_redsys-2.2.1}/LICENSE +0 -0
  11. {python_redsys-2.2.0 → python_redsys-2.2.1}/NOTICE +0 -0
  12. {python_redsys-2.2.0 → python_redsys-2.2.1}/python_redsys.egg-info/dependency_links.txt +0 -0
  13. {python_redsys-2.2.0 → python_redsys-2.2.1}/python_redsys.egg-info/requires.txt +0 -0
  14. {python_redsys-2.2.0 → python_redsys-2.2.1}/python_redsys.egg-info/top_level.txt +0 -0
  15. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/__init__.py +0 -0
  16. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/_code_texts.py +0 -0
  17. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/__init__.py +0 -0
  18. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/bizum.py +0 -0
  19. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/cards.py +0 -0
  20. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/cof.py +0 -0
  21. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/currencies.py +0 -0
  22. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/emv3ds.py +0 -0
  23. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/environments.py +0 -0
  24. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/languages.py +0 -0
  25. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/options.py +0 -0
  26. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/pay_methods.py +0 -0
  27. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/paygold.py +0 -0
  28. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/processed_pay_methods.py +0 -0
  29. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/responses.py +0 -0
  30. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/sca.py +0 -0
  31. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/secure_payment.py +0 -0
  32. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/transactions.py +0 -0
  33. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/api/xpay.py +0 -0
  34. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/codes.py +0 -0
  35. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/crypto.py +0 -0
  36. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/orders.py +0 -0
  37. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/py.typed +0 -0
  38. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/request.py +0 -0
  39. {python_redsys-2.2.0 → python_redsys-2.2.1}/redsys/threeds.py +0 -0
  40. {python_redsys-2.2.0 → python_redsys-2.2.1}/setup.cfg +0 -0
  41. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_bizum.py +0 -0
  42. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_clients.py +0 -0
  43. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_codes.py +0 -0
  44. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_constants.py +0 -0
  45. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_crypto.py +0 -0
  46. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_direct.py +0 -0
  47. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_environments.py +0 -0
  48. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_live.py +0 -0
  49. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_models.py +0 -0
  50. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_operations.py +0 -0
  51. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_orders.py +0 -0
  52. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_parameters.py +0 -0
  53. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_paygold.py +0 -0
  54. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_threeds.py +0 -0
  55. {python_redsys-2.2.0 → python_redsys-2.2.1}/tests/test_xpay.py +0 -0
@@ -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 |
@@ -132,6 +132,7 @@ Fields are validated when the operation method is called, before anything is sig
132
132
  | 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 |
133
133
  | A transaction type that contradicts the operation or the redirect connection, a non-HTTPS `endpoint`, an invalid API key or environment | `redsys.exceptions.ValidationError` |
134
134
  | A signature that does not match in `parse_response()` | `ValueError` |
135
+ | 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` |
135
136
  | RedSys answers with an error code instead of a signed result | `redsys.exceptions.ResponseError`; `.error_code` holds the `SISnnnn` code |
136
137
  | An HTTP error status from RedSys in `send()` | `httpx.HTTPStatusError` |
137
138
 
@@ -145,7 +146,7 @@ A parameter the library does not model yet can be passed by its wire name (`Ds_M
145
146
 
146
147
  | | |
147
148
  |---|---|
148
- | Version | 2.2.0; 1.x receives fixes until 2026-12-31 ([migration guide](docs/migration-1x-to-2x.md)) |
149
+ | Version | 2.2.1; 1.x receives fixes until 2026-12-31 ([migration guide](docs/migration-1x-to-2x.md)) |
149
150
  | Python | 3.10 to 3.15 |
150
151
  | 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 |
151
152
  | 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 |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "python-redsys"
7
- version = "2.2.0"
7
+ version = "2.2.1"
8
8
  description = "A simple, lightweight client to handle payments through the RedSys platform."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -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 |
@@ -47,6 +47,7 @@ tests/test_models.py
47
47
  tests/test_operations.py
48
48
  tests/test_orders.py
49
49
  tests/test_parameters.py
50
+ tests/test_parse_response.py
50
51
  tests/test_paygold.py
51
52
  tests/test_threeds.py
52
53
  tests/test_xpay.py
@@ -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
@@ -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):
@@ -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))
@@ -0,0 +1,187 @@
1
+ import os
2
+ import sys
3
+ from base64 import b64encode
4
+ from decimal import Decimal
5
+ from json import dumps, loads
6
+ from types import MappingProxyType
7
+ from unittest import mock
8
+
9
+ import httpx
10
+ import pytest
11
+ from pydantic import ValidationError as PydanticValidationError
12
+
13
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
14
+
15
+ from redsys import clients
16
+ from redsys.clients import MERCHANT_PARAMETERS, SIGNATURE, SIGNATURE_VERSION, DirectClient, RedirectClient
17
+ from redsys.crypto import HMAC_SHA256_V1, HMAC_SHA512_V2, get_signer
18
+ from redsys.exceptions import ResponseError, ValidationError
19
+ from redsys.models import _MAX_JSON_DEPTH, Response, _json_depth_exceeds
20
+
21
+ SECRET = 'sq7HjrUOBfKmC576ILgskD5srU870gJ7'
22
+ ORDER = '000000001'
23
+
24
+
25
+ def _client():
26
+ return RedirectClient(SECRET, merchant_code='999008881', terminal=1, sandbox=True)
27
+
28
+
29
+ def _encoded(raw: bytes) -> str:
30
+ return b64encode(raw).decode('ascii')
31
+
32
+
33
+ def _payload(merchant_parameters, signature='x', version=HMAC_SHA512_V2) -> dict:
34
+ return {SIGNATURE_VERSION: version, MERCHANT_PARAMETERS: merchant_parameters, SIGNATURE: signature}
35
+
36
+
37
+ def _signed(fields: dict, order: str = ORDER, version: str = HMAC_SHA256_V1) -> dict:
38
+ merchant_parameters = b64encode(dumps(fields).encode('utf-8'))
39
+ signature = get_signer(SECRET, version).sign(order, merchant_parameters)
40
+ return _payload(merchant_parameters.decode('ascii'), signature.decode('ascii'), version)
41
+
42
+
43
+ def _nested(depth: int):
44
+ value: list = []
45
+ for _ in range(depth - 1):
46
+ value = [value]
47
+ return value
48
+
49
+
50
+ _UNSIGNED_FIELDS = _encoded(b'{"Ds_Order": "000000001", "Ds_Response": "0000"}')
51
+
52
+ MALFORMED = {
53
+ 'not a mapping': [MERCHANT_PARAMETERS],
54
+ 'neither parameters nor error code': {},
55
+ 'no signature': {MERCHANT_PARAMETERS: _UNSIGNED_FIELDS},
56
+ 'signature not text': _payload(_UNSIGNED_FIELDS, signature=7),
57
+ 'signature too long': _payload(_UNSIGNED_FIELDS, signature='A' * 129),
58
+ 'parameters not text': _payload(7),
59
+ 'parameters not ascii': _payload('\ud800' + _UNSIGNED_FIELDS),
60
+ 'unsupported version': _payload(_UNSIGNED_FIELDS, version='HMAC_MD5_V0'),
61
+ 'not base64 json': _payload('AAAA'),
62
+ 'not utf-8': _payload(_encoded(b'\xff\xfe')),
63
+ 'json array': _payload(_encoded(b'[1, 2]')),
64
+ 'order not encodable': _payload(_encoded(b'{"Ds_Order": "\\ud800"}')),
65
+ 'nested too deep': _payload(_encoded(dumps({'Ds_Order': ORDER, 'x': _nested(_MAX_JSON_DEPTH)}).encode())),
66
+ }
67
+
68
+
69
+ @pytest.mark.parametrize('payload', MALFORMED.values(), ids=MALFORMED.keys())
70
+ def test_malformed_payload_raises_validation_error(payload):
71
+ with pytest.raises(ValidationError):
72
+ _client().parse_response(payload)
73
+
74
+
75
+ def test_validation_error_is_a_value_error():
76
+ with pytest.raises(ValueError):
77
+ _client().parse_response(_payload('AAAA'))
78
+
79
+
80
+ def test_error_payload_still_raises_response_error():
81
+ with pytest.raises(ResponseError):
82
+ _client().parse_response({'Ds_ErrorCode': 'SIS0042'})
83
+
84
+
85
+ def test_oversized_parameters_are_rejected_before_decoding():
86
+ payload = _signed({'Ds_Order': ORDER, 'Ds_Response': '0000'})
87
+ with (
88
+ mock.patch.object(clients, '_MAX_MERCHANT_PARAMETERS_LENGTH', len(payload[MERCHANT_PARAMETERS]) - 1),
89
+ mock.patch.object(clients, 'decode_merchant_parameters') as decode,
90
+ pytest.raises(ValidationError, match='exceeds'),
91
+ ):
92
+ _client().parse_response(payload)
93
+ decode.assert_not_called()
94
+
95
+
96
+ def test_parameters_at_the_limit_are_accepted():
97
+ payload = _signed({'Ds_Order': ORDER, 'Ds_Response': '0000'})
98
+ with mock.patch.object(clients, '_MAX_MERCHANT_PARAMETERS_LENGTH', len(payload[MERCHANT_PARAMETERS])):
99
+ assert _client().parse_response(payload).is_paid()
100
+
101
+
102
+ def test_deep_nesting_is_rejected_before_parsing():
103
+ with (
104
+ mock.patch('redsys.models.loads') as parse,
105
+ pytest.raises(ValidationError, match='nests deeper'),
106
+ ):
107
+ _client().parse_response(MALFORMED['nested too deep'])
108
+ parse.assert_not_called()
109
+
110
+
111
+ def test_nesting_at_the_limit_is_accepted():
112
+ fields = {'Ds_Order': ORDER, 'Ds_Response': '0000', 'x': _nested(_MAX_JSON_DEPTH - 1)}
113
+ assert _client().parse_response(_signed(fields)).is_paid()
114
+
115
+
116
+ @pytest.mark.parametrize(
117
+ 'text',
118
+ [
119
+ '{"a": "[[[[", "b": [1, {"c": "]]]]"}]}',
120
+ '{"a": "x\\"[[", "b": "\\\\", "c": [[]], "d": "\\\\\\"]]"}',
121
+ '{"Ds_MerchantData": "{\\"cart\\":[{\\"x\\":[1]}]}", "Ds_EMV3DS": {"a": [{"b": 1}]}}',
122
+ '[' * 40 + ']' * 40,
123
+ '{"a": "' + ']' * 40 + '", "b": ' + '[' * 30 + ']' * 30 + '}',
124
+ ],
125
+ )
126
+ def test_depth_ignores_brackets_inside_strings(text):
127
+ def depth(value):
128
+ children = value.values() if isinstance(value, dict) else value if isinstance(value, list) else ()
129
+ return 1 + max(map(depth, children), default=0) if isinstance(value, (dict, list)) else 0
130
+
131
+ actual = depth(loads(text))
132
+ padded = ('[' + text + ',' + ','.join(['[]'] * 40) + ']').encode()
133
+ assert _json_depth_exceeds(padded, actual + 1) is False
134
+ assert _json_depth_exceeds(padded, actual) is True
135
+
136
+
137
+ @pytest.mark.parametrize('amount', ['1E99999999', 'not a number'])
138
+ def test_fields_are_not_validated_without_a_matching_signature(amount):
139
+ payload = _payload(_encoded(dumps({'Ds_Order': ORDER, 'Ds_Amount': amount}).encode('utf-8')))
140
+ with (
141
+ mock.patch.object(Response, 'model_validate') as validate,
142
+ pytest.raises(ValueError, match='Signature is not valid'),
143
+ ):
144
+ _client().parse_response(payload)
145
+ validate.assert_not_called()
146
+
147
+
148
+ def test_missing_order_fails_verification():
149
+ with pytest.raises(ValueError, match='Signature is not valid'):
150
+ _client().parse_response(_signed({'Ds_Response': '0000'}))
151
+
152
+
153
+ def test_signed_invalid_field_raises_validation_error_with_the_cause():
154
+ with pytest.raises(ValidationError) as raised:
155
+ _client().parse_response(_signed({'Ds_Order': ORDER, 'Ds_Amount': 'not a number'}))
156
+ assert isinstance(raised.value.__cause__, PydanticValidationError)
157
+
158
+
159
+ def test_signed_amount_out_of_range_raises_validation_error():
160
+ with pytest.raises(ValidationError):
161
+ _client().parse_response(_signed({'Ds_Order': ORDER, 'Ds_Amount': '1E99999999'}))
162
+
163
+
164
+ def test_well_formed_signed_payload_parses():
165
+ response = _client().parse_response(_signed({'Ds_Order': ORDER, 'Ds_Response': '0000', 'Ds_Amount': '1056'}))
166
+ assert response.is_paid()
167
+ assert response.amount == Decimal('10.56')
168
+
169
+
170
+ @pytest.mark.parametrize('kind', [bytes, bytearray])
171
+ def test_binary_fields_are_accepted(kind):
172
+ payload = _signed({'Ds_Order': ORDER, 'Ds_Response': '0000'})
173
+ payload[MERCHANT_PARAMETERS] = kind(payload[MERCHANT_PARAMETERS].encode())
174
+ payload[SIGNATURE] = kind(payload[SIGNATURE].encode())
175
+ assert _client().parse_response(payload).is_paid()
176
+
177
+
178
+ def test_any_mapping_is_accepted():
179
+ assert _client().parse_response(MappingProxyType(_signed({'Ds_Order': ORDER, 'Ds_Response': '0000'}))).is_paid()
180
+
181
+
182
+ def test_send_raises_validation_error_for_an_answer_that_is_not_json():
183
+ client = DirectClient(SECRET, merchant_code='999008881', terminal=1, sandbox=True)
184
+ request = client.payment(order=ORDER, amount=Decimal('1.00'))
185
+ answer = httpx.Response(200, text='<html>busy</html>', request=httpx.Request('POST', request.endpoint))
186
+ with mock.patch('httpx.post', return_value=answer), pytest.raises(ValidationError, match='not JSON'):
187
+ request.send()
File without changes
File without changes
File without changes