Skip to content

Connect Azure DevOps with the Azure CLI without a PAT - #6735

Open
brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/issue-6073-azure-devops-cli
Open

brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/issue-6073-azure-devops-cli

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

What changes

Adds an Azure CLI (az) authentication path for Azure DevOps so users can connect without a Personal Access Token. PATs are often restricted or forbidden in Azure DevOps orgs (the issue notes Microsoft's own docs discourage them).

When no ORCA_AZURE_DEVOPS_* token/PAT env var is set, Orca mints a short-lived Azure DevOps OAuth token from the locally signed-in az session (az account get-access-token --resource <Azure DevOps GUID>) and uses it as a Bearer token for the existing REST calls — PR/branch review status and Create PR.

This follows the existing CLI-provider pattern (gh for GitHub, glab for GitLab).

What does NOT change (boundaries)

  • az is a token source only — Orca does not shell out to az repos/az devops for PR data; the existing REST client is unchanged.
  • Env-var PAT/token keeps priority. A configured PAT/token always wins and is never overridden by an ambient az login (which could point at a different identity/org). No behavior change for existing PAT users.
  • Local-only token acquisition. The token is minted on the local machine (same as env vars are read today). Remote/SSH az sessions and WSL az are intentionally out of scope — using them would create a status/REST split-brain. No regression for SSH PAT users.
  • No new settings, no telemetry, no new dependencies.

Closes #6073

Design approach

The seam is the auth layer in src/main/azure-devops/. A new az-cli-token.ts module mints + caches the token; resolveAzureDevOpsAuth({ allowAzCli }) layers it underneath the env config (env access-token → env PAT → az token → none). The REST read path (requestAzureDevOpsJsonAtBase), the create-PR path, the create-PR auth gate (isAzureDevOpsReviewCreationAuthenticated, now async), and the auth-status/preflight surface all consume the resolver. Provider-specific behavior stays behind the existing 'azure-devops' checks.

Cold-start protection: the heavier token mint is gated behind a cheap local isCommandAvailable('az') probe (run in parallel with the existing gh/glab probes). Machines with no az or with an env token pay no extra subprocess. The token is cached in-process (honoring expires_on with a 60s safety margin, a 5-min unknown-expiry fallback, and a 30s negative cache), with a shared in-flight promise so concurrent status polls trigger at most one spawn. The Re-check button clears the cache so a fresh az login is picked up immediately.

Design-review outcome

Ran Brennan's design-review loop (Claude + Codex in parallel, 3 iterations to clean). Notable catch: an early design would have let the env-base-URL status path bypass the cold-start gate and still spawn az; the gate was moved to the resolver's spawn site (allowAzCli) so it can't be bypassed. Also corrected an honest limitation about account-name display (below).

Implementation & deviations

Implemented as designed. The duplicate auth helpers in pull-request-creation.ts were consolidated to import from azure-devops-api-request.ts (single source of truth for authHeaders/resolver). One honest boundary: in the global Integrations card, the az-only case (no env base URL) shows the integration as configured but with a blank account name — the global status path has no org base URL to call /_apis/connectionData. The signed-in account name does surface on per-repo views and when ORCA_AZURE_DEVOPS_API_BASE_URL is set. We did not add org-base-URL discovery (scope creep).

Completeness verification

Read-only verification pass confirmed COMPLETE — every requirement, edge case, and the critical invariants (no az spawn on cold start with env token / absent az; env-var priority; base-URL resolution unchanged) hold, with file:line evidence.

Headline behavior status

IMPLEMENTED. A user signed into az with no PAT authenticates Azure DevOps PR status and Create-PR via the minted token through the live REST client — not scaffolding/fixture-only. The token flows into the real Authorization header on production paths.

Performance audit

Touched hot path: the 60s PR-status poll (getAzureDevOpsPullRequestForBranch, visibility-gated, capped at 3 worktrees). Audit confirmed: env-token users never spawn az; az-cli users spawn at most once per cache window; concurrent polls share one spawn; the cold-start az --version probe is added to the existing parallel batch (no added wall-clock); the spawn is bounded by a 5s timeout so it can't hang a poll. One LOW finding fixed in-branch: an installed-but-logged-out az (no env token) was re-spawned for every REST call in a poll because negative results weren't cached — added a 30s negative cache (with a deterministic spawn-count regression test). Cache is O(1) (single account-scoped slot), in-flight promise always settles (no leak).

Code-review loop

Ran review-code-fix-loop — 2 rounds, two review-code reviewers in parallel each round. Both reviewers returned clean in the final round (verified the real az account get-access-token JSON shape against Microsoft docs, token never logged, env-priority assertions are real, no async/await ordering bugs). The only nit (untranslated locale fallbacks for the new card sentence) matches the repo's auto-catalog convention and is deferred to the normal localization pass.

Validation (brennan-test-changes): LAND

  • pnpm run typecheck clean; pnpm run lint clean (incl. localization catalog + coverage parity across en/es/ja/ko/zh).
  • Targeted suites green: src/main/azure-devops + src/main/ipc/preflight.test.ts (74), src/renderer/.../settings (487). Logic exercised: token precedence, async create gate, status gating, negative cache, in-flight dedup, expiry/TTL refresh, preflight wiring.
  • Live UI: launched the app, navigated to Settings → Integrations with no Azure env vars; the Azure DevOps card renders the new "Or sign in with the Azure CLI (az login)." copy (monospace az login) in the Not-configured state, 0 console errors. (Screenshot evidence captured locally; not committed per repo policy.)

Manual verification needed (environment lacks az + an Azure DevOps org)

A true end-to-end az login → real PR status / Create-PR cannot run in the build environment (no az, no org). On a machine with az login to an Azure DevOps org and no ORCA_AZURE_DEVOPS_* env vars:

  1. Settings → Integrations: Azure DevOps card should read Connected/configured (account name may be blank unless ORCA_AZURE_DEVOPS_API_BASE_URL is set — see boundary above).
  2. On an Azure DevOps repo: PR/branch review status loads and Create PR succeeds via the minted token.
  3. az logout → Re-check → card drops to Not configured gracefully (no crash/hang).
  4. Set ORCA_AZURE_DEVOPS_TOKEN while also az-logged-in → PAT is used (env priority).

Static checks & tests run

pnpm run typecheck, pnpm run lint, targeted vitest suites (all green). New tests: az-cli-token.test.ts, azure-devops-api-request.test.ts, plus additions to client/pull-request-creation/preflight suites.

Residual risks / accepted gaps

  • az-only global card shows no account name without an env base URL (documented; functional auth still works).
  • No 401-driven proactive cache invalidation (covered by the TTL with 60s margin + negative cache).
  • Remote/SSH/WSL az token acquisition out of scope (follow-up).

Made with Orca 🐋

Add an Azure CLI (az) authentication path for Azure DevOps so users can
connect without a Personal Access Token, which is often restricted or
forbidden. When no ORCA_AZURE_DEVOPS_* token/PAT env var is set, Orca
mints a short-lived Azure DevOps OAuth token from the locally signed-in
`az` session (az account get-access-token) and uses it as a Bearer token
for the existing REST calls — PR/branch review status and Create PR.

This follows the existing CLI-provider pattern (gh for GitHub, glab for
GitLab): az is used only as a token source, not for PR data. Env-var
PAT/token keeps priority and is never overridden by an ambient az login.
The token is cached in-process (honoring expiry, with a short negative
cache) and the az probe is gated behind local availability so non-Azure
cold starts pay no extra subprocess.

Closes #6073

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

A new az-cli-token.ts module is added that runs az account get-access-token to retrieve an Azure DevOps OAuth token, with in-memory caching, negative-result caching, and concurrent-call deduplication. resolveAzureDevOpsAuth is introduced in azure-devops-api-request.ts to resolve credentials in priority order: env token, env PAT, then az CLI. getAzureDevOpsAuthStatus gains a localAzAvailable option; isAzureDevOpsReviewCreationAuthenticated becomes async; PR creation switches to resolveAzureDevOpsAuth. The preflight probe now checks az availability and passes it to the auth status call, resetting the az CLI cache on forced refresh. The settings UI adds az login guidance with new i18n strings in all supported locales.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: Azure DevOps auth via Azure CLI instead of a PAT.
Description check ✅ Passed It covers the required content in substance, including summary, testing, AI review, security, and notes, even though headings differ from the template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 4

🧹 Nitpick comments (1)
src/main/azure-devops/pull-request-creation.test.ts (1)

154-157: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the exact az CLI token in the request header.

/^Bearer / would also pass for Bearer undefined; checking the mocked token catches parsing/header propagation regressions.

Proposed test tightening
       const headers = init?.headers as Record<string, string>
-      expect(headers.Authorization).toMatch(/^Bearer /)
+      expect(headers.Authorization).toBe('Bearer az-token')
       return Response.json({

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 214a7b70-6f7f-4eb3-8372-c38157f2d6c4

📥 Commits

Reviewing files that changed from the base of the PR and between d877d94 and 83343ee.

📒 Files selected for processing (17)
  • src/main/azure-devops/az-cli-token.test.ts
  • src/main/azure-devops/az-cli-token.ts
  • src/main/azure-devops/azure-devops-api-request.test.ts
  • src/main/azure-devops/azure-devops-api-request.ts
  • src/main/azure-devops/client.test.ts
  • src/main/azure-devops/client.ts
  • src/main/azure-devops/pull-request-creation.test.ts
  • src/main/azure-devops/pull-request-creation.ts
  • src/main/ipc/preflight.test.ts
  • src/main/ipc/preflight.ts
  • src/main/source-control/hosted-review-creation.ts
  • src/renderer/src/components/settings/token-source-control-integration-cards.tsx
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json

Comment on lines +59 to +76
inFlightTokenRequest = acquireAzCliToken().then((token) => {
cachedResult = token
hasCachedResult = true
if (token) {
cacheUsableUntilMs =
token.expiresAtMs === null
? Date.now() + UNKNOWN_EXPIRY_CACHE_MS
: token.expiresAtMs - EXPIRY_SAFETY_MS
} else {
cacheUsableUntilMs = Date.now() + NEGATIVE_CACHE_MS
}
return token
})

try {
return await inFlightTokenRequest
} finally {
inFlightTokenRequest = null

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Ignore stale in-flight results after _resetAzCliTokenCache().

_resetAzCliTokenCache() clears the shared refs, but any older acquireAzCliToken().then(...) callback still writes into cachedResult afterward. In the forced re-check flow from src/main/ipc/preflight.ts:225-247, a pre-login request can therefore resolve after the reset and overwrite a freshly acquired token with a cached null result for another 30 seconds.

Suggested fix
 let cachedResult: AzCliToken | null = null
 let hasCachedResult = false
 let cacheUsableUntilMs = 0
 let inFlightTokenRequest: Promise<AzCliToken | null> | null = null
+let cacheGeneration = 0
@@
 export async function getAzureDevOpsAzCliAccessToken(): Promise<AzCliToken | null> {
   const now = Date.now()
   if (hasCachedResult && now < cacheUsableUntilMs) {
     return cachedResult
   }
   if (inFlightTokenRequest) {
     return inFlightTokenRequest
   }
 
+  const generation = cacheGeneration
   inFlightTokenRequest = acquireAzCliToken().then((token) => {
+    if (generation !== cacheGeneration) {
+      return token
+    }
     cachedResult = token
     hasCachedResult = true
     if (token) {
@@
 export function _resetAzCliTokenCache(): void {
+  cacheGeneration += 1
   cachedResult = null
   hasCachedResult = false
   cacheUsableUntilMs = 0
   inFlightTokenRequest = null
 }

Also applies to: 80-84

Comment on lines 29 to +35
beforeEach(() => {
process.env = { ...OLD_ENV, ORCA_AZURE_DEVOPS_TOKEN: 'pat-token' }
gitExecFileAsyncMock.mockReset()
execLocalPreflightCommandMock.mockReset()
isCommandAvailableMock.mockReset()
_resetAzureDevOpsRepoRefCache()
_resetAzCliTokenCache()

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Sanitize Azure DevOps auth env in test setup.

OLD_ENV can carry ORCA_AZURE_DEVOPS_ACCESS_TOKEN, which the resolver prefers over the default PAT and can make tests depend on the developer’s shell.

Proposed deterministic setup
   beforeEach(() => {
-    process.env = { ...OLD_ENV, ORCA_AZURE_DEVOPS_TOKEN: 'pat-token' }
+    process.env = { ...OLD_ENV }
+    delete process.env.ORCA_AZURE_DEVOPS_ACCESS_TOKEN
+    delete process.env.ORCA_AZURE_DEVOPS_PAT
+    process.env.ORCA_AZURE_DEVOPS_TOKEN = 'pat-token'
     gitExecFileAsyncMock.mockReset()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
beforeEach(() => {
process.env = { ...OLD_ENV, ORCA_AZURE_DEVOPS_TOKEN: 'pat-token' }
gitExecFileAsyncMock.mockReset()
execLocalPreflightCommandMock.mockReset()
isCommandAvailableMock.mockReset()
_resetAzureDevOpsRepoRefCache()
_resetAzCliTokenCache()
beforeEach(() => {
process.env = { ...OLD_ENV }
delete process.env.ORCA_AZURE_DEVOPS_ACCESS_TOKEN
delete process.env.ORCA_AZURE_DEVOPS_PAT
process.env.ORCA_AZURE_DEVOPS_TOKEN = 'pat-token'
gitExecFileAsyncMock.mockReset()
execLocalPreflightCommandMock.mockReset()
isCommandAvailableMock.mockReset()
_resetAzureDevOpsRepoRefCache()
_resetAzCliTokenCache()

code: 'auth_required',
error:
'Create PR failed: Azure DevOps is not authenticated. Next step: set ORCA_AZURE_DEVOPS_TOKEN in this environment.'
'Create PR failed: Azure DevOps is not authenticated. Next step: set ORCA_AZURE_DEVOPS_TOKEN or sign in with the Azure CLI (az login).'

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Mention all supported Azure DevOps env auth variables.

The resolver accepts ORCA_AZURE_DEVOPS_TOKEN, ORCA_AZURE_DEVOPS_PAT, and ORCA_AZURE_DEVOPS_ACCESS_TOKEN; this error only points users to one of them.

Proposed copy update
-        'Create PR failed: Azure DevOps is not authenticated. Next step: set ORCA_AZURE_DEVOPS_TOKEN or sign in with the Azure CLI (az login).'
+        'Create PR failed: Azure DevOps is not authenticated. Next step: set ORCA_AZURE_DEVOPS_TOKEN, ORCA_AZURE_DEVOPS_PAT, or ORCA_AZURE_DEVOPS_ACCESS_TOKEN, or sign in with the Azure CLI (az login).'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
'Create PR failed: Azure DevOps is not authenticated. Next step: set ORCA_AZURE_DEVOPS_TOKEN or sign in with the Azure CLI (az login).'
'Create PR failed: Azure DevOps is not authenticated. Next step: set ORCA_AZURE_DEVOPS_TOKEN, ORCA_AZURE_DEVOPS_PAT, or ORCA_AZURE_DEVOPS_ACCESS_TOKEN, or sign in with the Azure CLI (az login).'

Comment on lines +213 to +224
{translate(
'auto.components.settings.token.source.control.integration.cards.9c4a0c82e7',
' Or sign in with the Azure CLI'
)}{' '}
(
<span className="font-mono text-[11px]">
{translate(
'auto.components.settings.token.source.control.integration.cards.a58e8fa2b9',
'az login'
)}
</span>
).

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Point the new Azure CLI path at Azure CLI docs.

Line 213 adds az login as a first-class setup option, but the card’s Learn more action for the not-configured state still sends users to the PAT/token article. That leaves the new path without any discoverable follow-up guidance from this screen.

@JoeEarly

Copy link
Copy Markdown

@nwparker Would you mind reviewing this one

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Azure Devops - integrate via azure cli

2 participants