diff --git a/src/main/azure-devops/az-cli-access-token.test.ts b/src/main/azure-devops/az-cli-access-token.test.ts new file mode 100644 index 000000000000..32f6a1051439 --- /dev/null +++ b/src/main/azure-devops/az-cli-access-token.test.ts @@ -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((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) + }) +}) diff --git a/src/main/azure-devops/az-cli-access-token.ts b/src/main/azure-devops/az-cli-access-token.ts new file mode 100644 index 000000000000..a2e2ab6889ed --- /dev/null +++ b/src/main/azure-devops/az-cli-access-token.ts @@ -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 | 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 { + 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 { + 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') +} + +export function _resetAzCliAccessTokenCacheForTests(): void { + cached = null + failedAtMs = null + inFlight = null +} diff --git a/src/main/azure-devops/az-cli-invocation.ts b/src/main/azure-devops/az-cli-invocation.ts new file mode 100644 index 000000000000..7785288a2398 --- /dev/null +++ b/src/main/azure-devops/az-cli-invocation.ts @@ -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 { + 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 +} diff --git a/src/main/azure-devops/azure-devops-api-request.test.ts b/src/main/azure-devops/azure-devops-api-request.test.ts index a804ebcadb03..deb4e82bbef7 100644 --- a/src/main/azure-devops/azure-devops-api-request.test.ts +++ b/src/main/azure-devops/azure-devops-api-request.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { _resetAzCliAccessTokenCacheForTests } from './az-cli-access-token' import { _resetAzureDevOpsPreviewApiVersionCache, requestAzureDevOpsJson, @@ -6,6 +7,12 @@ import { } from './azure-devops-api-request' import type { AzureDevOpsRepoRef } from './repository-ref' +const runAzAccessTokenCommandMock = vi.hoisted(() => vi.fn()) + +vi.mock('./az-cli-invocation', () => ({ + runAzAccessTokenCommand: runAzAccessTokenCommandMock +})) + const OLD_ENV = process.env const OLD_FETCH = globalThis.fetch @@ -37,7 +44,10 @@ describe('Azure DevOps API request (STA-3494)', () => { beforeEach(() => { process.env = { ...OLD_ENV, ORCA_AZURE_DEVOPS_TOKEN: 'pat-token' } delete process.env.ORCA_AZURE_DEVOPS_API_BASE_URL + runAzAccessTokenCommandMock.mockReset() + runAzAccessTokenCommandMock.mockRejectedValue(new Error('az not available')) _resetAzureDevOpsPreviewApiVersionCache() + _resetAzCliAccessTokenCacheForTests() }) afterEach(() => { @@ -132,3 +142,65 @@ describe('Azure DevOps API request (STA-3494)', () => { expect(paths).toEqual(['/rewrite/MyProject/_apis/git/repositories/my-repo']) }) }) + +function fetchCapturingAuthorization(captured: (string | null)[]): typeof fetch { + return vi.fn(async (_input: string | URL | Request, init?: RequestInit) => { + const headers = new Headers(init?.headers) + captured.push(headers.get('Authorization')) + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'Content-Type': 'application/json' } + }) + }) as unknown as typeof fetch +} + +describe('requestAzureDevOpsJsonAtBase auth resolution', () => { + beforeEach(() => { + process.env = { ...OLD_ENV } + delete process.env.ORCA_AZURE_DEVOPS_TOKEN + delete process.env.ORCA_AZURE_DEVOPS_PAT + delete process.env.ORCA_AZURE_DEVOPS_ACCESS_TOKEN + delete process.env.ORCA_AZURE_DEVOPS_USERNAME + runAzAccessTokenCommandMock.mockReset() + _resetAzureDevOpsPreviewApiVersionCache() + _resetAzCliAccessTokenCacheForTests() + }) + + afterEach(() => { + process.env = OLD_ENV + globalThis.fetch = OLD_FETCH + }) + + it('falls back to the az CLI token for hosted Azure DevOps when no env token is set', async () => { + runAzAccessTokenCommandMock.mockResolvedValue( + JSON.stringify({ accessToken: 'entra-jwt', expires_on: 32472144000 }) + ) + const captured: (string | null)[] = [] + globalThis.fetch = fetchCapturingAuthorization(captured) + + await requestAzureDevOpsJsonAtBase('https://dev.azure.com/acme/Project', '/_apis/projects') + + expect(captured).toEqual(['Bearer entra-jwt']) + }) + + it('never invokes az for on-prem Azure DevOps Server base URLs', async () => { + const captured: (string | null)[] = [] + globalThis.fetch = fetchCapturingAuthorization(captured) + + await requestAzureDevOpsJsonAtBase('https://tfs.corp.example/tfs/Collection', '/_apis/projects') + + expect(runAzAccessTokenCommandMock).not.toHaveBeenCalled() + expect(captured).toEqual([null]) + }) + + it('prefers a configured env token over the az CLI', async () => { + process.env.ORCA_AZURE_DEVOPS_TOKEN = 'pat-token' + const captured: (string | null)[] = [] + globalThis.fetch = fetchCapturingAuthorization(captured) + + await requestAzureDevOpsJsonAtBase('https://dev.azure.com/acme/Project', '/_apis/projects') + + expect(runAzAccessTokenCommandMock).not.toHaveBeenCalled() + expect(captured).toEqual([`Basic ${Buffer.from(':pat-token').toString('base64')}`]) + }) +}) diff --git a/src/main/azure-devops/azure-devops-api-request.ts b/src/main/azure-devops/azure-devops-api-request.ts index 03c7faac3f4e..70657fb5d929 100644 --- a/src/main/azure-devops/azure-devops-api-request.ts +++ b/src/main/azure-devops/azure-devops-api-request.ts @@ -1,6 +1,10 @@ import { Buffer } from 'node:buffer' import type { AzureDevOpsRepoRef } from './repository-ref' import { cancelUnreadResponseBody } from '../lib/unread-response-body' +import { + getAzCliAzureDevOpsAccessToken, + isEntraEligibleAzureDevOpsBaseUrl +} from './az-cli-access-token' const REQUEST_TIMEOUT_MS = 5000 const DEFAULT_API_VERSION = '7.1' @@ -77,7 +81,7 @@ export function azureDevOpsTokenConfigured(config: AzureDevOpsAuthConfig): boole return Boolean(config.pat || config.accessToken) } -function authHeaders(config: AzureDevOpsAuthConfig): Record { +function envAuthHeaders(config: AzureDevOpsAuthConfig): Record { if (config.accessToken) { return { Authorization: `Bearer ${config.accessToken}` } } @@ -88,6 +92,26 @@ function authHeaders(config: AzureDevOpsAuthConfig): Record { return {} } +/** + * Env tokens win; otherwise hosted Azure DevOps falls back to the az CLI's + * Entra login. On-prem Azure DevOps Server never tries az — it only accepts + * PAT/Windows auth. + */ +export async function resolveAzureDevOpsAuthHeaders( + baseUrl: string +): Promise> { + const config = getAzureDevOpsAuthConfig() + const fromEnv = envAuthHeaders(config) + if (Object.keys(fromEnv).length > 0) { + return fromEnv + } + if (!isEntraEligibleAzureDevOpsBaseUrl(baseUrl)) { + return {} + } + const token = await getAzCliAzureDevOpsAccessToken() + return token ? { Authorization: `Bearer ${token}` } : {} +} + function isUrlPathAncestor(ancestor: string, descendant: string): boolean { try { const ancestorUrl = new URL(ancestor) @@ -155,12 +179,11 @@ export async function requestAzureDevOpsJsonAtBase( // throws instead of collapsing to null so callers never report false not_found. throwOnFailure = false ): Promise { - const config = getAzureDevOpsAuthConfig() - const doFetch = (url: URL): Promise => + const doFetch = async (url: URL): Promise => fetch(url, { headers: { Accept: 'application/json', - ...authHeaders(config) + ...(await resolveAzureDevOpsAuthHeaders(baseUrl)) }, signal: AbortSignal.timeout(options.timeoutMs ?? REQUEST_TIMEOUT_MS) }) diff --git a/src/main/azure-devops/client.test.ts b/src/main/azure-devops/client.test.ts index 81761bba12f8..f8a76b6a32d2 100644 --- a/src/main/azure-devops/client.test.ts +++ b/src/main/azure-devops/client.test.ts @@ -7,15 +7,21 @@ import { normalizeAzureDevOpsApiBaseUrl } from './client' import { _resetAzureDevOpsPreviewApiVersionCache } from './azure-devops-api-request' +import { _resetAzCliAccessTokenCacheForTests } from './az-cli-access-token' import { _resetAzureDevOpsRepoRefCache } from './repository-ref' import { __resetRepoDefaultBranchCacheForTests } from '../source-control/repo-default-branch' const gitExecFileAsyncMock = vi.hoisted(() => vi.fn()) +const runAzAccessTokenCommandMock = vi.hoisted(() => vi.fn()) vi.mock('../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) +vi.mock('./az-cli-invocation', () => ({ + runAzAccessTokenCommand: runAzAccessTokenCommandMock +})) + /** Serve the remote URL plus the #9171 default-branch resolver probes. */ function primeGitExecWithDefaultBranch(defaultRef = 'refs/remotes/origin/main'): void { gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { @@ -39,8 +45,11 @@ describe('Azure DevOps client', () => { beforeEach(() => { process.env = { ...OLD_ENV, ORCA_AZURE_DEVOPS_TOKEN: 'pat-token' } gitExecFileAsyncMock.mockReset() + runAzAccessTokenCommandMock.mockReset() + runAzAccessTokenCommandMock.mockRejectedValue(new Error('az not available')) _resetAzureDevOpsRepoRefCache() _resetAzureDevOpsPreviewApiVersionCache() + _resetAzCliAccessTokenCacheForTests() __resetRepoDefaultBranchCacheForTests() }) @@ -96,6 +105,30 @@ describe('Azure DevOps client', () => { expect(versions).toEqual(['7.1', '7.1-preview']) }) + it('marks an az CLI login as configured when no env token or base URL is set', async () => { + delete process.env.ORCA_AZURE_DEVOPS_API_BASE_URL + delete process.env.ORCA_AZURE_DEVOPS_TOKEN + runAzAccessTokenCommandMock.mockResolvedValue( + JSON.stringify({ accessToken: 'entra-jwt', expires_on: 32472144000 }) + ) + await expect(getAzureDevOpsAuthStatus()).resolves.toEqual({ + configured: true, + authenticated: false, + account: null, + baseUrl: null, + tokenConfigured: false + }) + }) + + it('stays not configured when neither env tokens nor an az login exist', async () => { + delete process.env.ORCA_AZURE_DEVOPS_API_BASE_URL + delete process.env.ORCA_AZURE_DEVOPS_TOKEN + await expect(getAzureDevOpsAuthStatus()).resolves.toMatchObject({ + configured: false, + authenticated: false + }) + }) + it('resolves a PR for a branch through repository, PR, and status REST calls', async () => { gitExecFileAsyncMock.mockResolvedValue({ stdout: 'https://dev.azure.com/acme/Project/_git/repo\n' diff --git a/src/main/azure-devops/client.ts b/src/main/azure-devops/client.ts index 9ddae9ffe457..838bc133a2fa 100644 --- a/src/main/azure-devops/client.ts +++ b/src/main/azure-devops/client.ts @@ -12,6 +12,7 @@ import { getHostedReviewLocalGitOptions, type HostedReviewExecutionOptions } from '../source-control/hosted-review-git-options' +import { getAzCliAzureDevOpsAccessToken } from './az-cli-access-token' import { azureDevOpsTokenConfigured, getAzureDevOpsAuthConfig, @@ -135,8 +136,11 @@ export async function getAzureDevOpsAuthStatus(): Promise const baseUrl = config.apiBaseUrl ? normalizeAzureDevOpsApiBaseUrl(config.apiBaseUrl) : null const hasToken = azureDevOpsTokenConfigured(config) if (!baseUrl && !hasToken) { + // Why: an az CLI login authenticates hosted orgs without any env setup, so + // it counts as configured even before a repository supplies the base URL. + const azToken = await getAzCliAzureDevOpsAccessToken() return { - configured: false, + configured: azToken !== null, authenticated: false, account: null, baseUrl: null, diff --git a/src/main/azure-devops/pull-request-creation.test.ts b/src/main/azure-devops/pull-request-creation.test.ts index 7cd401747ffc..79adbe72af4a 100644 --- a/src/main/azure-devops/pull-request-creation.test.ts +++ b/src/main/azure-devops/pull-request-creation.test.ts @@ -6,16 +6,24 @@ import { import { _resetAzureDevOpsPreviewApiVersionCache } from './azure-devops-api-request' import { _resetAzureDevOpsRepoRefCache } from './repository-ref' import { REMOTE_URL_PROBE_TIMEOUT_MS } from '../git/remote-url-probe' +import { _resetAzCliAccessTokenCacheForTests } from './az-cli-access-token' -const { gitExecFileAsyncMock, getSshGitProviderMock } = vi.hoisted(() => ({ - gitExecFileAsyncMock: vi.fn(), - getSshGitProviderMock: vi.fn() -})) +const { gitExecFileAsyncMock, getSshGitProviderMock, runAzAccessTokenCommandMock } = vi.hoisted( + () => ({ + gitExecFileAsyncMock: vi.fn(), + getSshGitProviderMock: vi.fn(), + runAzAccessTokenCommandMock: vi.fn() + }) +) vi.mock('../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) +vi.mock('./az-cli-invocation', () => ({ + runAzAccessTokenCommand: runAzAccessTokenCommandMock +})) + vi.mock('../providers/ssh-git-dispatch', () => ({ getSshGitProvider: getSshGitProviderMock, getSshGitProviderGeneration: () => 0 @@ -37,8 +45,11 @@ describe('Azure DevOps pull request creation', () => { stdout: 'https://dev.azure.com/acme/Project/_git/repo\n', stderr: '' }) + runAzAccessTokenCommandMock.mockReset() + runAzAccessTokenCommandMock.mockRejectedValue(new Error('az not available')) _resetAzureDevOpsRepoRefCache() _resetAzureDevOpsPreviewApiVersionCache() + _resetAzCliAccessTokenCacheForTests() }) afterEach(() => { @@ -47,9 +58,78 @@ describe('Azure DevOps pull request creation', () => { _resetAzureDevOpsRepoRefCache() }) - it('treats token-only auth as sufficient for repo-scoped creation', () => { + it('treats token-only auth as sufficient for repo-scoped creation', async () => { delete process.env.ORCA_AZURE_DEVOPS_API_BASE_URL - expect(isAzureDevOpsReviewCreationAuthenticated()).toBe(true) + await expect(isAzureDevOpsReviewCreationAuthenticated('/repo')).resolves.toBe(true) + }) + + it('recognizes an az CLI login as authentication for hosted Azure DevOps repos', async () => { + delete process.env.ORCA_AZURE_DEVOPS_TOKEN + runAzAccessTokenCommandMock.mockResolvedValue( + JSON.stringify({ accessToken: 'entra-jwt', expires_on: 32472144000 }) + ) + + await expect(isAzureDevOpsReviewCreationAuthenticated('/repo')).resolves.toBe(true) + }) + + it('stays unauthenticated without a token when az has no login', async () => { + delete process.env.ORCA_AZURE_DEVOPS_TOKEN + + await expect(isAzureDevOpsReviewCreationAuthenticated('/repo')).resolves.toBe(false) + }) + + it('forwards local git exec options into repo-ref resolution for the auth gate', async () => { + delete process.env.ORCA_AZURE_DEVOPS_TOKEN + runAzAccessTokenCommandMock.mockResolvedValue( + JSON.stringify({ accessToken: 'entra-jwt', expires_on: 32472144000 }) + ) + + await expect( + isAzureDevOpsReviewCreationAuthenticated('/repo', null, { + localGitExecOptions: { wslDistro: 'Ubuntu-22.04' } + }) + ).resolves.toBe(true) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + ['remote', 'get-url', 'origin'], + expect.objectContaining({ wslDistro: 'Ubuntu-22.04' }) + ) + }) + + it('requires a token for on-prem base URLs instead of consulting az', async () => { + delete process.env.ORCA_AZURE_DEVOPS_TOKEN + process.env.ORCA_AZURE_DEVOPS_API_BASE_URL = 'https://tfs.corp.example/tfs/Collection' + + await expect(isAzureDevOpsReviewCreationAuthenticated('/repo')).resolves.toBe(false) + expect(runAzAccessTokenCommandMock).not.toHaveBeenCalled() + }) + + it('creates the pull request with the az CLI token when no env token is set', async () => { + delete process.env.ORCA_AZURE_DEVOPS_TOKEN + runAzAccessTokenCommandMock.mockResolvedValue( + JSON.stringify({ accessToken: 'entra-jwt', expires_on: 32472144000 }) + ) + const fetchMock = vi.fn(async (_input: string | URL | Request, init?: RequestInit) => { + expect((init?.headers as Record | undefined)?.Authorization).toBe( + 'Bearer entra-jwt' + ) + return Response.json({ + pullRequestId: 39, + title: 'Entra create', + status: 'active', + creationDate: '2026-06-01T00:00:00Z' + }) + }) + globalThis.fetch = fetchMock as never + + await expect( + createAzureDevOpsPullRequest('/repo', { + provider: 'azure-devops', + base: 'main', + head: 'feature/azure', + title: 'Entra create' + }) + ).resolves.toMatchObject({ ok: true, number: 39 }) + expect(fetchMock).toHaveBeenCalledOnce() }) it('posts a pull request create body to the repository REST endpoint', async () => { @@ -223,7 +303,8 @@ describe('Azure DevOps pull request creation', () => { }) ).resolves.toMatchObject({ ok: false, - code: 'auth_required' + code: 'auth_required', + error: expect.stringContaining('run az login or set ORCA_AZURE_DEVOPS_TOKEN') }) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { cwd: '/repo', diff --git a/src/main/azure-devops/pull-request-creation.ts b/src/main/azure-devops/pull-request-creation.ts index e190e65a4628..e6acb3211b75 100644 --- a/src/main/azure-devops/pull-request-creation.ts +++ b/src/main/azure-devops/pull-request-creation.ts @@ -1,4 +1,3 @@ -import { Buffer } from 'node:buffer' import type { CreateHostedReviewInput, CreateHostedReviewResult } from '../../shared/hosted-review' import { normalizeHostedReviewBaseRef, @@ -8,11 +7,23 @@ import { HostedReviewApiRequestError, requestHostedReviewJson } from '../source-control/hosted-review-api-request' +import { + getHostedReviewLocalGitOptions, + type HostedReviewExecutionOptions +} from '../source-control/hosted-review-git-options' import { readHostedPullRequestTemplate } from '../source-control/pull-request-template' +import { + getAzCliAzureDevOpsAccessToken, + isEntraEligibleAzureDevOpsBaseUrl +} from './az-cli-access-token' import { azureDevOpsApiVersionForOrigin, + azureDevOpsTokenConfigured, + getAzureDevOpsAuthConfig, isAzureDevOpsPreviewVersionRejection, markAzureDevOpsPreviewApiVersionOrigin, + normalizeAzureDevOpsApiBaseUrl, + resolveAzureDevOpsAuthHeaders, resolveAzureDevOpsGitApiBaseUrl } from './azure-devops-api-request' import { getAzureDevOpsPullRequestForBranch } from './client' @@ -21,39 +32,32 @@ import { getAzureDevOpsRepoRef, type AzureDevOpsRepoRef } from './repository-ref const CREATE_REQUEST_TIMEOUT_MS = 60_000 -type AzureDevOpsCreateAuthConfig = { - pat: string | null - accessToken: string | null - username: string | null -} - -function envValue(name: string): string | null { - const value = process.env[name]?.trim() ?? '' - return value.length > 0 ? value : null -} - -function getAuthConfig(): AzureDevOpsCreateAuthConfig { - return { - pat: envValue('ORCA_AZURE_DEVOPS_TOKEN') ?? envValue('ORCA_AZURE_DEVOPS_PAT'), - accessToken: envValue('ORCA_AZURE_DEVOPS_ACCESS_TOKEN'), - username: envValue('ORCA_AZURE_DEVOPS_USERNAME') - } -} - -export function isAzureDevOpsReviewCreationAuthenticated(): boolean { - const config = getAuthConfig() - return Boolean(config.pat || config.accessToken) -} - -function authHeaders(config: AzureDevOpsCreateAuthConfig): Record { - if (config.accessToken) { - return { Authorization: `Bearer ${config.accessToken}` } +/** + * A configured env token always authenticates. Otherwise hosted Azure DevOps + * accepts the az CLI's Entra login; on-prem servers require the token. + */ +export async function isAzureDevOpsReviewCreationAuthenticated( + repoPath: string, + connectionId?: string | null, + options: HostedReviewExecutionOptions = {} +): Promise { + const config = getAzureDevOpsAuthConfig() + if (azureDevOpsTokenConfigured(config)) { + return true } - if (config.pat) { - const encoded = Buffer.from(`${config.username ?? ''}:${config.pat}`).toString('base64') - return { Authorization: `Basic ${encoded}` } + const baseUrl = config.apiBaseUrl + ? normalizeAzureDevOpsApiBaseUrl(config.apiBaseUrl) + : ( + await getAzureDevOpsRepoRef( + repoPath, + connectionId, + getHostedReviewLocalGitOptions(options) + ) + )?.apiBaseUrl + if (!baseUrl || !isEntraEligibleAzureDevOpsBaseUrl(baseUrl)) { + return false } - return {} + return (await getAzCliAzureDevOpsAccessToken()) !== null } function apiUrl(repo: AzureDevOpsRepoRef, path: string): URL { @@ -124,7 +128,7 @@ function classifyCreateError(error: unknown): CreateHostedReviewResult { ok: false, 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: run az login or set ORCA_AZURE_DEVOPS_TOKEN in this environment.' } } if (status === 409 || lower.includes('already exists') || lower.includes('active pull request')) { @@ -218,6 +222,7 @@ export async function createAzureDevOpsPullRequest( ...(input.draft ? { isDraft: true } : {}) } + const baseUrl = resolveAzureDevOpsGitApiBaseUrl(repo) try { const raw = await requestCreatePullRequest( repo, @@ -227,7 +232,7 @@ export async function createAzureDevOpsPullRequest( headers: { Accept: 'application/json', 'Content-Type': 'application/json', - ...authHeaders(getAuthConfig()) + ...(await resolveAzureDevOpsAuthHeaders(baseUrl)) }, body: JSON.stringify(requestBody) } diff --git a/src/main/source-control/hosted-review-creation-provider.ts b/src/main/source-control/hosted-review-creation-provider.ts index 323497d24195..a4b4a733bac6 100644 --- a/src/main/source-control/hosted-review-creation-provider.ts +++ b/src/main/source-control/hosted-review-creation-provider.ts @@ -86,7 +86,7 @@ export function reviewCopy(provider: HostedReviewProvider): { shortLabel: 'PR', reviewLabel: 'pull request', providerName: 'Azure DevOps', - authInstruction: 'Set ORCA_AZURE_DEVOPS_TOKEN' + authInstruction: 'Run az login or set ORCA_AZURE_DEVOPS_TOKEN' } } if (provider === 'gitea') { @@ -123,7 +123,7 @@ export async function isProviderAuthenticated( return isGitLabAuthenticated(repoPath, connectionId, options) } if (provider === 'azure-devops') { - return isAzureDevOpsReviewCreationAuthenticated() + return isAzureDevOpsReviewCreationAuthenticated(repoPath, connectionId, options) } if (provider === 'gitea') { return isGiteaReviewCreationAuthenticated() diff --git a/src/renderer/src/components/right-sidebar/source-control-create-review-blocked-action.ts b/src/renderer/src/components/right-sidebar/source-control-create-review-blocked-action.ts index fd0824d41cc8..8da4bd13db8a 100644 --- a/src/renderer/src/components/right-sidebar/source-control-create-review-blocked-action.ts +++ b/src/renderer/src/components/right-sidebar/source-control-create-review-blocked-action.ts @@ -28,7 +28,7 @@ export function resolveHostedReviewAuthInstruction(provider: HostedReviewProvide return 'Run glab auth login' } if (provider === 'azure-devops') { - return 'Set ORCA_AZURE_DEVOPS_TOKEN' + return 'Run az login or set ORCA_AZURE_DEVOPS_TOKEN' } if (provider === 'gitea') { return 'Set ORCA_GITEA_TOKEN' diff --git a/src/renderer/src/components/right-sidebar/source-control-dropdown-items.create-pr-intent.test.ts b/src/renderer/src/components/right-sidebar/source-control-dropdown-items.create-pr-intent.test.ts index 741723a173ea..ed22a3fa7fc8 100644 --- a/src/renderer/src/components/right-sidebar/source-control-dropdown-items.create-pr-intent.test.ts +++ b/src/renderer/src/components/right-sidebar/source-control-dropdown-items.create-pr-intent.test.ts @@ -143,7 +143,7 @@ describe('resolveDropdownItems Create PR intent', () => { ) it.each([ - ['azure-devops', 'Set ORCA_AZURE_DEVOPS_TOKEN in this environment'], + ['azure-devops', 'Run az login or set ORCA_AZURE_DEVOPS_TOKEN in this environment'], ['gitea', 'Set ORCA_GITEA_TOKEN in this environment'] ] as const)('uses token auth copy when %s PR creation needs authentication', (provider, hint) => { const items = resolveDropdownItems( diff --git a/src/renderer/src/components/settings/token-source-control-integration-cards.tsx b/src/renderer/src/components/settings/token-source-control-integration-cards.tsx index 1bf0499c6288..4831363636d3 100644 --- a/src/renderer/src/components/settings/token-source-control-integration-cards.tsx +++ b/src/renderer/src/components/settings/token-source-control-integration-cards.tsx @@ -33,8 +33,8 @@ export function AzureDevOpsIntegrationCard(): React.JSX.Element { 'Pull requests and build statuses for detected Azure Repos' ) : translate( - 'auto.components.settings.token.source.control.integration.cards.0eb50d5593', - 'Pull requests and build statuses via Azure DevOps REST API tokens.' + 'auto.components.settings.token.source.control.integration.cards.az.description', + 'Pull requests and build statuses via the az CLI or Azure DevOps REST API tokens.' ) } checking={status === 'checking'} @@ -56,8 +56,18 @@ export function AzureDevOpsIntegrationCard(): React.JSX.Element { ) : status === 'not-configured' ? ( <> {translate( - 'auto.components.settings.token.source.control.integration.cards.7bbc9c64f0', - 'Set' + 'auto.components.settings.token.source.control.integration.cards.az.run', + 'Run' + )}{' '} + + {translate( + 'auto.components.settings.token.source.control.integration.cards.az.login', + 'az login' + )} + + {translate( + 'auto.components.settings.token.source.control.integration.cards.az.or.set', + ' (Azure CLI), set' )}{' '} {translate( diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 5af0a46d60a9..be5c51184d12 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -10447,7 +10447,6 @@ "48842720d2": "ORCA_AZURE_DEVOPS_TOKEN", "7bbc9c64f0": "Set", "f3f47dc7de": "Azure DevOps status is not available in this runtime yet.", - "0eb50d5593": "Pull requests and build statuses via Azure DevOps REST API tokens.", "54636c65d4": "Pull requests and build statuses for detected Azure Repos", "ea204f5e03": "{{value0}} · Pull requests and build statuses", "6154b02093": "Bitbucket credentials are configured but could not authenticate. Check the token and repository permissions, then restart Orca if environment variables changed.", @@ -10463,7 +10462,15 @@ "statusNotConfigured": "Not configured", "statusAuthFailed": "Auth failed", "statusConfigured": "Configured", - "statusOptionalSetup": "Optional setup" + "statusOptionalSetup": "Optional setup", + "az": { + "run": "Run", + "login": "az login", + "or": { + "set": " (Azure CLI), set" + }, + "description": "Pull requests and build statuses via the az CLI or Azure DevOps REST API tokens." + } } } } diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 91e9dc49dcc4..00caae59dd03 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -9425,7 +9425,6 @@ "48842720d2": "ORCA_AZURE_DEVOPS_TOKEN", "7bbc9c64f0": "Configura", "f3f47dc7de": "El estado de Azure DevOps aún no está disponible en este runtime.", - "0eb50d5593": "Pull requests y estados de build mediante tokens de la API REST de Azure DevOps.", "54636c65d4": "Pull requests y estados de build para Azure Repos detectados", "ea204f5e03": "{{value0}} · Pull requests y estados de build", "6154b02093": "Las credenciales de Bitbucket están configuradas, pero no se pudo autenticar. Comprueba el token y los permisos del repositorio; después reinicia Orca si cambiaron las variables de entorno.", @@ -9435,7 +9434,14 @@ "63a7f47392": "ORCA_BITBUCKET_EMAIL", "24ac1c69dc": "El estado de Bitbucket aún no está disponible en este runtime.", "a924e8dcd1": "Pull requests y estados de build mediante tokens de la API de Bitbucket Cloud.", - "0fa5629dad": "Pull requests y estados de build" + "0fa5629dad": "Pull requests y estados de build", + "az": { + "run": "Run", + "login": "az login", + "or": { + "set": " (Azure CLI), set" + } + } } } } diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 493dfce6bdae..091f95912eb1 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -9425,7 +9425,6 @@ "48842720d2": "ORCA_AZURE_DEVOPS_TOKEN", "7bbc9c64f0": "設定:", "f3f47dc7de": "このランタイムでは、Azure DevOps の状態をまだ取得できません。", - "0eb50d5593": "Azure DevOps REST API トークン経由の PR とビルドステータス。", "54636c65d4": "検出された Azure リポジトリの PR とビルドステータス", "ea204f5e03": "{{value0}} · PR とビルドステータス", "6154b02093": "Bitbucket の認証情報は設定されていますが、認証できませんでした。トークンとリポジトリの権限を確認し、環境変数を変更した場合は Orca を再起動してください。", @@ -9435,7 +9434,14 @@ "63a7f47392": "ORCA_BITBUCKET_EMAIL", "24ac1c69dc": "このランタイムでは、Bitbucket の状態をまだ取得できません。", "a924e8dcd1": "Bitbucket Cloud API トークン経由の PR とビルドステータス。", - "0fa5629dad": "PR とビルドステータス" + "0fa5629dad": "PR とビルドステータス", + "az": { + "run": "Run", + "login": "az login", + "or": { + "set": " (Azure CLI), set" + } + } } } } diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 583b6ba2da6c..d6e7d36d8fd2 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -9417,7 +9417,6 @@ "48842720d2": "ORCA_AZURE_DEVOPS_TOKEN", "7bbc9c64f0": "설정", "f3f47dc7de": "이 런타임에서는 아직 Azure DevOps 상태를 사용할 수 없습니다.", - "0eb50d5593": "Azure DevOps REST API 토큰을 통한 PR 및 빌드 상태입니다.", "54636c65d4": "감지된 Azure Repos의 PR 및 빌드 상태", "ea204f5e03": "{{value0}} · PR 및 빌드 상태", "6154b02093": "Bitbucket 자격 증명이 구성되어 있지만 인증할 수 없습니다. 토큰과 repos 권한을 확인하고, 환경 변수가 변경되었다면 Orca를 다시 시작하세요.", @@ -9427,7 +9426,14 @@ "63a7f47392": "ORCA_BITBUCKET_EMAIL", "24ac1c69dc": "이 런타임에서는 아직 Bitbucket 상태를 사용할 수 없습니다.", "a924e8dcd1": "Bitbucket Cloud API 토큰을 통한 PR 및 빌드 상태입니다.", - "0fa5629dad": "PR 및 빌드 상태" + "0fa5629dad": "PR 및 빌드 상태", + "az": { + "run": "Run", + "login": "az login", + "or": { + "set": " (Azure CLI), set" + } + } } } } diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index dc0cf6707652..5516f2efe72d 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -9460,7 +9460,6 @@ "48842720d2": "ORCA_AZURE_DEVOPS_TOKEN", "7bbc9c64f0": "设置", "f3f47dc7de": "此运行时暂不支持 Azure DevOps 状态。", - "0eb50d5593": "通过 Azure DevOps REST API token 获取 pull request 和构建状态。", "54636c65d4": "已检测 Azure Repos 的 pull request 和构建状态", "ea204f5e03": "{{value0}} · 拉取请求和构建状态", "6154b02093": "Bitbucket 凭据已配置但无法通过身份验证。请检查 token 和仓库权限;如果环境变量已更改,请重启 Orca。", @@ -9470,7 +9469,14 @@ "63a7f47392": "ORCA_BITBUCKET_EMAIL", "24ac1c69dc": "此运行时暂不支持 Bitbucket 状态。", "a924e8dcd1": "通过 Bitbucket Cloud API token 获取 pull request 和构建状态。", - "0fa5629dad": "pull request 和构建状态" + "0fa5629dad": "pull request 和构建状态", + "az": { + "run": "Run", + "login": "az login", + "or": { + "set": " (Azure CLI), set" + } + } } } }