Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
197 changes: 197 additions & 0 deletions src/main/azure-devops/az-cli-access-token.test.ts
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)
})
})
100 changes: 100 additions & 0 deletions src/main/azure-devops/az-cli-access-token.ts
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
}
}
Comment thread
yoyoys marked this conversation as resolved.
Resolved

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')
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

export function _resetAzCliAccessTokenCacheForTests(): void {
cached = null
failedAtMs = null
inFlight = null
}
22 changes: 22 additions & 0 deletions src/main/azure-devops/az-cli-invocation.ts
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
}
Loading