From 2d77d611d826815bf4f691fb9033b6f6186bcdf6 Mon Sep 17 00:00:00 2001 From: Zoheb Shaikh Date: Thu, 12 Dec 2024 15:48:21 +0000 Subject: [PATCH] Fix auth token saving (#753) resolve a bug in file saving The environment variable `XDG_CONFIG_HOME` contains a directory not a file path. So adding a file name in front of directory path to get a writable location --- src/blueapi/service/authentication.py | 16 ++++++++-------- tests/unit_tests/service/test_authentication.py | 13 +++++++++---- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/blueapi/service/authentication.py b/src/blueapi/service/authentication.py index d9c6d2d4a..df3df8a25 100644 --- a/src/blueapi/service/authentication.py +++ b/src/blueapi/service/authentication.py @@ -18,7 +18,7 @@ from blueapi.config import OIDCConfig from blueapi.service.model import Cache -BLUEAPI_CACHE_LOCATION = "~/.cache/blueapi_cache" +DEFAULT_CAHCE_DIR = "~/.cache/" SCOPES = "openid offline_access" @@ -33,7 +33,9 @@ def delete_cache(self) -> None: ... class SessionCacheManager(CacheManager): def __init__(self, token_path: Path | None) -> None: - self._token_path: Path = token_path if token_path else self._get_xdg_cache_dir() + self._token_path: Path = ( + token_path if token_path else self._default_token_cache_path() + ) @cached_property def _file_path(self) -> str: @@ -54,14 +56,12 @@ def load_cache(self) -> Cache: def delete_cache(self) -> None: Path(self._file_path).unlink(missing_ok=True) - def _get_xdg_cache_dir(self) -> Path: + def _default_token_cache_path(self) -> Path: """ - Return the XDG cache directory. + Return the default cache file path. """ - cache_dir = os.environ.get("XDG_CACHE_HOME") - if not cache_dir: - cache_dir = os.path.expanduser(BLUEAPI_CACHE_LOCATION) - return Path(cache_dir) + cache_path = os.environ.get("XDG_CACHE_HOME", DEFAULT_CAHCE_DIR) + return Path(cache_path).expanduser() / "blueapi_cache" class SessionManager: diff --git a/tests/unit_tests/service/test_authentication.py b/tests/unit_tests/service/test_authentication.py index f464b286a..94c489b03 100644 --- a/tests/unit_tests/service/test_authentication.py +++ b/tests/unit_tests/service/test_authentication.py @@ -10,10 +10,7 @@ from blueapi.config import OIDCConfig from blueapi.service import main -from blueapi.service.authentication import ( - SessionCacheManager, - SessionManager, -) +from blueapi.service.authentication import SessionCacheManager, SessionManager @pytest.fixture @@ -132,3 +129,11 @@ def test_processes_valid_token( ): inner = main.verify_access_token(oidc_config) inner(access_token=valid_token_with_jwt["access_token"]) + + +def test_session_cache_manager_returns_writable_file_path(tmp_path): + os.environ["XDG_CACHE_HOME"] = str(tmp_path) + cache = SessionCacheManager(token_path=None) + Path(cache._file_path).touch() + assert os.path.isfile(cache._file_path) + assert cache._file_path == f"{tmp_path}/blueapi_cache"