Repository navigation
Connect Azure DevOps with the Azure CLI without a PAT - #6735
brennanb2025 wants to merge 1 commit into
Conversation
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]>
📝 WalkthroughWalkthroughA new 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
|
@coderabbitai review |
✅ Action performedReview finished.
|
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
src/main/azure-devops/pull-request-creation.test.ts (1)
154-157: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert the exact az CLI token in the request header.
/^Bearer /would also pass forBearer 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
📒 Files selected for processing (17)
src/main/azure-devops/az-cli-token.test.tssrc/main/azure-devops/az-cli-token.tssrc/main/azure-devops/azure-devops-api-request.test.tssrc/main/azure-devops/azure-devops-api-request.tssrc/main/azure-devops/client.test.tssrc/main/azure-devops/client.tssrc/main/azure-devops/pull-request-creation.test.tssrc/main/azure-devops/pull-request-creation.tssrc/main/ipc/preflight.test.tssrc/main/ipc/preflight.tssrc/main/source-control/hosted-review-creation.tssrc/renderer/src/components/settings/token-source-control-integration-cards.tsxsrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/i18n/locales/es.jsonsrc/renderer/src/i18n/locales/ja.jsonsrc/renderer/src/i18n/locales/ko.jsonsrc/renderer/src/i18n/locales/zh.json
| 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 |
There was a problem hiding this comment.
🩺 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
| beforeEach(() => { | ||
| process.env = { ...OLD_ENV, ORCA_AZURE_DEVOPS_TOKEN: 'pat-token' } | ||
| gitExecFileAsyncMock.mockReset() | ||
| execLocalPreflightCommandMock.mockReset() | ||
| isCommandAvailableMock.mockReset() | ||
| _resetAzureDevOpsRepoRefCache() | ||
| _resetAzCliTokenCache() |
There was a problem hiding this comment.
🩺 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.
| 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).' |
There was a problem hiding this comment.
🎯 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.
| '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).' |
| {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> | ||
| ). |
There was a problem hiding this comment.
🎯 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.
|
@nwparker Would you mind reviewing this one |
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-inazsession (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 (
ghfor GitHub,glabfor GitLab).What does NOT change (boundaries)
azis a token source only — Orca does not shell out toaz repos/az devopsfor PR data; the existing REST client is unchanged.az login(which could point at a different identity/org). No behavior change for existing PAT users.azsessions and WSLazare intentionally out of scope — using them would create a status/REST split-brain. No regression for SSH PAT users.Closes #6073
Design approach
The seam is the auth layer in
src/main/azure-devops/. A newaz-cli-token.tsmodule mints + caches the token;resolveAzureDevOpsAuth({ allowAzCli })layers it underneath the env config (env access-token → env PAT →aztoken → 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 existinggh/glabprobes). Machines with noazor with an env token pay no extra subprocess. The token is cached in-process (honoringexpires_onwith 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 freshaz loginis 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.tswere consolidated to import fromazure-devops-api-request.ts(single source of truth forauthHeaders/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 whenORCA_AZURE_DEVOPS_API_BASE_URLis 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
azspawn on cold start with env token / absentaz; env-var priority; base-URL resolution unchanged) hold, with file:line evidence.Headline behavior status
IMPLEMENTED. A user signed into
azwith 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 realAuthorizationheader 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 spawnaz; az-cli users spawn at most once per cache window; concurrent polls share one spawn; the cold-startaz --versionprobe 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-outaz(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, tworeview-codereviewers in parallel each round. Both reviewers returned clean in the final round (verified the realaz account get-access-tokenJSON 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): LANDpnpm run typecheckclean;pnpm run lintclean (incl. localization catalog + coverage parity across en/es/ja/ko/zh).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.az login)." copy (monospaceaz 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 (noaz, no org). On a machine withaz loginto an Azure DevOps org and noORCA_AZURE_DEVOPS_*env vars:ORCA_AZURE_DEVOPS_API_BASE_URLis set — see boundary above).az logout→ Re-check → card drops to Not configured gracefully (no crash/hang).ORCA_AZURE_DEVOPS_TOKENwhile alsoaz-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 toclient/pull-request-creation/preflightsuites.Residual risks / accepted gaps
aztoken acquisition out of scope (follow-up).Made with Orca 🐋