test_serializer.py 6.1 KB

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