diff --git a/tests/test_api.py b/tests/test_api.py index e6e2f6c..65facd9 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -6,6 +6,15 @@ from unittest.mock import MagicMock +def test_is_valid(): + now = time.time() + assert not zign.api.is_valid({}) + assert not zign.api.is_valid({'creation_time': now - 3610, 'expires_in': 3600}) + assert zign.api.is_valid({'creation_time': now - 100, 'expires_in': 600}) + # still valid for 2 minutes, but we only return tokens valid for at least 5 more minutes + assert not zign.api.is_valid({'creation_time': now - 3480, 'expires_in': 3600}) + + def test_get_new_token_auth_fail(monkeypatch): response = MagicMock(status_code=401) monkeypatch.setattr('requests.get', MagicMock(return_value=response)) diff --git a/zign/api.py b/zign/api.py index 09a463b..e2725c6 100644 --- a/zign/api.py +++ b/zign/api.py @@ -10,6 +10,8 @@ from .config import KEYRING_KEY, TOKENS_FILE_PATH +TOKEN_MINIMUM_VALIDITY_SECONDS = 60*5 # 5 minutes + class ServerError(Exception): def __init__(self, message): @@ -150,7 +152,7 @@ def get_named_token(scope, realm, name, user, password, url=None, def is_valid(token: dict): now = time.time() - return token and now < (token.get('creation_time', 0) + token.get('expires_in', 0)) + return token and now < (token.get('creation_time', 0) + token.get('expires_in', 0) - TOKEN_MINIMUM_VALIDITY_SECONDS) def is_user_scope(scope: str):