From 8a37076844da7de61a88071440612a63cac2c7f2 Mon Sep 17 00:00:00 2001 From: Filip Andonie <47191006+Filip1x9@users.noreply.github.com> Date: Wed, 28 Aug 2024 10:28:46 +0100 Subject: [PATCH] fix: race-condition on token request close to expiry (#102) --- src/fds/sdk/utils/authentication/confidential.py | 2 +- src/fds/sdk/utils/authentication/constants.py | 1 + tests/fds/sdk/utils/authentication/test_confidential.py | 6 +++--- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/fds/sdk/utils/authentication/confidential.py b/src/fds/sdk/utils/authentication/confidential.py index 0146f84..52d42e7 100644 --- a/src/fds/sdk/utils/authentication/confidential.py +++ b/src/fds/sdk/utils/authentication/confidential.py @@ -242,7 +242,7 @@ def _is_cached_token_valid(self) -> bool: if not self._cached_token: log.debug("Access Token cache is empty") return False - if time.time() < self._cached_token[CONSTS.TOKEN_EXPIRES_AT]: + if time.time() < self._cached_token[CONSTS.TOKEN_EXPIRES_AT] - CONSTS.TOKEN_EXPIRY_OFFSET_SECS: return True else: log.debug("Cached access token has expired at %s", self._cached_token[CONSTS.TOKEN_EXPIRES_AT]) diff --git a/src/fds/sdk/utils/authentication/constants.py b/src/fds/sdk/utils/authentication/constants.py index 413a0b7..aaf9133 100644 --- a/src/fds/sdk/utils/authentication/constants.py +++ b/src/fds/sdk/utils/authentication/constants.py @@ -14,6 +14,7 @@ class CONSTS: # access token TOKEN_ACCESS_TOKEN = "access_token" TOKEN_EXPIRES_AT = "expires_at" + TOKEN_EXPIRY_OFFSET_SECS = 30 # config CONFIG_CLIENT_ID = "clientId" diff --git a/tests/fds/sdk/utils/authentication/test_confidential.py b/tests/fds/sdk/utils/authentication/test_confidential.py index 56c9382..4b533b9 100644 --- a/tests/fds/sdk/utils/authentication/test_confidential.py +++ b/tests/fds/sdk/utils/authentication/test_confidential.py @@ -409,7 +409,7 @@ def test_get_access_token_cached(example_config, mocker, caplog): mock_oauth2_session = mocker.patch("fds.sdk.utils.authentication.confidential.OAuth2Session") mock_oauth2_session.return_value.fetch_token.return_value = { "access_token": "test", - "expires_at": 10, + "expires_at": 40, } mocker.patch("fds.sdk.utils.authentication.confidential.time.time", return_value=0) @@ -418,7 +418,7 @@ def test_get_access_token_cached(example_config, mocker, caplog): assert client.get_access_token() == client.get_access_token() mock_oauth2_session.return_value.fetch_token.assert_called_once() - assert "Retrieving cached token. Expires in '10' seconds" in caplog.text + assert "Retrieving cached token. Expires in '40' seconds" in caplog.text def test_get_access_token_cache_expired(client, mocker, caplog): @@ -428,7 +428,7 @@ def test_get_access_token_cache_expired(client, mocker, caplog): "fds.sdk.utils.authentication.confidential.OAuth2Session.fetch_token", return_value={ "access_token": "test", - "expires_at": 10, + "expires_at": 30, }, )