Repository navigation
feat(azure-devops): authenticate via az CLI Entra login with token fallback #12201
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+642
−64
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
e0496e7
feat(azure-devops): authenticate via az CLI Entra login with token fa…
yoyoys 04e21ee
fix(azure-devops): dedupe concurrent az spawns and bound token cache …
yoyoys 1d3a4ae
fix(azure-devops): address PR #12201 review findings
yoyoys e5949a0
fix(azure-devops): route the az invocation through runProcess
yoyoys File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,197 @@ | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' | ||
| import { | ||
| _resetAzCliAccessTokenCacheForTests, | ||
| getAzCliAzureDevOpsAccessToken, | ||
| isEntraEligibleAzureDevOpsBaseUrl | ||
| } from './az-cli-access-token' | ||
|
|
||
| const runAzAccessTokenCommandMock = vi.hoisted(() => vi.fn()) | ||
|
|
||
| vi.mock('./az-cli-invocation', () => ({ | ||
| runAzAccessTokenCommand: runAzAccessTokenCommandMock | ||
| })) | ||
|
|
||
| describe('getAzCliAzureDevOpsAccessToken', () => { | ||
| beforeEach(() => { | ||
| runAzAccessTokenCommandMock.mockReset() | ||
| _resetAzCliAccessTokenCacheForTests() | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| vi.useRealTimers() | ||
| }) | ||
|
|
||
| it('returns the access token acquired for the Azure DevOps resource', async () => { | ||
| runAzAccessTokenCommandMock.mockResolvedValue( | ||
| JSON.stringify({ | ||
| accessToken: 'entra-jwt', | ||
| expiresOn: '2999-01-01 00:00:00.000000', | ||
| expires_on: 32472144000, | ||
| subscription: 'sub', | ||
| tenant: 'tenant', | ||
| tokenType: 'Bearer' | ||
| }) | ||
| ) | ||
|
|
||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBe('entra-jwt') | ||
| expect(runAzAccessTokenCommandMock).toHaveBeenCalledWith( | ||
| '499b84ac-1321-427f-aa17-267ca6975798' | ||
| ) | ||
| }) | ||
|
|
||
| it('reuses the cached token until expiry so polling does not respawn az', async () => { | ||
| vi.useFakeTimers() | ||
| vi.setSystemTime(new Date('2026-08-03T00:00:00Z')) | ||
| runAzAccessTokenCommandMock.mockResolvedValue( | ||
| JSON.stringify({ | ||
| accessToken: 'cached-jwt', | ||
| expires_on: Date.parse('2026-08-03T01:00:00Z') / 1000 | ||
| }) | ||
| ) | ||
|
|
||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBe('cached-jwt') | ||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBe('cached-jwt') | ||
| expect(runAzAccessTokenCommandMock).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| it('re-acquires a token once the cached one nears expiry', async () => { | ||
| vi.useFakeTimers() | ||
| vi.setSystemTime(new Date('2026-08-03T00:00:00Z')) | ||
| runAzAccessTokenCommandMock.mockResolvedValueOnce( | ||
| JSON.stringify({ | ||
| accessToken: 'first-jwt', | ||
| expires_on: Date.parse('2026-08-03T01:00:00Z') / 1000 | ||
| }) | ||
| ) | ||
| runAzAccessTokenCommandMock.mockResolvedValueOnce( | ||
| JSON.stringify({ | ||
| accessToken: 'second-jwt', | ||
| expires_on: Date.parse('2026-08-03T02:00:00Z') / 1000 | ||
| }) | ||
| ) | ||
|
|
||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBe('first-jwt') | ||
| // Why: inside the 5-minute expiry margin the token must not be served stale. | ||
| vi.setSystemTime(new Date('2026-08-03T00:56:00Z')) | ||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBe('second-jwt') | ||
| expect(runAzAccessTokenCommandMock).toHaveBeenCalledTimes(2) | ||
| }) | ||
|
|
||
| it('returns null when az is unavailable or not logged in', async () => { | ||
| runAzAccessTokenCommandMock.mockRejectedValue(new Error('spawn az ENOENT')) | ||
|
|
||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBeNull() | ||
| }) | ||
|
|
||
| it('does not respawn az on every call right after a failure', async () => { | ||
| vi.useFakeTimers() | ||
| vi.setSystemTime(new Date('2026-08-03T00:00:00Z')) | ||
| runAzAccessTokenCommandMock.mockRejectedValue(new Error('Please run "az login"')) | ||
|
|
||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBeNull() | ||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBeNull() | ||
| expect(runAzAccessTokenCommandMock).toHaveBeenCalledTimes(1) | ||
|
|
||
| // Why: after the cooldown a fresh az login must be picked up without restarting Orca. | ||
| vi.setSystemTime(new Date('2026-08-03T00:01:01Z')) | ||
| runAzAccessTokenCommandMock.mockResolvedValue( | ||
| JSON.stringify({ | ||
| accessToken: 'recovered-jwt', | ||
| expires_on: Date.parse('2026-08-03T02:00:00Z') / 1000 | ||
| }) | ||
| ) | ||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBe('recovered-jwt') | ||
| }) | ||
|
|
||
| it('shares one az invocation across concurrent callers', async () => { | ||
| let resolveAz: (value: string) => void = () => {} | ||
| runAzAccessTokenCommandMock.mockReturnValue( | ||
| new Promise<string>((resolve) => { | ||
| resolveAz = resolve | ||
| }) | ||
| ) | ||
|
|
||
| const first = getAzCliAzureDevOpsAccessToken() | ||
| const second = getAzCliAzureDevOpsAccessToken() | ||
| resolveAz(JSON.stringify({ accessToken: 'shared-jwt', expires_on: 32472144000 })) | ||
|
|
||
| await expect(first).resolves.toBe('shared-jwt') | ||
| await expect(second).resolves.toBe('shared-jwt') | ||
| expect(runAzAccessTokenCommandMock).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| it('expires tokens from older az versions that only report a local-time expiresOn', async () => { | ||
| vi.useFakeTimers() | ||
| // Why: az's expiresOn has no timezone and Date.parse reads it as local | ||
| // time, so the test clock uses the same zone-less form. | ||
| vi.setSystemTime(new Date('2026-08-03T00:00:00')) | ||
| runAzAccessTokenCommandMock.mockResolvedValueOnce( | ||
| JSON.stringify({ accessToken: 'old-az-jwt', expiresOn: '2026-08-03 01:00:00.000000' }) | ||
| ) | ||
| runAzAccessTokenCommandMock.mockResolvedValueOnce( | ||
| JSON.stringify({ accessToken: 'renewed-jwt', expiresOn: '2026-08-03 02:00:00.000000' }) | ||
| ) | ||
|
|
||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBe('old-az-jwt') | ||
| vi.setSystemTime(new Date('2026-08-03T00:56:00')) | ||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBe('renewed-jwt') | ||
| }) | ||
|
|
||
| it('treats an already-expired token as a failure so the cooldown still applies', async () => { | ||
| vi.useFakeTimers() | ||
| vi.setSystemTime(new Date('2026-08-03T00:00:00Z')) | ||
| runAzAccessTokenCommandMock.mockResolvedValue( | ||
| JSON.stringify({ | ||
| accessToken: 'stale-jwt', | ||
| expires_on: Date.parse('2026-08-02T00:00:00Z') / 1000 | ||
| }) | ||
| ) | ||
|
|
||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBeNull() | ||
| // Why: without the cooldown every sequential poll would respawn az forever. | ||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBeNull() | ||
| expect(runAzAccessTokenCommandMock).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| it('caps the cache lifetime when az reports no parseable expiry at all', async () => { | ||
| vi.useFakeTimers() | ||
| vi.setSystemTime(new Date('2026-08-03T00:00:00Z')) | ||
| runAzAccessTokenCommandMock.mockResolvedValueOnce( | ||
| JSON.stringify({ accessToken: 'unknown-expiry-jwt' }) | ||
| ) | ||
| runAzAccessTokenCommandMock.mockResolvedValueOnce( | ||
| JSON.stringify({ accessToken: 'refetched-jwt' }) | ||
| ) | ||
|
|
||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBe('unknown-expiry-jwt') | ||
| // Why: without an expiry a stale token would otherwise be served forever | ||
| // and every request after Entra's ~1h lifetime would 401 until restart. | ||
| vi.setSystemTime(new Date('2026-08-03T00:31:00Z')) | ||
| await expect(getAzCliAzureDevOpsAccessToken()).resolves.toBe('refetched-jwt') | ||
| }) | ||
| }) | ||
|
|
||
| describe('isEntraEligibleAzureDevOpsBaseUrl', () => { | ||
| it('accepts the hosted Azure DevOps domains', () => { | ||
| expect(isEntraEligibleAzureDevOpsBaseUrl('https://dev.azure.com/acme')).toBe(true) | ||
| expect(isEntraEligibleAzureDevOpsBaseUrl('https://acme.visualstudio.com')).toBe(true) | ||
| }) | ||
|
|
||
| it('rejects on-prem Azure DevOps Server hosts, which do not accept Entra tokens', () => { | ||
| expect(isEntraEligibleAzureDevOpsBaseUrl('https://tfs.corp.example/tfs/Collection')).toBe(false) | ||
| }) | ||
|
|
||
| it('rejects lookalike hosts and malformed URLs', () => { | ||
| expect(isEntraEligibleAzureDevOpsBaseUrl('https://dev.azure.com.evil.example/acme')).toBe(false) | ||
| expect(isEntraEligibleAzureDevOpsBaseUrl('https://notvisualstudio.com')).toBe(false) | ||
| expect(isEntraEligibleAzureDevOpsBaseUrl('not a url')).toBe(false) | ||
| }) | ||
|
|
||
| it('rejects non-HTTPS URLs so a bearer token never travels in cleartext', () => { | ||
| expect(isEntraEligibleAzureDevOpsBaseUrl('http://dev.azure.com/acme')).toBe(false) | ||
| }) | ||
|
|
||
| it('rejects the bare visualstudio.com apex, which is not an Azure DevOps API host', () => { | ||
| expect(isEntraEligibleAzureDevOpsBaseUrl('https://visualstudio.com')).toBe(false) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import { runAzAccessTokenCommand } from './az-cli-invocation' | ||
|
|
||
| /** Azure DevOps' fixed Entra application ID — identical for every tenant. */ | ||
| export const AZURE_DEVOPS_ENTRA_RESOURCE_ID = '499b84ac-1321-427f-aa17-267ca6975798' | ||
|
|
||
| // Why: refresh before Entra's expiry so in-flight requests never carry a token | ||
| // that lapses mid-request. | ||
| const EXPIRY_MARGIN_MS = 5 * 60 * 1000 | ||
|
|
||
| // Why: while az is missing or logged out every poll would otherwise pay a | ||
| // ~1s CLI spawn; back off, but short enough that a fresh `az login` is | ||
| // noticed without restarting Orca. | ||
| const FAILURE_COOLDOWN_MS = 60 * 1000 | ||
|
|
||
| // Why: when az omits every expiry field the token still lapses after Entra's | ||
| // ~1h lifetime; a bounded cache re-acquires instead of serving 401s forever. | ||
| const UNKNOWN_EXPIRY_TTL_MS = 30 * 60 * 1000 | ||
|
|
||
| type CachedToken = { token: string; expiresAtMs: number } | ||
|
|
||
| let cached: CachedToken | null = null | ||
| let failedAtMs: number | null = null | ||
| let inFlight: Promise<string | null> | null = null | ||
|
|
||
| function parseTokenResponse(stdout: string): CachedToken | null { | ||
| const parsed = JSON.parse(stdout) as { | ||
| accessToken?: unknown | ||
| expires_on?: unknown | ||
| expiresOn?: unknown | ||
| } | ||
| if (typeof parsed.accessToken !== 'string') { | ||
| return null | ||
| } | ||
| // Why: expires_on (epoch, UTC) only exists on newer az; older versions emit | ||
| // just expiresOn, a zone-less local-time string that Date.parse reads as local. | ||
| let expiresAtMs = | ||
| typeof parsed.expires_on === 'number' | ||
| ? parsed.expires_on * 1000 | ||
| : typeof parsed.expiresOn === 'string' | ||
| ? Date.parse(parsed.expiresOn) | ||
| : Number.NaN | ||
| if (!Number.isFinite(expiresAtMs)) { | ||
| expiresAtMs = Date.now() + UNKNOWN_EXPIRY_TTL_MS | ||
| } | ||
| return { token: parsed.accessToken, expiresAtMs } | ||
| } | ||
|
|
||
| async function acquireToken(): Promise<string | null> { | ||
| try { | ||
| const stdout = await runAzAccessTokenCommand(AZURE_DEVOPS_ENTRA_RESOURCE_ID) | ||
| cached = parseTokenResponse(stdout) | ||
| // Why: a token already inside the expiry margin would be discarded on the | ||
| // next call; without the cooldown every sequential poll would respawn az. | ||
| if (cached && cached.expiresAtMs - EXPIRY_MARGIN_MS <= Date.now()) { | ||
| cached = null | ||
| } | ||
| failedAtMs = cached ? null : Date.now() | ||
| return cached?.token ?? null | ||
| } catch { | ||
| failedAtMs = Date.now() | ||
| return null | ||
| } | ||
| } | ||
|
|
||
| export function getAzCliAzureDevOpsAccessToken(): Promise<string | null> { | ||
| if (cached && Date.now() < cached.expiresAtMs - EXPIRY_MARGIN_MS) { | ||
| return Promise.resolve(cached.token) | ||
| } | ||
| if (failedAtMs !== null && Date.now() < failedAtMs + FAILURE_COOLDOWN_MS) { | ||
| return Promise.resolve(null) | ||
| } | ||
| // Why: concurrent polls during a cold cache must share one az spawn, not race N. | ||
| inFlight ??= acquireToken().finally(() => { | ||
| inFlight = null | ||
| }) | ||
| return inFlight | ||
| } | ||
|
|
||
| /** Entra tokens only work for the hosted service, never on-prem Azure DevOps Server. */ | ||
| export function isEntraEligibleAzureDevOpsBaseUrl(baseUrl: string): boolean { | ||
| let url: URL | ||
| try { | ||
| url = new URL(baseUrl) | ||
| } catch { | ||
| return false | ||
| } | ||
| // Why: the base URL can come from env or a git remote — never hand a bearer | ||
| // token to a cleartext scheme. | ||
| if (url.protocol !== 'https:') { | ||
| return false | ||
| } | ||
| const host = url.hostname.toLowerCase() | ||
| return host === 'dev.azure.com' || host.endsWith('.visualstudio.com') | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| export function _resetAzCliAccessTokenCacheForTests(): void { | ||
| cached = null | ||
| failedAtMs = null | ||
| inFlight = null | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| import { runProcess } from '../../shared/child-process/run-process' | ||
| import { resolveWindowsCommand } from '../win32-utils' | ||
|
|
||
| // Why: az is a Python CLI — cold starts routinely exceed the API request timeout. | ||
| const AZ_TIMEOUT_MS = 20_000 | ||
|
|
||
| /** Run `az account get-access-token` for an Entra resource; returns raw stdout JSON. */ | ||
| export async function runAzAccessTokenCommand(resource: string): Promise<string> { | ||
| const { code, stdout, stderr, timedOut } = await runProcess({ | ||
| // Why: runProcess spawns without a shell, so Windows needs the resolved | ||
| // path — `az` ships as a .cmd shim that bare-name spawning cannot find. | ||
| program: resolveWindowsCommand('az'), | ||
| args: ['account', 'get-access-token', '--resource', resource, '--output', 'json'], | ||
| timeoutMs: AZ_TIMEOUT_MS | ||
| }) | ||
| // Why: runProcess reports failure in the result; callers cache on a thrown error. | ||
| if (timedOut || code !== 0) { | ||
| const reason = timedOut ? 'timed out' : `exited ${code}` | ||
| throw new Error(`az account get-access-token ${reason}${stderr.trim() ? `: ${stderr.trim()}` : ''}`) | ||
| } | ||
| return stdout | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.