From cd681f40732f0ce9e80919b54d697879b8be7698 Mon Sep 17 00:00:00 2001 From: rumaisa a Date: Mon, 9 Nov 2026 17:21:00 +0530 Subject: [PATCH 1/2] fix: create persisted token cache files as 0600 The python -m msal tester saves its token cache to msal_cache.bin in the current directory with open(..., "w"), so the file holding refresh tokens is created 0644 under the usual umask, and an existing file is reused with whatever mode and owner it already has. The SerializableTokenCache docstring recipe has the same open() call. Create the tester's file with mode 0600 and fchmod it before writing, and create the recipe's file with mode 0600. --- msal/__main__.py | 16 +++++++++----- msal/token_cache.py | 4 +++- tests/test_main.py | 54 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 6 deletions(-) create mode 100644 tests/test_main.py diff --git a/msal/__main__.py b/msal/__main__.py index 24fe85e6..82bd2b07 100644 --- a/msal/__main__.py +++ b/msal/__main__.py @@ -14,11 +14,17 @@ _token_cache_filename = "msal_cache.bin" global_cache = msal.SerializableTokenCache() -atexit.register(lambda: - open(_token_cache_filename, "w").write(global_cache.serialize()) - # Hint: The following optional line persists only when state changed - if global_cache.has_state_changed else None - ) + +def _save_cache(): + if global_cache.has_state_changed: # Persists only when state changed + # The cache contains refresh tokens, so only its owner may read it + fd = os.open( + _token_cache_filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as f: + if hasattr(os, "fchmod"): # Also covers a file that already existed + os.fchmod(fd, 0o600) + f.write(global_cache.serialize()) +atexit.register(_save_cache) _AZURE_CLI = "04b07795-8ddb-461a-bbee-02f9e1bf7b46" _VISUAL_STUDIO = "04f0c124-f2bc-4f59-8241-bf6df9866bbd" diff --git a/msal/token_cache.py b/msal/token_cache.py index 128bf7ca..607d24b1 100644 --- a/msal/token_cache.py +++ b/msal/token_cache.py @@ -601,7 +601,9 @@ class SerializableTokenCache(TokenCache): if os.path.exists(cache_filename): cache.deserialize(open(cache_filename, "r").read()) atexit.register(lambda: - open(cache_filename, "w").write(cache.serialize()) + open( # Readable only by its owner, because it contains refresh tokens + os.open(cache_filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), + "w").write(cache.serialize()) # Hint: The following optional line persists only when state changed if cache.has_state_changed else None ) diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 00000000..921045c3 --- /dev/null +++ b/tests/test_main.py @@ -0,0 +1,54 @@ +import os +import stat +import sys +import tempfile +from unittest.mock import patch + +import msal +from tests import unittest +from tests.test_token_cache import build_response + + +@unittest.skipIf(sys.platform == "win32", "File mode bits are POSIX-specific") +class TestTesterTokenCacheFile(unittest.TestCase): + """The ``python -m msal`` tester persists refresh tokens into its cwd""" + + @classmethod + def setUpClass(cls): + with patch("builtins.input", return_value=""): # Its DEBUG log prompt + from msal import __main__ as tester + cls.tester = tester + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.addCleanup(os.chdir, os.getcwd()) + os.chdir(tmp.name) + cache = msal.SerializableTokenCache() + cache.add({ + "client_id": "my_app", + "scope": ["s1"], + "token_endpoint": "https://login.example.com/contoso/oauth2/v2.0/token", + "response": build_response( + uid="uid", utid="utid", access_token="an AT", + refresh_token="a RT"), + }) + patcher = patch.object(self.tester, "global_cache", cache) + patcher.start() + self.addCleanup(patcher.stop) + + def assertCacheFileIsOwnerOnly(self): + self.tester._save_cache() + filename = self.tester._token_cache_filename + self.assertEqual(0o600, stat.S_IMODE(os.stat(filename).st_mode)) + with open(filename) as f: + self.assertIn("a RT", f.read()) + + def test_new_cache_file_should_be_owner_only(self): + self.addCleanup(os.umask, os.umask(0o022)) # A common default umask + self.assertCacheFileIsOwnerOnly() + + def test_existing_cache_file_should_become_owner_only(self): + open(self.tester._token_cache_filename, "w").close() + os.chmod(self.tester._token_cache_filename, 0o644) # Left by older versions + self.assertCacheFileIsOwnerOnly() From f69fb3799956a94416199c606f24e044abc26b8a Mon Sep 17 00:00:00 2001 From: rumaisa a Date: Wed, 25 Nov 2026 22:27:15 +0530 Subject: [PATCH 2/2] fix: truncate the cache only after it is owner-only, and tighten it in the recipe too --- msal/__main__.py | 4 ++-- msal/token_cache.py | 17 +++++++++++------ tests/test_main.py | 10 ++++++++++ 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/msal/__main__.py b/msal/__main__.py index 82bd2b07..971cda94 100644 --- a/msal/__main__.py +++ b/msal/__main__.py @@ -18,11 +18,11 @@ def _save_cache(): if global_cache.has_state_changed: # Persists only when state changed # The cache contains refresh tokens, so only its owner may read it - fd = os.open( - _token_cache_filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + fd = os.open(_token_cache_filename, os.O_WRONLY | os.O_CREAT, 0o600) with os.fdopen(fd, "w") as f: if hasattr(os, "fchmod"): # Also covers a file that already existed os.fchmod(fd, 0o600) + f.truncate(0) # Only once the file is known to be owner-only f.write(global_cache.serialize()) atexit.register(_save_cache) diff --git a/msal/token_cache.py b/msal/token_cache.py index 607d24b1..1ef8f7fa 100644 --- a/msal/token_cache.py +++ b/msal/token_cache.py @@ -600,13 +600,18 @@ class SerializableTokenCache(TokenCache): cache = msal.SerializableTokenCache() if os.path.exists(cache_filename): cache.deserialize(open(cache_filename, "r").read()) - atexit.register(lambda: - open( # Readable only by its owner, because it contains refresh tokens - os.open(cache_filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), - "w").write(cache.serialize()) + def save_cache(): # Hint: The following optional line persists only when state changed - if cache.has_state_changed else None - ) + if not cache.has_state_changed: + return + # The cache contains refresh tokens, so only its owner may read it + fd = os.open(cache_filename, os.O_WRONLY | os.O_CREAT, 0o600) + with os.fdopen(fd, "w") as f: + if hasattr(os, "fchmod"): # Also tightens a pre-existing file + os.fchmod(fd, 0o600) + f.truncate(0) # Only once the file is known to be owner-only + f.write(cache.serialize()) + atexit.register(save_cache) app = msal.ClientApplication(..., token_cache=cache) ... diff --git a/tests/test_main.py b/tests/test_main.py index 921045c3..178fba85 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -52,3 +52,13 @@ def test_existing_cache_file_should_become_owner_only(self): open(self.tester._token_cache_filename, "w").close() os.chmod(self.tester._token_cache_filename, 0o644) # Left by older versions self.assertCacheFileIsOwnerOnly() + + def test_unchmodable_cache_file_should_keep_its_content(self): + filename = self.tester._token_cache_filename + with open(filename, "w") as f: # A cache owned by somebody else + f.write("previous content") + with patch("os.fchmod", side_effect=PermissionError): + with self.assertRaises(PermissionError): + self.tester._save_cache() + with open(filename) as f: + self.assertEqual("previous content", f.read())