Skip to content

Agentic session (COPILOT_AGENT_SESSION_ID) makes az account get-access-token launch interactive browser login on silent-token failure #34211

Closed

Description

Describe the bug

With a non-empty COPILOT_AGENT_SESSION_ID, which Copilot agent hosts set for the shells they start, any UserCredential.acquire_token call whose silent result makes check_result raise AuthenticationError enters the interactive authentication fallback, even for non-SSH requests such as az account get-access-token. Without the variable, the same failure returns the error and an az login hint.

Cause, in src/azure-cli-core/azure/cli/core/auth/msal_credentials.py, UserCredential.acquire_token:

  1. The agentic-session block (added with agentic_session.py) always sets kwargs["data"]["client_session"] = agentic_session_id.
  2. On AuthenticationError, the existing fallback uses 'data' in kwargs to detect VM SSH (az ssh):
    if 'data' in kwargs:
        logger.warning(ex)
        result = self._acquire_token_interactive(scopes, **kwargs)
    else:
        raise
    az account get-access-token reaches this through Profile.get_raw_token, which calls cred.acquire_token(scopes) without data. Agentic mode now always populates data, so this branch fires for any such failing request. The code's own comment says non-SSH scenarios should "not launch browser, but show the error message and az login command instead."

This code is unchanged on the current dev branch.

Impact in practice: tools that shell out to az run it non-interactively with a timeout; here that was .NET Azure.Identity 1.21.0 AzureCliCredential via DefaultAzureCredential. Each affected failing call attempts interactive authentication and opens a browser sign-in tab. When the SDK times out it kills the process it launched, but the Python process kept running (PPID 1) with a 127.0.0.1 listening socket (see Additional context). A test suite making five such calls per run left orphans in bursts of five; we found 55 orphaned az account get-access-token Python processes on one machine.

Related command

az account get-access-token --output json --resource https://cognitiveservices.azure.com --tenant <tenant-id>

