test(auth): token tests clearer about timezone assumptions

This commit is contained in:
Houkime 2023-11-10 17:40:52 +00:00
parent dd6f37a17d
commit 1bbb804919
3 changed files with 14 additions and 6 deletions

View file

@ -22,7 +22,7 @@ class NewDeviceKey(BaseModel):
def is_valid(self) -> bool:
"""
Check if the recovery key is valid.
Check if key is valid.
"""
if is_past(self.expires_at):
return False
@ -30,7 +30,7 @@ class NewDeviceKey(BaseModel):
def as_mnemonic(self) -> str:
"""
Get the recovery key as a mnemonic.
Get the key as a mnemonic.
"""
return Mnemonic(language="english").to_mnemonic(bytes.fromhex(self.key))

View file

@ -47,6 +47,7 @@ class RecoveryKey(BaseModel):
) -> "RecoveryKey":
"""
Factory to generate a random token.
If passed naive time as expiration, assumes utc
"""
creation_date = datetime.now(timezone.utc)
if expiration is not None:

View file

@ -1,18 +1,25 @@
import pytest
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
from selfprivacy_api.models.tokens.recovery_key import RecoveryKey
from selfprivacy_api.models.tokens.new_device_key import NewDeviceKey
def test_recovery_key_expired():
expiration = datetime.now() - timedelta(minutes=5)
def test_recovery_key_expired_utcnaive():
expiration = datetime.utcnow() - timedelta(minutes=5)
key = RecoveryKey.generate(expiration=expiration, uses_left=2)
assert not key.is_valid()
def test_recovery_key_expired_tzaware():
expiration = datetime.now(timezone.utc) - timedelta(minutes=5)
key = RecoveryKey.generate(expiration=expiration, uses_left=2)
assert not key.is_valid()
def test_new_device_key_expired():
expiration = datetime.now() - timedelta(minutes=5)
# key is supposed to be tzaware
expiration = datetime.now(timezone.utc) - timedelta(minutes=5)
key = NewDeviceKey.generate()
key.expires_at = expiration
assert not key.is_valid()