Add support for extract_timestamp in MultiFernet (#11427)

Co-authored-by: Max Melamed <max.melamed@Whatnot6Y5J36W2.lan>
This commit is contained in:
maxmelamed 2024-08-13 11:42:35 -04:00 committed by GitHub
parent 7fda121e69
commit df8e11b95d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 41 additions and 0 deletions

View file

@ -10,6 +10,8 @@ Changelog
* Enforce the :rfc:`5280` requirement that extended key usage extensions must
not be empty.
* Added support for timestamp extraction to the
:class:`~cryptography.fernet.MultiFernet` class.
.. _v43-0-0:

View file

@ -213,3 +213,11 @@ class MultiFernet:
except InvalidToken:
pass
raise InvalidToken
def extract_timestamp(self, msg: bytes | str) -> int:
for f in self._fernets:
try:
return f.extract_timestamp(msg)
except InvalidToken:
pass
raise InvalidToken

View file

@ -277,3 +277,34 @@ class TestMultiFernet:
with pytest.raises(InvalidToken):
mf2.rotate(mf1.encrypt(b"abc"))
def test_extract_timestamp_first_fernet_valid_token(self, backend):
f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
mf1 = MultiFernet([f1])
current_time = 1526138327
token = mf1.encrypt_at_time(b"encrypt me", current_time)
assert mf1.extract_timestamp(token) == current_time
def test_extract_timestamp_second_fernet_valid_token(self, backend):
f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend)
mf1 = MultiFernet([f1, f2])
current_time = 1526138327
token = f2.encrypt_at_time(b"encrypt me", current_time)
assert mf1.extract_timestamp(token) == current_time
def test_extract_timestamp_invalid_token(self, backend):
f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
mf1 = MultiFernet([f1])
with pytest.raises(InvalidToken):
mf1.extract_timestamp(b"nonsensetoken")
with pytest.raises(InvalidToken):
mf1.extract_timestamp(b"\x80abc")
with pytest.raises(InvalidToken):
mf1.extract_timestamp(b"\x00")
with pytest.raises(InvalidToken):
mf1.extract_timestamp("nonsensetoken")
with pytest.raises(InvalidToken):
mf1.extract_timestamp("abc")
with pytest.raises(InvalidToken):
mf1.extract_timestamp("")