(this is exactly what Azure.Identity's AzureCliCredential runs)

Errors

With COPILOT_AGENT_SESSION_ID unset, the command fails fast as expected:

ERROR: AADSTS530004: AcceptCompliantDevice setting isn't configured for this organization. The admin needs to configure this setting to allow external users access to protected resources. ...
Run the command below to authenticate interactively; additional arguments may be added as needed:
az logout
az login --tenant "<tenant-id>" --scope "https://cognitiveservices.azure.com/.default"

With it set, the command does not exit with the authentication error. It logs the error as a warning and enters interactive authentication. With BROWSER=/usr/bin/true the process stayed running with a Python LISTEN socket on 127.0.0.1:<port>; without it, the default browser opens a sign-in page.

Issue script & Debug output

Repro needs a signed-in user account for which silent token acquisition fails in the target tenant (e.g. a guest/external account blocked by Conditional Access, or any interaction_required / MFA claims case). BROWSER=/usr/bin/true stops a real browser opening but still shows the interactive flow starting.

TENANT='<tenant-id>'   # replace with a real tenant ID
R=https://cognitiveservices.azure.com

# 1. Expected behaviour: fails immediately with AADSTS... and the `az login` hint
env -u COPILOT_AGENT_SESSION_ID az account get-access-token --resource $R --tenant $TENANT

# 2. Bug: starts interactive auth-code flow and hangs
COPILOT_AGENT_SESSION_ID=test BROWSER=/usr/bin/true \
  az account get-access-token --resource $R --tenant $TENANT --debug
# in another shell: lsof -nP -iTCP -sTCP:LISTEN | grep -i python   -> 127.0.0.1:<port>

Expected behavior

Agentic-session mode should not change the failure behaviour. A failed silent token request outside az ssh should raise the AuthenticationError with the az login hint, exactly as without COPILOT_AGENT_SESSION_ID. In particular, az account get-access-token, which is called by SDK credentials in non-interactive contexts, should never open a browser.

Suggested fix: detect the SSH case explicitly instead of relying on 'data' in kwargs. The SSH path supplies a data dict containing token_type: "ssh-cert" (plus req_cnf and key_id), so the fallback could check (kwargs.get("data") or {}).get("token_type") == "ssh-cert". A smaller fix is to record whether the caller supplied data before the agentic block adds client_session, though that keeps the older, broader heuristic.

Environment Summary

azure-cli          2.90.0 (Homebrew)
msal               1.36.0
Python             3.14.7
OS                 macOS 27.0.1 (arm64)
COPILOT_AGENT_SESSION_ID set by the GitHub Copilot agent host

Additional context

  • Related, separate: Homebrew's az wrapper (.../bin/az) runs python -Im azure.cli "$@" without exec, which adds a shell process between the caller and Python. Terminating only that shell can leave Python running. .NET Azure.Identity launches az through /bin/sh -c and calls Process.Kill() without killing the process tree, which is what we observed. Using exec in the wrapper would remove this layer, though full cleanup also depends on how the caller launches and terminates the process.
  • Workaround for affected users: unset COPILOT_AGENT_SESSION_ID for SDK/test processes, or make sure the default az account can get tokens silently for the tenants it is asked about.

Activity

  1. yonzhan commented on Oct 11, 2026

    @yonzhan
    Collaborator

    Thank you for opening this issue, we will look into it.

  2. added
    customer-reported
    Auto-Assign
    ARM
    Azure CLI Team
    question
    Account
    Service Attention
    on Oct 11, 2026
  3. added this to the Backlog milestone on Oct 11, 2026
  4. removed
    Service Attention
    on Oct 11, 2026
  5. 5 remaining items

  6. microsoft-github-policy-service commented on Oct 13, 2026

    @microsoft-github-policy-service
    Contributor

    🔔 Routing this issue to @Azure/act-observability-squad.

  7. isra-fel commented on Oct 13, 2026

    @isra-fel
    Member

    Though I couldn't reproduce this easily (requires a tenant that could trigger a MFA failure) the root cause analysis looks legit to me. Thanks for reporting!

  8. added
    Request X Engineering Agent
    on Oct 14, 2026
  9. microsoft-github-policy-service commented on Oct 14, 2026

    @microsoft-github-policy-service
    Contributor

    🔔 Routing this issue to @Azure/act-identity-squad.

  10. added
    Request X Engineering Agent
    and removed
    Request X Engineering Agent
    on Oct 14, 2026
  11. microsoft-github-policy-service commented on Oct 14, 2026

    @microsoft-github-policy-service
    Contributor

    🔔 Routing this issue to @Azure/act-identity-squad.

  12. x-engineering-agent commented on Oct 14, 2026

    @x-engineering-agent
    Contributor

    X Engineering Agent Bug analysis: Root cause · low confidence

    Confidence: Low (0.40)

    Summary

    In an agentic session, failed non-SSH access-token acquisition enters browser authentication instead of preserving AuthenticationError and login guidance.

    🔬 Likely root cause

    Agent-session metadata creates kwargs[data], invalidating the data-presence heuristic used to recognize SSH-certificate requests in the AuthenticationError fallback.

    Affected code
    • src/azure-cli-core/azure/cli/core/auth/msal_credentials.py › UserCredential.acquire_token
    • src/azure-cli-core/azure/cli/core/_profile.py › Profile.get_raw_token (line 418)
    • src/azure-cli-core/azure/cli/core/auth/tests/test_agentic_session.py › TestUserCredentialAgenticSession
    🚫 Ruled out
    • Configuration: Conditional Access can explain silent acquisition failure, but does not justify treating an ordinary access-token request as an SSH certificate request.
    • Environment: The wrong branch is in shared Python credential logic, independent of macOS/Homebrew; shell-wrapper and process cleanup concerns are separate.
    • Intended behavior: The SSH-only fallback comment and maintainer confirmation exclude interactive authentication for ordinary get-access-token failures.
    🛠️ Proposed change

    Identify SSH certificate requests by the explicit token_type=ssh-cert marker rather than data presence. Preserve agent-session metadata, broker claims, cache behavior, genuine SSH interactive fallback and ordinary AuthenticationError/login guidance.

    Workaround

    Unset COPILOT_AGENT_SESSION_ID only for affected SDK/test subprocesses when acceptable; this avoids the mistaken fallback but does not fix the underlying authentication failure.

    🔬 Technical details

    Evidence

    • UserCredential.acquire_token adds client_session to data and params when COPILOT_AGENT_SESSION_ID is set; its AuthenticationError handler then treats any data key as SSH and invokes _acquire_token_interactive.
    • Profile.get_raw_token calls cred.acquire_token(scopes) without caller data. Profile.get_msal_token is the SSH-certificate entry point; the SSH extension supplies token_type=ssh-cert.
    • The existing TestUserCredentialAgenticSession exercises successful mocked MSAL acquisition, not the AuthenticationError branch. Maintainer feedback explicitly says get-access-token should not trigger browser fallback.

    Test plan

    Add mocked failure-path tests in auth/tests/test_agentic_session.py: session unset/set, broker off/on, ordinary and unrelated data must propagate AuthenticationError without interactive calls; explicit SSH certificate data must retain fallback. Assert metadata and guidance, and cover Profile.get_raw_token failure. No Azure recordings are needed for these deterministic credential-unit regressions; tenant-specific live behavior remains unverified.

    Generated code: Handwritten code. The root cause is azure-cli-core/auth/msal_credentials.py, outside generated AAZ output.

    Out of scope: Homebrew wrapper exec semantics and SDK process-tree cleanup are separate changes.

    🔁 Live reproduction (BAMI sandbox) — Inconclusive

    Verdict: Inconclusive: the sandbox could not run the reproduction to the end.
    Reason: the sandbox identity cannot sign in to or access the resources involved.
    The analysis above is based on reading the code only, so its confidence is capped at low.

    Commands ran in an isolated Azure sandbox subscription from a validated ReproSpec; output is redacted.

    X Engineering Agent · Fixer · react 👍 / 👎 to train the agent

  13. removed
    Request X Engineering Agent
    on Oct 19, 2026
  14. krschau commented on Nov 3, 2026

    @krschau
    Contributor

    I hit this during az login, not only get-access-token. I used a multi-tenant account where one tenant blocks sign-in through Conditional Access (AADSTS53003), with COPILOT_AGENT_SESSION_ID set.

    Expected:  find_using_specific_tenant catches the AuthenticationError, warns, and moves on to the next tenant (_profile.py#L850-L859).

    Actual: the agentic block injects data, so 'data' in kwargs is true and the silent failure launches a second interactive sign-in for the blocked tenant (msal_credentials.py#L53-L96).

    I agree with the proposed approach of identifying VM SSH by  token_type . Both  az ssh  ( azext_ssh/custom.py ) and  az sftp ( azext_sftp/file_utils.py ) send  data={"token_type": "ssh-cert", ...}. This is what I tested locally:

    +        is_vm_ssh = (kwargs.get('data') or {}).get('token_type') == 'ssh-cert'
    +
             # Apply agentic session parameters for user identity flows
     ...
    -            if 'data' in kwargs:
    +            if is_vm_ssh:
    

    The check reads the caller's data before the agentic injection, so it doesn't depend on client_session being added. With this patch, az login warns for the blocked tenant and finishes successfully. I can open a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

ARMAccountAuto-AssignAzure CLI Teamact-identity-squadbugcustomer-reported

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions