Skip to content

[Profile] az login: Support automatic OIDC federated token refresh - #34495

Closed
MaddyMicrosoft wants to merge 15 commits into
devfrom
maddy/oidc-refresh-from-fork
Closed

MaddyMicrosoft wants to merge 15 commits into
devfrom
maddy/oidc-refresh-from-fork

Conversation

@MaddyMicrosoft

@MaddyMicrosoft MaddyMicrosoft commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

🤖 PR Validation — ⚠️ Review suggested

Breaking Changes Tests Suppressions
⚠️ None 🔄 130/130 ️✔️ None
⚠️AzureCLI-BreakingChangeTest
⚠️profile
rule cmd_name rule_message suggest_message
⚠️ 1006 - ParaAdd login cmd login added parameter federated_identity
⚠️ 1006 - ParaAdd login cmd login added parameter federated_token_callback

PR Title

[Profile] az login: Support automatic OIDC federated token refresh

PR Body

Related command
az login

Description
This PR adds automatic OIDC federated token refresh support for az login so long-running CI/CD jobs don't fail with AADSTS700024 after the initial assertion expires.

What changed

  1. Added provider-based refresh mode for service principal login:
    • --federated-identity (supports GitHub and Azure DevOps token retrieval paths)
  2. Added BYO refresh mode:
    • --federated-token-callback (alias: --federated-token-cmd) to fetch a fresh assertion from a user-provided command
  3. Added/updated login validation:
    • service-principal-only enforcement for federated refresh modes
    • mutual exclusion checks for incompatible auth options
  4. Hardened refresh implementation:
    • callback command runs without shell interpretation
    • explicit HTTP timeout and clearer network error paths for provider token requests
    • thread-safe callback invocation for concurrent token requests
  5. Added/updated tests for:
    • provider dispatch and provider-specific token fetch
    • callback parsing/execution behavior and failure paths
    • timeout and error handling
    • callback thread-safety behavior

Effect

az login can now refresh federated assertions on demand during later token acquisitions, improving reliability for long-running OIDC-based automation.

Testing Guide

Local validation (argument guards):

# service principal only guard
.\.venv\Scripts\python.exe -m azure.cli login --federated-identity

# incompatible combination guard
.\.venv\Scripts\python.exe -m azure.cli login --service-principal -u x -t y --federated-identity --password z

# mutual exclusion between static federated token and callback
.\.venv\Scripts\python.exe -m azure.cli login --service-principal -u x -t y --federated-token a --federated-token-callback "echo b"

Live GitHub Actions E2E validation:

- Login using federated identity succeeds at T+0
- Wait past initial assertion lifetime (~10–12 minutes)
- Token acquisition succeeds after wait (no AADSTS700024)
- Sustained multi-refresh scenario also succeeds

This checklist is used to make sure that common guidelines for a pull request are followed.

