python-redsys 1.2.2__py3-none-any.whl → 1.2.3__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: 1.2.2
3
+ Version: 1.2.3
4
4
  Summary: A simple, lightweight client to handle payments through the RedSys platform.
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -88,7 +88,7 @@ RedSys notifies the result both as a server-to-server POST to `merchant_url` and
88
88
 
89
89
  ### 3. Verify and read the response
90
90
 
91
- `create_response()` takes the received `Ds_Signature` and `Ds_MerchantParameters` and raises `ValueError` on signature mismatch.
91
+ `create_response()` takes the received `Ds_Signature` and `Ds_MerchantParameters`, verifies the signature before it reads any field, and raises `ValueError` on signature mismatch or a malformed payload: a `Ds_Signature` over 128 characters, a `Ds_MerchantParameters` over 128 KiB or that is not a Base64-encoded JSON object nested at most 32 levels, or a signed field that cannot be read.
92
92
 
93
93
  ```python
94
94
  response = client.create_response(signature, merchant_parameters) # as RedSys posted them back
@@ -1,13 +1,13 @@
1
- redsys/__init__.py,sha256=k234cuEigYkeydQvG5NyAl4pPAyCQSjL65UvOkeTak8,138
2
- redsys/client.py,sha256=ervLX4FbzDfWjh_SO2SFyY9IT0PZ5aIcVZdYy4mUO7Q,3937
1
+ redsys/__init__.py,sha256=9mEZ9vAD-YQf1MT52c_PVG1MlN5V6RjMBHsmIklM8xk,138
2
+ redsys/client.py,sha256=JLlu_ecfaJ-ngbEN5uJbLNKsOfN_mrxcOQlgmFwpHp0,6714
3
3
  redsys/constants.py,sha256=lJYgbmikxh0b9iVM4M5XFWBWVvdFY27OkcXSLluHSsQ,2497
4
4
  redsys/request.py,sha256=IEzlRi34JgDBRRyaBHtIrAZ38fADL977RdBFaeWDdbY,5304
5
5
  redsys/response.py,sha256=YDihLSIE388Ib53qr9PUtGsWqLqj1zFdjbgn9x_i-8A,5585
6
6
  redsys/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
- redsys/tests/test_client.py,sha256=oND8W9y6O6MkDLNxnBpd8UDShwKWoAW3SgKmWDOXHrw,3858
7
+ redsys/tests/test_client.py,sha256=T2XGBUsBqf1RjFVougDk-67O6w2RvKPb0gg3FyDARSA,9364
8
8
  redsys/tests/test_request.py,sha256=FONigjMNdaug2DwillYKCLPK-gzIYZSVUZmcm9QkCms,3110
9
9
  redsys/tests/test_response.py,sha256=K1QP7eRyBum88LXG6IOQtno8FZNxoVHUv-GJU83k5OI,1777
10
- python_redsys-1.2.2.dist-info/METADATA,sha256=PXqNlioj4tNFrfUXhiPZ1P77pgIJne39Q_oD4sXto4U,5517
11
- python_redsys-1.2.2.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
12
- python_redsys-1.2.2.dist-info/licenses/LICENSE,sha256=Ku6mJcUOcHd2aZ4o2Jh4Tjkx1oZT-iT0VCyUNvm2IXU,1257
13
- python_redsys-1.2.2.dist-info/RECORD,,
10
+ python_redsys-1.2.3.dist-info/METADATA,sha256=l4ErY7ar9CAYUWdtq1g4b78RsgbGID9GE6YCAweLQSM,5777
11
+ python_redsys-1.2.3.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
12
+ python_redsys-1.2.3.dist-info/licenses/LICENSE,sha256=Ku6mJcUOcHd2aZ4o2Jh4Tjkx1oZT-iT0VCyUNvm2IXU,1257
13
+ python_redsys-1.2.3.dist-info/RECORD,,
redsys/__init__.py CHANGED
@@ -1,2 +1,2 @@
1
- __version__ = "1.2.2"
1
+ __version__ = "1.2.3"
2
2
  __version_info__ = tuple(int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split("."))
redsys/client.py CHANGED
@@ -5,12 +5,15 @@ import json
5
5
  import re
6
6
  from abc import ABC
7
7
  from abc import abstractmethod
8
+ from itertools import accumulate
9
+ from operator import sub as subtract
8
10
  from typing import Any
9
11
  from typing import Dict
10
12
 
11
13
  from Crypto.Cipher import DES3
12
14
 
13
15
  from redsys.request import Request
16
+ from redsys.response import ORDER
14
17
  from redsys.response import Response
15
18
 
16
19
  # Calculated parameters
@@ -19,6 +22,34 @@ MERCHANT_PARAMETERS = "Ds_MerchantParameters"
19
22
  SIGNATURE = "Ds_Signature"
20
23
  DEFAULT_SIGNATURE_VERSION = "HMAC_SHA256_V1"
21
24
 
25
+ # Real notifications take a few KiB; the caps bound the work done before the signature is checked.
26
+ _MAX_MERCHANT_PARAMETERS_LENGTH = 128 * 1024
27
+ _MAX_SIGNATURE_LENGTH = 128
28
+ # RedSys payloads nest two or three levels; deeper JSON can exhaust a small thread
29
+ # stack inside the C JSON decoder and kill the process.
30
+ _MAX_JSON_DEPTH = 32
31
+ _NOT_BRACKETS = bytes(sorted(set(range(256)) - set(b"[]{}")))
32
+ _BRACKET_WEIGHTS = bytes.maketrans(b"[{]}", b"\x02\x02\x00\x00")
33
+ _NOT_ALPHANUMERIC = re.compile(b"[^a-zA-Z0-9]")
34
+
35
+
36
+ def _json_depth_exceeds(text: bytes, limit: int) -> bool:
37
+ """Whether JSON text nests deeper than ``limit``; brackets inside strings do not count."""
38
+ if text.count(b"[") + text.count(b"{") <= limit:
39
+ return False
40
+ # Bytes operations only: the text may be attacker-sized, and a byte loop costs ten times more.
41
+ outside_strings = b"".join(text.replace(b"\\\\", b"").replace(b'\\"', b"").split(b'"')[::2])
42
+ # Opening brackets weigh 2 and closing ones 0: the running sum minus the position is the depth.
43
+ weights = outside_strings.translate(_BRACKET_WEIGHTS, _NOT_BRACKETS)
44
+ return max(map(subtract, accumulate(weights), range(1, len(weights) + 1)), default=0) > limit
45
+
46
+
47
+ def _received_field(value: str, name: str, max_length: int) -> bytes:
48
+ """A received Base64 field as bytes; Base64 is ASCII text."""
49
+ if not isinstance(value, str) or len(value) > max_length or not value.isascii():
50
+ raise ValueError(f"{name} is not Base64 text of at most {max_length} characters.")
51
+ return value.encode()
52
+
22
53
 
23
54
  class Client(ABC):
24
55
  """
@@ -44,8 +75,11 @@ class Client(ABC):
44
75
 
45
76
  @staticmethod
46
77
  def decode_parameters(parameters: bytes) -> Dict[str, Any]:
47
- """Decodes the merchant parameters from base64"""
48
- return json.loads(base64.b64decode(parameters).decode())
78
+ """Decodes the merchant parameters from base64; JSON nested deeper than any RedSys payload raises ValueError"""
79
+ text = base64.b64decode(parameters)
80
+ if _json_depth_exceeds(text, _MAX_JSON_DEPTH):
81
+ raise ValueError(f"JSON nests deeper than {_MAX_JSON_DEPTH} levels.")
82
+ return json.loads(text.decode())
49
83
 
50
84
  @staticmethod
51
85
  def sign_hmac256(encrypted_order: bytes, merchant_parameters: bytes) -> bytes:
@@ -91,15 +125,28 @@ class RedirectClient(Client):
91
125
  Checks if the received signature corresponds to the sent signature.
92
126
 
93
127
  Both the `signature` and `merchant parameters` are plain strings, not bytes.
128
+ The fields are read only after the signature matches; a malformed payload
129
+ raises `ValueError` too.
94
130
  """
95
- decoded_parameters = self.decode_parameters(merchant_parameters.encode())
96
- response = Response(decoded_parameters)
97
- calculated_signature = self.generate_signature(response.order, merchant_parameters.encode())
98
- # Remove any non-alphanumeric characters from the signature
99
- not_alphanumeric = re.compile("[^a-zA-Z0-9]")
100
- safe_signature = re.sub(not_alphanumeric, "", signature)
101
-
102
- safe_calculated_signature = re.sub(not_alphanumeric, "", calculated_signature.decode())
103
- if safe_signature != safe_calculated_signature:
131
+ received_signature = _received_field(signature, SIGNATURE, _MAX_SIGNATURE_LENGTH)
132
+ encoded_parameters = _received_field(merchant_parameters, MERCHANT_PARAMETERS, _MAX_MERCHANT_PARAMETERS_LENGTH)
133
+ try:
134
+ decoded_parameters = self.decode_parameters(encoded_parameters)
135
+ except ValueError as error:
136
+ raise ValueError(f"{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object: {error}") from error
137
+ if not isinstance(decoded_parameters, dict):
138
+ raise ValueError(f"{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object.")
139
+ order = decoded_parameters.get(ORDER)
140
+ # encrypt_3DES takes at most 16 ASCII bytes; any other order cannot verify, so it signs as ''.
141
+ if not (isinstance(order, str) and order.isascii() and len(order) <= 16):
142
+ order = ""
143
+ calculated_signature = self.generate_signature(order, encoded_parameters)
144
+ # Signatures may arrive in URL-safe Base64; only the alphanumeric core is compared.
145
+ if not hmac.compare_digest(
146
+ _NOT_ALPHANUMERIC.sub(b"", received_signature), _NOT_ALPHANUMERIC.sub(b"", calculated_signature)
147
+ ):
104
148
  raise ValueError("The provided signature is not valid.")
105
- return response
149
+ try:
150
+ return Response(decoded_parameters)
151
+ except (ValueError, ArithmeticError) as error:
152
+ raise ValueError(f"{MERCHANT_PARAMETERS} holds a field that is not valid.") from error
@@ -1,8 +1,13 @@
1
+ import base64
2
+ import hmac
3
+ import json
1
4
  from decimal import ROUND_HALF_UP
2
5
  from decimal import Decimal as D
6
+ from unittest import mock
3
7
 
4
8
  import pytest
5
9
 
10
+ from redsys import client as client_module
6
11
  from redsys.client import RedirectClient
7
12
  from redsys.constants import EUR
8
13
  from redsys.constants import STANDARD_PAYMENT
@@ -87,3 +92,120 @@ class TestRedirectClient:
87
92
  bad_signature = b"sadfe2r3q2fdssaf3"
88
93
  with pytest.raises(ValueError, match="The provided signature is not valid"):
89
94
  self.client.create_response(bad_signature.decode(), encoded_params.decode())
95
+
96
+
97
+ SECRET = "sq7HjrUOBfKmC576ILgskD5srU870gJ7"
98
+ ORDER = "000000000001"
99
+
100
+
101
+ def _nested(depth):
102
+ value = []
103
+ for _ in range(depth - 1):
104
+ value = [value]
105
+ return value
106
+
107
+
108
+ class TestCreateResponseHardening:
109
+ @pytest.fixture(autouse=True)
110
+ def set_up(self):
111
+ self.client = RedirectClient(SECRET)
112
+
113
+ def _signed(self, fields, order=ORDER):
114
+ encoded = self.client.encode_parameters(fields)
115
+ return self.client.generate_signature(order, encoded).decode(), encoded.decode()
116
+
117
+ def _unsigned(self, raw):
118
+ return "x", base64.b64encode(raw).decode()
119
+
120
+ @pytest.mark.parametrize(
121
+ "signature, merchant_parameters",
122
+ [
123
+ (b"x", "e30="),
124
+ ("A" * 129, "e30="),
125
+ ("x", 7),
126
+ ("x", "ée30="),
127
+ ("x", "AAAA"),
128
+ ("x", base64.b64encode(b"\xff\xfe").decode()),
129
+ ("x", base64.b64encode(b"[1, 2]").decode()),
130
+ ],
131
+ ids=[
132
+ "signature bytes",
133
+ "signature too long",
134
+ "parameters not text",
135
+ "parameters not ascii",
136
+ "not base64 json",
137
+ "not utf-8",
138
+ "json array",
139
+ ],
140
+ )
141
+ def test_malformed_payload_raises_value_error(self, signature, merchant_parameters):
142
+ with pytest.raises(ValueError) as raised:
143
+ self.client.create_response(signature, merchant_parameters)
144
+ assert "The provided signature is not valid" not in str(raised.value)
145
+
146
+ def test_oversized_parameters_are_rejected_before_decoding(self, monkeypatch):
147
+ signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000"})
148
+ monkeypatch.setattr(client_module, "_MAX_MERCHANT_PARAMETERS_LENGTH", len(merchant_parameters) - 1)
149
+ with mock.patch.object(RedirectClient, "decode_parameters") as decode, pytest.raises(
150
+ ValueError, match="at most"
151
+ ):
152
+ self.client.create_response(signature, merchant_parameters)
153
+ decode.assert_not_called()
154
+
155
+ def test_parameters_at_the_limit_are_accepted(self, monkeypatch):
156
+ signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000"})
157
+ monkeypatch.setattr(client_module, "_MAX_MERCHANT_PARAMETERS_LENGTH", len(merchant_parameters))
158
+ assert self.client.create_response(signature, merchant_parameters).is_paid
159
+
160
+ def test_deep_nesting_is_rejected_before_parsing(self):
161
+ raw = json.dumps({"Ds_Order": ORDER, "x": _nested(32)}).encode()
162
+ with mock.patch("redsys.client.json.loads") as parse, pytest.raises(ValueError, match="nests deeper"):
163
+ self.client.create_response(*self._unsigned(raw))
164
+ parse.assert_not_called()
165
+
166
+ def test_nesting_at_the_limit_is_accepted(self):
167
+ signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000", "x": _nested(31)})
168
+ assert self.client.create_response(signature, merchant_parameters).is_paid
169
+
170
+ @pytest.mark.parametrize(
171
+ "text, depth",
172
+ [
173
+ ('{"a": "[[[[", "b": [1, {"c": "]]]]"}]}', 3),
174
+ ('{"a": "x\\"[[", "b": "\\\\", "c": [[]], "d": "\\\\\\"]]"}', 3),
175
+ ('{"a": "' + "]" * 40 + '", "b": ' + "[" * 30 + "]" * 30 + "}", 31),
176
+ ],
177
+ )
178
+ def test_depth_ignores_brackets_inside_strings(self, text, depth):
179
+ padded = ("[" + text + "," + ",".join(["[]"] * 40) + "]").encode()
180
+ assert client_module._json_depth_exceeds(padded, depth + 1) is False
181
+ assert client_module._json_depth_exceeds(padded, depth) is True
182
+
183
+ @pytest.mark.parametrize("fields", [{"Ds_Response": "0000"}, {"Ds_Order": "1" * 20}, {"Ds_Order": 1}])
184
+ def test_order_that_cannot_sign_fails_verification(self, fields):
185
+ signature, merchant_parameters = self._signed(fields)
186
+ with pytest.raises(ValueError, match="The provided signature is not valid"):
187
+ self.client.create_response(signature, merchant_parameters)
188
+
189
+ def test_fields_are_not_read_without_a_matching_signature(self):
190
+ raw = json.dumps({"Ds_Order": ORDER, "Ds_Amount": "not a number"}).encode()
191
+ invalid = pytest.raises(ValueError, match="The provided signature is not valid")
192
+ with mock.patch("redsys.client.Response") as response, invalid:
193
+ self.client.create_response(*self._unsigned(raw))
194
+ response.assert_not_called()
195
+
196
+ def test_signed_invalid_field_raises_value_error(self):
197
+ signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Amount": "not a number"})
198
+ with pytest.raises(ValueError, match="holds a field"):
199
+ self.client.create_response(signature, merchant_parameters)
200
+
201
+ def test_signatures_compare_in_constant_time(self):
202
+ signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000"})
203
+ with mock.patch("redsys.client.hmac.compare_digest", wraps=hmac.compare_digest) as compare:
204
+ self.client.create_response(signature, merchant_parameters)
205
+ compare.assert_called_once()
206
+
207
+ def test_url_safe_signature_is_accepted(self):
208
+ signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000", "Ds_Amount": "1056"})
209
+ response = self.client.create_response(signature.replace("+", "-").replace("/", "_"), merchant_parameters)
210
+ assert response.is_paid
211
+ assert response.amount == D("10.56")