test_serializer.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import hashlib
  2. import pickle
  3. from functools import partial
  4. from io import BytesIO
  5. from io import StringIO
  6. from typing import Any
  7. from typing import cast
  8. from typing import IO
  9. from typing import overload
  10. from typing import Union
  11. import pytest
  12. from itsdangerous.exc import BadPayload
  13. from itsdangerous.exc import BadSignature
  14. from itsdangerous.serializer import Serializer
  15. from itsdangerous.signer import _lazy_sha1
  16. from itsdangerous.signer import Signer
  17. @overload
  18. def coerce_str(ref: str, s: str) -> str: ...
  19. @overload
  20. def coerce_str(ref: bytes, s: str) -> bytes: ...
  21. def coerce_str(ref: Union[str, bytes], s: str) -> Union[str, bytes]:
  22. if isinstance(ref, bytes):
  23. return s.encode("utf8")
  24. return s
  25. class TestSerializer:
  26. @pytest.fixture(params=(Serializer, partial(Serializer, serializer=pickle)))
  27. def serializer_factory(self, request):
  28. return partial(request.param, secret_key="secret_key")
  29. @pytest.fixture()
  30. def serializer(self, serializer_factory):
  31. return serializer_factory()
  32. @pytest.fixture()
  33. def value(self):
  34. return {"id": 42}
  35. @pytest.mark.parametrize(
  36. "value", (None, True, "str", "text", [1, 2, 3], {"id": 42})
  37. )
  38. def test_serializer(self, serializer: Serializer, value: Any):
  39. assert serializer.loads(serializer.dumps(value)) == value
  40. @pytest.mark.parametrize(
  41. "transform",
  42. (
  43. lambda s: s.upper(),
  44. lambda s: s + coerce_str(s, "a"),
  45. lambda s: coerce_str(s, "a") + s[1:],
  46. lambda s: s.replace(coerce_str(s, "."), coerce_str(s, "")),
  47. ),
  48. )
  49. def test_changed_value(self, serializer: Serializer, value: Any, transform):
  50. signed = serializer.dumps(value)
  51. assert serializer.loads(signed) == value
  52. changed = transform(signed)
  53. with pytest.raises(BadSignature):
  54. serializer.loads(changed)
  55. def test_bad_signature_exception(self, serializer: Serializer, value: Any):
  56. bad_signed = serializer.dumps(value)[:-1]
  57. with pytest.raises(BadSignature) as exc_info:
  58. serializer.loads(bad_signed)
  59. payload = cast(bytes, exc_info.value.payload)
  60. assert serializer.load_payload(payload) == value
  61. def test_bad_payload_exception(self, serializer: Serializer, value: Any):
  62. original = serializer.dumps(value)
  63. payload = original.rsplit(coerce_str(original, "."), 1)[0] # type: ignore
  64. bad = serializer.make_signer().sign(payload[:-1])
  65. with pytest.raises(BadPayload) as exc_info:
  66. serializer.loads(bad)
  67. assert exc_info.value.original_error is not None
  68. def test_loads_unsafe(self, serializer: Serializer, value: Any):
  69. signed = serializer.dumps(value)
  70. assert serializer.loads_unsafe(signed) == (True, value)
  71. bad_signed = signed[:-1]
  72. assert serializer.loads_unsafe(bad_signed) == (False, value)
  73. payload = signed.rsplit(coerce_str(signed, "."), 1)[0] # type: ignore
  74. bad_payload = serializer.make_signer().sign(payload[:-1])[:-1]
  75. assert serializer.loads_unsafe(bad_payload) == (False, None)
  76. class BadUnsign(serializer.signer): # type: ignore
  77. def unsign(self, signed_value, *args, **kwargs):
  78. try:
  79. return super().unsign(signed_value, *args, **kwargs)
  80. except BadSignature as e:
  81. e.payload = None
  82. raise
  83. serializer.signer = BadUnsign
  84. assert serializer.loads_unsafe(bad_signed) == (False, None)
  85. def test_file(self, serializer: Serializer, value: Any):
  86. f = cast(
  87. IO, BytesIO() if isinstance(serializer.dumps(value), bytes) else StringIO()
  88. )
  89. serializer.dump(value, f)
  90. f.seek(0)
  91. assert serializer.load(f) == value
  92. f.seek(0)
  93. assert serializer.load_unsafe(f) == (True, value)
  94. def test_alt_salt(self, serializer: Serializer, value: Any):
  95. signed = serializer.dumps(value, salt="other")
  96. with pytest.raises(BadSignature):
  97. serializer.loads(signed)
  98. assert serializer.loads(signed, salt="other") == value
  99. def test_signer_cls(self, serializer_factory, serializer: Serializer, value: Any):
  100. class Other(serializer.signer): # type: ignore
  101. default_key_derivation = "hmac"
  102. other = serializer_factory(signer=Other)
  103. assert other.loads(other.dumps(value)) == value
  104. assert other.dumps(value) != serializer.dumps(value)
  105. def test_signer_kwargs(
  106. self, serializer_factory, serializer: Serializer, value: Any
  107. ):
  108. other = serializer_factory(signer_kwargs={"key_derivation": "hmac"})
  109. assert other.loads(other.dumps(value)) == value
  110. assert other.dumps("value") != serializer.dumps("value")
  111. def test_serializer_kwargs(self, serializer_factory):
  112. serializer = serializer_factory(serializer_kwargs={"skipkeys": True})
  113. try:
  114. serializer.serializer.dumps(None, skipkeys=True)
  115. except TypeError:
  116. return
  117. assert serializer.loads(serializer.dumps({(): 1})) == {}
  118. def test_fallback_signers(self, serializer_factory, value: Any):
  119. serializer = serializer_factory(signer_kwargs={"digest_method": hashlib.sha256})
  120. signed = serializer.dumps(value)
  121. fallback_serializer = serializer_factory(
  122. signer_kwargs={"digest_method": hashlib.sha1},
  123. fallback_signers=[{"digest_method": hashlib.sha256}],
  124. )
  125. assert fallback_serializer.loads(signed) == value
  126. def test_iter_unsigners(self, serializer: Serializer, serializer_factory):
  127. class Signer256(serializer.signer): # type: ignore
  128. default_digest_method = hashlib.sha256
  129. serializer = serializer_factory(
  130. secret_key="secret_key",
  131. fallback_signers=[
  132. {"digest_method": hashlib.sha256},
  133. (Signer, {"digest_method": hashlib.sha256}),
  134. Signer256,
  135. ],
  136. )
  137. unsigners = serializer.iter_unsigners()
  138. assert next(unsigners).digest_method == _lazy_sha1
  139. for signer in unsigners:
  140. assert signer.digest_method == hashlib.sha256
  141. def test_digests():
  142. factory = partial(Serializer, secret_key="dev key", salt="dev salt")
  143. default_value = factory(signer_kwargs={}).dumps([42])
  144. sha1_value = factory(signer_kwargs={"digest_method": hashlib.sha1}).dumps([42])
  145. sha512_value = factory(signer_kwargs={"digest_method": hashlib.sha512}).dumps([42])
  146. assert default_value == sha1_value
  147. assert sha1_value == "[42].-9cNi0CxsSB3hZPNCe9a2eEs1ZM"
  148. assert sha512_value == (
  149. "[42].MKCz_0nXQqv7wKpfHZcRtJRmpT2T5uvs9YQsJEhJimqxc"
  150. "9bCLxG31QzS5uC8OVBI1i6jyOLAFNoKaF5ckO9L5Q"
  151. )