- [x] The PR title and description has followed the guideline in [Submitting Pull Requests](https://github.com/Azure/azure-cli/tree/dev/doc/authoring_command_modules#submitting-pull-requests).

- [x] I adhere to the [Command Guidelines](https://github.com/Azure/azure-cli/blob/dev/doc/command_guidelines.md).

- [x] I adhere to the [Error Handling Guidelines](https://github.com/Azure/azure-cli/blob/dev/doc/error_handling_guidelines.md).

MaddyMicrosoft and others added 15 commits October 9, 2026 01:56
… federated tokens

Static `--federated-token` values expire in ~10 minutes and cannot be refreshed,
so long-running CI/CD tasks fail with `AADSTS700024: Client assertion is not
within its valid time range`.

This registers a callable client_assertion with MSAL (the documented, recommended
interface) so an expired OIDC ID token is transparently re-fetched on every token
acquisition, including in later `az` processes. Wiring:

- New `FEDERATED_IDENTITY` sentinel persisted as the SP entry's client_assertion.
- `ServicePrincipalAuth.get_msal_client_credential()` resolves that sentinel to a
  provider dispatcher, `get_federated_id_token()`, instead of a static string.
- Dispatcher implements GitHub Actions; other environments raise a clear error
  pointing at `--federated-token`. Azure DevOps is a planned follow-up (#28708).
- New `az login --federated-identity` flag, mutually exclusive with
  `--federated-token` and only valid with `--service-principal`.

Adds unit tests covering the sentinel-to-callable resolution, the GitHub fetch
(success and HTTP error), and the unsupported/no-provider branches.

Partially addresses #28708

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…token refresh

Extends `--federated-identity` (GitHub Actions only) to also refresh OIDC federated
tokens on Azure DevOps Pipelines, so long-running pipeline tasks no longer fail with
`AADSTS700024`.

The provider dispatcher now detects Azure DevOps and POSTs to the pipeline oidctoken
API, following the documented Azure DevOps / azure-identity `AzurePipelinesCredential`
contract. Because the refresh runs in a later `az` process, the three required inputs
are read from the environment:

- request URL:  ARM_OIDC_REQUEST_URL, else SYSTEM_OIDCREQUESTURI
- access token: ARM_OIDC_REQUEST_TOKEN, else SYSTEM_ACCESSTOKEN (System.AccessToken)
- service conn: ARM_OIDC_AZURE_SERVICE_CONNECTION_ID

Missing variables produce a clear, actionable error. Adds unit tests for the Azure
DevOps success path, missing-environment handling, and updates the help text.

Partially addresses #28708

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…oken refresh

Adds a provider-agnostic escape hatch alongside the built-in `--federated-identity`
providers. `--federated-token-callback <command>` takes any command that prints a
fresh OIDC token to stdout; Azure CLI wraps it as the MSAL client_assertion callable
and re-runs it on demand, so token refresh works with any CI/CD system (not just the
built-in GitHub Actions / Azure DevOps providers) without platform-specific logic in
the CLI.

- The command is persisted (client_assertion_callback) so later `az` processes rebuild
  the callable and refresh independently.
- Mutually exclusive with --federated-token and --federated-identity; service principal
  only. Clear errors on non-zero exit or empty output. The token value is never logged.

The three flags now cover the full spectrum: static token (--federated-token),
built-in providers (--federated-identity), and universal callback
(--federated-token-callback).

Partially addresses #28708

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Harden --federated-token-callback: parse the command into an argv list and run it
  without a shell (shell=False), so a tampered token cache cannot become arbitrary
  code execution. Users needing pipes/redirection use a script or wrap in bash -c.
- Reject combining --federated-token/--federated-identity/--federated-token-callback
  with --password or --certificate (previously the secret silently won and refresh
  was silently disabled).
- Fix the GitHub OIDC request URL to append the audience with the correct separator
  when the URL has no existing query string.
- Correct the misleading --service-principal usage error to list all credential modes.
- Align --federated-identity help text with the actual mutual-exclusion validation.
- Add tests for the no-shell argv behavior and the query-less GitHub URL case.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…on-length linter

The --federated-token-callback option (26 chars) exceeds azure-cli's 22-char
option-length threshold, so add the shorter --federated-token-cmd alias.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Per MSAL guidance, the client_assertion callback must be thread-safe because
concurrent token requests may invoke it simultaneously. Serialize the provider
dispatcher (get_federated_id_token) and the command-based callback with locks so
overlapping refreshes cannot race (duplicate HTTP fetch / subprocess run). Adds a
concurrency test asserting the callback never executes overlapping invocations.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Code-review follow-ups on the OIDC token-refresh feature:

- Add an explicit connect/read timeout to the GitHub Actions and Azure DevOps OIDC
  token requests via a shared _oidc_http_request helper. Without it, a stalled
  connection would hang token acquisition (and, for --federated-identity, every
  concurrent refresh thread holding the lock) indefinitely on a long-running CI job.
  Timeout and connection failures now raise a clear CLIError.
- Parse the --federated-token-callback command with POSIX rules on every platform.
  The previous posix=False path on Windows left literal quote characters in argv, so a
  quoted argument containing spaces (e.g. an audience) reached the program corrupted.
  POSIX parsing handles quoting correctly and consistently; the Windows backslash
  caveat is documented in the help text and docstring.

Adds tests for the request timeout path and quoted-argument parsing.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
… federated tokens

Static `--federated-token` values expire in ~10 minutes and cannot be refreshed,
so long-running CI/CD tasks fail with `AADSTS700024: Client assertion is not
within its valid time range`.

This registers a callable client_assertion with MSAL (the documented, recommended
interface) so an expired OIDC ID token is transparently re-fetched on every token
acquisition, including in later `az` processes. Wiring:

- New `FEDERATED_IDENTITY` sentinel persisted as the SP entry's client_assertion.
- `ServicePrincipalAuth.get_msal_client_credential()` resolves that sentinel to a
  provider dispatcher, `get_federated_id_token()`, instead of a static string.
- Dispatcher implements GitHub Actions; other environments raise a clear error
  pointing at `--federated-token`. Azure DevOps is a planned follow-up (#28708).
- New `az login --federated-identity` flag, mutually exclusive with
  `--federated-token` and only valid with `--service-principal`.

Adds unit tests covering the sentinel-to-callable resolution, the GitHub fetch
(success and HTTP error), and the unsupported/no-provider branches.

Partially addresses #28708

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…token refresh

Extends `--federated-identity` (GitHub Actions only) to also refresh OIDC federated
tokens on Azure DevOps Pipelines, so long-running pipeline tasks no longer fail with
`AADSTS700024`.

The provider dispatcher now detects Azure DevOps and POSTs to the pipeline oidctoken
API, following the documented Azure DevOps / azure-identity `AzurePipelinesCredential`
contract. Because the refresh runs in a later `az` process, the three required inputs
are read from the environment:

- request URL:  ARM_OIDC_REQUEST_URL, else SYSTEM_OIDCREQUESTURI
- access token: ARM_OIDC_REQUEST_TOKEN, else SYSTEM_ACCESSTOKEN (System.AccessToken)
- service conn: ARM_OIDC_AZURE_SERVICE_CONNECTION_ID

Missing variables produce a clear, actionable error. Adds unit tests for the Azure
DevOps success path, missing-environment handling, and updates the help text.

Partially addresses #28708

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…oken refresh

Adds a provider-agnostic escape hatch alongside the built-in `--federated-identity`
providers. `--federated-token-callback <command>` takes any command that prints a
fresh OIDC token to stdout; Azure CLI wraps it as the MSAL client_assertion callable
and re-runs it on demand, so token refresh works with any CI/CD system (not just the
built-in GitHub Actions / Azure DevOps providers) without platform-specific logic in
the CLI.

- The command is persisted (client_assertion_callback) so later `az` processes rebuild
  the callable and refresh independently.
- Mutually exclusive with --federated-token and --federated-identity; service principal
  only. Clear errors on non-zero exit or empty output. The token value is never logged.

The three flags now cover the full spectrum: static token (--federated-token),
built-in providers (--federated-identity), and universal callback
(--federated-token-callback).

Partially addresses #28708

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Harden --federated-token-callback: parse the command into an argv list and run it
  without a shell (shell=False), so a tampered token cache cannot become arbitrary
  code execution. Users needing pipes/redirection use a script or wrap in bash -c.
- Reject combining --federated-token/--federated-identity/--federated-token-callback
  with --password or --certificate (previously the secret silently won and refresh
  was silently disabled).
- Fix the GitHub OIDC request URL to append the audience with the correct separator
  when the URL has no existing query string.
- Correct the misleading --service-principal usage error to list all credential modes.
- Align --federated-identity help text with the actual mutual-exclusion validation.
- Add tests for the no-shell argv behavior and the query-less GitHub URL case.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…on-length linter

The --federated-token-callback option (26 chars) exceeds azure-cli's 22-char
option-length threshold, so add the shorter --federated-token-cmd alias.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Per MSAL guidance, the client_assertion callback must be thread-safe because
concurrent token requests may invoke it simultaneously. Serialize the provider
dispatcher (get_federated_id_token) and the command-based callback with locks so
overlapping refreshes cannot race (duplicate HTTP fetch / subprocess run). Adds a
concurrency test asserting the callback never executes overlapping invocations.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Code-review follow-ups on the OIDC token-refresh feature:

- Add an explicit connect/read timeout to the GitHub Actions and Azure DevOps OIDC
  token requests via a shared _oidc_http_request helper. Without it, a stalled
  connection would hang token acquisition (and, for --federated-identity, every
  concurrent refresh thread holding the lock) indefinitely on a long-running CI job.
  Timeout and connection failures now raise a clear CLIError.
- Parse the --federated-token-callback command with POSIX rules on every platform.
  The previous posix=False path on Windows left literal quote characters in argv, so a
  quoted argument containing spaces (e.g. an audience) reached the program corrupted.
  POSIX parsing handles quoting correctly and consistently; the Windows backslash
  caveat is documented in the help text and docstring.

Adds tests for the request timeout path and quoted-argument parsing.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 25, 2026 03:38

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The callback implementation permits execution of an untrusted executable during authentication and credential leakage through error reporting, while malformed callback quoting produces an internal failure instead of a usage error.

3 open issues
What changed in this PR

Adds on-demand OIDC assertion refresh to service-principal az login, helping long-running CI/CD jobs continue authenticating after the initial assertion expires.

Changes:

  • Adds provider-based refresh for GitHub Actions and Azure DevOps, plus a user-command callback mode.
  • Validates incompatible login options and persists refresh configuration for later CLI processes.
  • Adds HTTP timeouts, serialized callback execution, and tests for credential handling and provider requests.
File Description
src/​azure-cli/​azure/​cli/​command_modules/​profile/​custom.py Validates refresh options and passes them into service-principal credentials.
src/​azure-cli/​azure/​cli/​command_modules/​profile/​__init__.py Registers refresh flags, callback alias, and help text.
src/​azure-cli-core/​azure/​cli/​core/​auth/​tests/​test_identity.py Tests persistence, provider requests, callback execution, and concurrency.
src/​azure-cli-core/​azure/​cli/​core/​auth/​identity.py Implements provider token retrieval and persisted refresh callbacks.

Review effort: Balanced

import subprocess
with lock:
try:
result = subprocess.run(args, capture_output=True, text=True, check=True)
Comment on lines +656 to +657
raise CLIError('--federated-token-callback command exited with code {}: {}'.format(
ex.returncode, (ex.stderr or '').strip()))
import shlex
# POSIX parsing on every platform so quoted arguments containing spaces are handled correctly and
# consistently. The trade-off is that backslashes are escape characters (see the Windows note above).
args = shlex.split(command, posix=True)
@yonzhan

Copy link
Copy Markdown
Collaborator

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@MaddyMicrosoft
MaddyMicrosoft deleted the maddy/oidc-refresh-from-fork branch November 25, 2026 05:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants