Skip to content

Commit 02f7618

Browse files
Shira SassoonCopilot
andcommitted
fix: clear token cache on set_azure_cli to prevent stale cross-tenant tokens
When transitioning from no stored tenant to a stored tenant, set_tenant() did not call logout() (only triggers on tenant mismatch). This left stale cached tokens from the previous no-tenant session. Now set_azure_cli() always clears _azure_cli_token_cache at the start of every login. Adds regression test verifying cache is cleared on no-tenant → tenant-B. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent f560488 commit 02f7618

2 files changed

Lines changed: 26 additions & 0 deletions

File tree

src/fabric_cli/core/fab_auth.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,9 @@ def set_azure_cli(self, tenant_id=None):
436436
from Azure CLI's active session via 'az account show'.
437437
Always forces a fresh query (bypasses cache) since this is a login action.
438438
"""
439+
# Clear token cache on every login to prevent stale tokens from a
440+
# previous tenant (or no-tenant) session from being reused.
441+
self._azure_cli_token_cache.clear()
439442
# Set tenant first — set_tenant() may call logout() which clears auth info
440443
if tenant_id:
441444
self.set_tenant(tenant_id)

tests/test_core/test_fab_auth_azure_cli.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,29 @@ def test_identity_type_preserved_after_tenant_change(
542542
assert auth.get_identity_type() == "azure_cli"
543543
assert auth.get_tenant_id() == "tenant-B"
544544

545+
@patch("fabric_cli.core.fab_auth.AzureCliCredential")
546+
def test_login_clears_token_cache_from_no_tenant_state(
547+
self, mock_credential_class, temp_dir_fixture
548+
):
549+
"""set_azure_cli should clear token cache even when transitioning from no tenant."""
550+
mock_token = MagicMock()
551+
mock_token.token = "stale-token"
552+
mock_token.expires_on = int(time.time()) + 3600
553+
554+
mock_credential = MagicMock()
555+
mock_credential.get_token.return_value = mock_token
556+
mock_credential_class.return_value = mock_credential
557+
558+
auth = FabAuth()
559+
auth.set_access_mode("azure_cli")
560+
# Acquire a token with no tenant stored
561+
auth._acquire_token_from_azure_cli(con.SCOPE_FABRIC_DEFAULT)
562+
assert auth._azure_cli_token_cache.get(con.SCOPE_FABRIC_DEFAULT[0]) is not None
563+
564+
# Login with explicit tenant — cache must be cleared
565+
auth.set_azure_cli(tenant_id="new-tenant")
566+
assert auth._azure_cli_token_cache.get(con.SCOPE_FABRIC_DEFAULT[0]) is None
567+
545568

546569
class TestAzureCliTenantDiscoveryFailures:
547570
"""Test _get_azure_cli_tenant failure paths."""

0 commit comments

Comments
 (0)