diff --git a/src/cli/__tests__/auth-session-cloud-origin.test.ts b/src/cli/__tests__/auth-session-cloud-origin.test.ts new file mode 100644 index 0000000000..d03cad387b --- /dev/null +++ b/src/cli/__tests__/auth-session-cloud-origin.test.ts @@ -0,0 +1,240 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { normalizeError } from '@agent-device/kernel/errors'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { + loginWithDeviceAuth, + readCliSession, + resolveCliSessionPath, + resolveRemoteAuth, + writeCliSession, +} from '../auth-session.ts'; + +const baseFlags = { + json: false, + help: false, + version: false, + daemonBaseUrl: 'https://bridge.agent-device.dev', + tenant: 'acme', + runId: 'run-123', +}; + +const START = 'https://cloud.example/api/control-plane/device-auth/start'; +const POLL = 'https://cloud.example/api/control-plane/device-auth/poll'; +const REFRESH = 'https://cloud.example/api/control-plane/cli-session/refresh'; + +function jsonResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); +} + +/** A refresh of the stored session that records each request URL and answers with a token. */ +function refreshWith(stateDir: string, env: Record, requests: string[]) { + return resolveRemoteAuth({ + command: 'snapshot', + flags: baseFlags, + stateDir, + allowInteractiveLogin: false, + env, + io: { + fetch: async (url) => { + requests.push(String(url)); + return jsonResponse({ accessToken: 'adc_agent_fresh' }); + }, + }, + }); +} + +/** Answers device-auth start and poll with an approved login, and any other URL with a 404. */ +const deviceAuthCloud = async (url: URL | RequestInfo): Promise => { + if (String(url) === START) { + return jsonResponse({ + deviceCode: 'device-secret', + userCode: 'ABCD-EFGH', + verificationUri: 'https://cloud.example/authorize', + }); + } + if (String(url) === POLL) { + return jsonResponse({ + status: 'approved', + accessToken: 'adc_agent_login', + cliSession: { id: 'session-new', refreshCredential: 'adc_refresh_new' }, + }); + } + return new Response('{}', { status: 404 }); +}; + +function loginAt(stateDir: string, fetch: typeof globalThis.fetch) { + return loginWithDeviceAuth({ + stateDir, + flags: baseFlags, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example/' }, + io: { + stdinIsTTY: true, + stdoutIsTTY: true, + stderr: { write: () => true }, + openBrowser: async () => {}, + fetch, + }, + }); +} + +/** Writes the session file as raw JSON, the way an older CLI or a hand edit leaves it. */ +function writeRawSession(stateDir: string, record: Record): void { + const filePath = resolveCliSessionPath(stateDir); + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, JSON.stringify(record)); +} + +const isIssuerUnverified = (error: unknown) => { + const normalized = normalizeError(error); + return ( + normalized.details?.reason === 'cli_session_issuer_unverified' && + String(normalized.hint).includes('agent-device auth login') + ); +}; + +test('a stored CLI session is sent only to the cloud that issued it', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-origin-'); + try { + writeCliSession({ + stateDir: tempRoot, + session: { + version: 2, + id: 'session-origin', + cloudBaseUrl: 'https://cloud.example', + refreshCredential: 'adc_refresh_secret', + createdAt: '2026-01-01T00:00:00.000Z', + }, + }); + const requests: string[] = []; + + await assert.rejects( + () => + refreshWith( + tempRoot, + { AGENT_DEVICE_CLOUD_BASE_URL: 'https://elsewhere.example' }, + requests, + ), + (error) => normalizeError(error).details?.reason === 'cloud_login_origin_mismatch', + ); + assert.deepEqual(requests, []); + + const same = await refreshWith( + tempRoot, + { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example/' }, + requests, + ); + assert.equal(same.flags.daemonAuthToken, 'adc_agent_fresh'); + assert.deepEqual(requests, [REFRESH]); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('a rotation is not stored over a session that a login moved to another cloud', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-origin-rotate-'); + try { + const session = { + version: 2 as const, + id: 'session-moved', + cloudBaseUrl: 'https://cloud.example', + refreshCredential: 'adc_refresh_old', + createdAt: '2026-01-01T00:00:00.000Z', + }; + writeCliSession({ stateDir: tempRoot, session }); + const moved = { ...session, cloudBaseUrl: 'https://other-cloud.example' }; + + await resolveRemoteAuth({ + command: 'snapshot', + flags: baseFlags, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + fetch: async () => { + // Another process logs in to another cloud while this refresh is in flight. + writeCliSession({ stateDir: tempRoot, session: moved }); + return jsonResponse({ accessToken: 'adc_agent_1', refreshCredential: 'adc_refresh_new' }); + }, + }, + }); + + assert.deepEqual(readCliSession({ stateDir: tempRoot }), moved); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('a version 1 session is refused with a re-login reason, and a fresh login is used', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-origin-legacy-'); + try { + writeRawSession(tempRoot, { + version: 1, + id: 'session-legacy', + cloudBaseUrl: 'https://cloud.example', + refreshCredential: 'adc_refresh_legacy', + createdAt: '2026-01-01T00:00:00.000Z', + }); + const requests: string[] = []; + + await assert.rejects(() => refreshWith(tempRoot, {}, requests), isIssuerUnverified); + assert.deepEqual(requests, []); + assert.equal(readCliSession({ stateDir: tempRoot }), null); + + const login = await loginAt(tempRoot, deviceAuthCloud); + assert.equal(login.session.version, 2); + + const refreshed = await refreshWith(tempRoot, {}, requests); + assert.equal(refreshed.flags.daemonAuthToken, 'adc_agent_fresh'); + assert.deepEqual(requests, [REFRESH]); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +// Every auth route goes through the redirect-checked transport, whose cases are proven in +// cloud-auth-request.test.ts. A route that called fetch directly would follow this redirect. +test.each([START, POLL, REFRESH])( + 'a cross-origin redirect from %s is refused before it is followed, and nothing is stored', + async (redirected) => { + const tempRoot = mkdtempForTestSync('agent-device-auth-origin-redirect-'); + try { + const sent: string[] = []; + const fetch = async (url: URL | RequestInfo) => { + sent.push(String(url)); + return String(url) === redirected + ? new Response(null, { + status: 307, + headers: { location: 'https://elsewhere.example/auth' }, + }) + : await deviceAuthCloud(url); + }; + if (redirected === REFRESH) await loginAt(tempRoot, deviceAuthCloud); + const stored = readCliSession({ stateDir: tempRoot }); + + await assert.rejects( + () => + redirected === REFRESH + ? resolveRemoteAuth({ + command: 'snapshot', + flags: baseFlags, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { fetch }, + }) + : loginAt(tempRoot, fetch), + (error) => normalizeError(error).details?.reason === 'cloud_auth_redirect_refused', + ); + assert.equal(sent.at(-1), redirected); + assert.deepEqual(readCliSession({ stateDir: tempRoot }), stored); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + }, +); diff --git a/src/cli/__tests__/auth-session-exchange.test.ts b/src/cli/__tests__/auth-session-exchange.test.ts index 9ddc281ddb..a9aa79fda9 100644 --- a/src/cli/__tests__/auth-session-exchange.test.ts +++ b/src/cli/__tests__/auth-session-exchange.test.ts @@ -35,7 +35,7 @@ function writeStoredSession(stateDir: string, overrides: Record writeCliSession({ stateDir, session: { - version: 1, + version: 2, id: 'session-pairing', cloudBaseUrl: 'https://cloud.example', refreshCredential: 'adc_refresh_old', diff --git a/src/cli/__tests__/auth-session-refresh.test.ts b/src/cli/__tests__/auth-session-refresh.test.ts index 543b7defda..c4b483cd87 100644 --- a/src/cli/__tests__/auth-session-refresh.test.ts +++ b/src/cli/__tests__/auth-session-refresh.test.ts @@ -37,7 +37,7 @@ function writeStoredSession(stateDir: string, overrides: Record writeCliSession({ stateDir, session: { - version: 1, + version: 2, id: 'session-refresh', cloudBaseUrl: 'https://cloud.example', refreshCredential: 'adc_refresh_old', diff --git a/src/cli/__tests__/auth-session-refusal.test.ts b/src/cli/__tests__/auth-session-refusal.test.ts index 0faba91711..556ed4e13c 100644 --- a/src/cli/__tests__/auth-session-refusal.test.ts +++ b/src/cli/__tests__/auth-session-refusal.test.ts @@ -35,7 +35,7 @@ function writeStoredSession(stateDir: string): void { writeCliSession({ stateDir, session: { - version: 1, + version: 2, id: 'session-refusal', cloudBaseUrl: 'https://cloud.example', refreshCredential: 'adc_refresh_stored', diff --git a/src/cli/__tests__/auth-session-umask.test.ts b/src/cli/__tests__/auth-session-umask.test.ts index 80d7a4ed3c..fa61a0b659 100644 --- a/src/cli/__tests__/auth-session-umask.test.ts +++ b/src/cli/__tests__/auth-session-umask.test.ts @@ -9,7 +9,7 @@ test.skipIf(process.platform === 'win32')( () => { const tempRoot = mkdtempForTestSync('agent-device-auth-session-umask-'); const session = { - version: 1 as const, + version: 2 as const, id: 'session-first', cloudBaseUrl: 'https://cloud.example', refreshCredential: 'adc_refresh_umask', diff --git a/src/cli/__tests__/auth-session.test.ts b/src/cli/__tests__/auth-session.test.ts index 2f4d0eb4df..8c8b586d3f 100644 --- a/src/cli/__tests__/auth-session.test.ts +++ b/src/cli/__tests__/auth-session.test.ts @@ -100,7 +100,7 @@ test('remote auth leaves non-cloud remote daemons to existing daemon auth valida writeCliSession({ stateDir: tempRoot, session: { - version: 1, + version: 2, id: 'session-non-cloud', cloudBaseUrl: 'https://cloud.example', refreshCredential: 'adc_refresh_should_not_be_used', @@ -132,7 +132,7 @@ test('remote auth refreshes a stored CLI session into an agent token', async () writeCliSession({ stateDir: tempRoot, session: { - version: 1, + version: 2, id: 'session-1', cloudBaseUrl: 'https://cloud.example', workspaceId: 'acme', @@ -175,7 +175,7 @@ test('remote auth refreshes a stored CLI session into an agent token', async () test('remote auth stores a refresh credential that the cloud rotated', async () => { const tempRoot = mkdtempForTestSync('agent-device-auth-rotate-'); const session = { - version: 1 as const, + version: 2 as const, id: 'session-rotate', cloudBaseUrl: 'https://cloud.example', refreshCredential: 'adc_refresh_old', @@ -226,7 +226,7 @@ test('remote auth stores a refresh credential that the cloud rotated', async () test('a rotated credential does not replace a session another writer changed', async () => { const tempRoot = mkdtempForTestSync('agent-device-auth-rotate-race-'); const session = { - version: 1 as const, + version: 2 as const, id: 'session-race', cloudBaseUrl: 'https://cloud.example', refreshCredential: 'adc_refresh_old', @@ -286,7 +286,7 @@ test('logout without a stored session takes no lock and writes nothing', async ( test('a stored rotation is kept when the lock release fails, and the warning is best effort', async () => { const tempRoot = mkdtempForTestSync('agent-device-auth-release-'); const session = { - version: 1 as const, + version: 2 as const, id: 'session-release', cloudBaseUrl: 'https://cloud.example', refreshCredential: 'adc_refresh_old', @@ -347,7 +347,7 @@ test('a timed-out session lock wait keeps a login waiting and fails a refresh re writeCliSession({ stateDir: tempRoot, session: { - version: 1, + version: 2, id: 'session-timeout', cloudBaseUrl: 'https://cloud.example', refreshCredential: 'adc_refresh_old', @@ -465,7 +465,7 @@ test('device login does not print a user code that carries control characters', test('remote auth does not fall back to login when session refresh gets 503', async () => { const tempRoot = mkdtempForTestSync('agent-device-auth-refresh-503-'); const session = { - version: 1 as const, + version: 2 as const, id: 'session-503', cloudBaseUrl: 'https://cloud.example', refreshCredential: 'adc_refresh_503', @@ -515,7 +515,7 @@ test('remote auth fails immediately when stored CLI session is revoked', async ( writeCliSession({ stateDir: tempRoot, session: { - version: 1, + version: 2, id: 'session-revoked', cloudBaseUrl: 'https://cloud.example', refreshCredential: 'adc_refresh_revoked', @@ -623,7 +623,7 @@ test('auth summary and logout do not expose stored refresh credentials', async ( writeCliSession({ stateDir: tempRoot, session: { - version: 1, + version: 2, id: 'session-3', cloudBaseUrl: 'https://cloud.example', refreshCredential: 'adc_refresh_hidden', @@ -873,7 +873,7 @@ function assertRefusedWithoutOutput(refused: RefusedDeviceLogin): void { test('a rewritten CLI session replaces the file, so a reader never sees a partial record', () => { const tempRoot = mkdtempForTestSync('agent-device-auth-session-replace-'); const session = { - version: 1 as const, + version: 2 as const, id: 'session-first', cloudBaseUrl: 'https://cloud.example', refreshCredential: 'adc_refresh_first', diff --git a/src/cli/__tests__/cloud-auth-request.test.ts b/src/cli/__tests__/cloud-auth-request.test.ts new file mode 100644 index 0000000000..0b7584669e --- /dev/null +++ b/src/cli/__tests__/cloud-auth-request.test.ts @@ -0,0 +1,165 @@ +import { afterEach, expect, test } from 'vitest'; +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { normalizeError } from '@agent-device/kernel/errors'; +import { postCloudAuthJson } from '../cloud-auth-request.ts'; + +// These tests use Node's own fetch against loopback servers, so they prove that no redirect is +// followed by fetch itself and that a refused target never receives a request. + +type Received = { method?: string; path?: string; body: string; contentType?: string }; +/** A canned response. Routes are data, so no handler is ever chosen by the request path. */ +type Route = { status: number; headers: Record; body: string }; + +const servers: http.Server[] = []; + +afterEach(async () => { + await Promise.all( + servers.splice(0).map( + (server) => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + ), + ); +}); + +async function listen() { + const received: Received[] = []; + const routes = new Map(); + const server = http.createServer((req, res) => { + let body = ''; + req.setEncoding('utf8'); + req.on('data', (chunk: string) => (body += chunk)); + req.on('end', () => { + received.push({ + method: req.method, + path: req.url, + body, + contentType: req.headers['content-type'], + }); + const entry = routes.get(req.url ?? ''); + // A queue serves its responses in order and keeps repeating the last one. + const route = Array.isArray(entry) && entry.length > 1 ? entry.shift() : [entry].flat()[0]; + if (route === undefined) return void res.writeHead(404).end(); + res.writeHead(route.status, route.headers).end(route.body); + }); + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + return { origin: `http://127.0.0.1:${port}`, received, routes }; +} + +const redirect = (status: number, location?: string): Route => ({ + status, + headers: location === undefined ? {} : { location }, + body: '', +}); +const answer: Route = { + status: 200, + headers: { 'content-type': 'application/json' }, + body: '{"accessToken":"adc_agent"}', +}; + +const BODY = { deviceCode: 'device-secret' }; +const post = (origin: string) => + postCloudAuthJson<{ accessToken: string }>({ baseUrl: origin, pathName: '/start', body: BODY }); +const posted = (path: string) => ({ + method: 'POST', + path, + body: JSON.stringify(BODY), + contentType: 'application/json', +}); +const fetchedAsGet = (path: string) => ({ method: 'GET', path, body: '', contentType: undefined }); + +test.each([ + [307, posted('/next')], + [308, posted('/next')], + [301, fetchedAsGet('/next')], + [302, fetchedAsGet('/next')], + [303, fetchedAsGet('/next')], +])('a same-origin %i is followed with the method fetch gives it', async (status, followed) => { + const cloud = await listen(); + cloud.routes.set('/start', redirect(status, '/next')); + cloud.routes.set('/next', answer); + + expect(await post(cloud.origin)).toEqual({ accessToken: 'adc_agent' }); + expect(cloud.received).toEqual([posted('/start'), followed]); +}); + +test.each([ + [301, fetchedAsGet('/start')], + [302, fetchedAsGet('/start')], + [303, fetchedAsGet('/start')], + [307, posted('/start')], + [308, posted('/start')], +])( + 'an empty Location on a %i redirects to the same URL, as fetch does', + async (status, followed) => { + const cloud = await listen(); + cloud.routes.set('/start', [redirect(status, ''), answer]); + + expect(await post(cloud.origin)).toEqual({ accessToken: 'adc_agent' }); + expect(cloud.received).toEqual([posted('/start'), followed]); + }, +); + +test('a chain keeps the POST through a 307 and stays a GET after a 303', async () => { + const cloud = await listen(); + cloud.routes.set('/start', redirect(307, '/a')); + cloud.routes.set('/a', redirect(303, '/b')); + cloud.routes.set('/b', redirect(307, '/c')); + cloud.routes.set('/c', answer); + + await post(cloud.origin); + expect(cloud.received).toEqual([ + posted('/start'), + posted('/a'), + fetchedAsGet('/b'), + fetchedAsGet('/c'), + ]); +}); + +test('three same-origin redirects are followed and a fourth is refused', async () => { + const cloud = await listen(); + cloud.routes.set('/start', redirect(307, '/1')); + cloud.routes.set('/1', redirect(307, '/2')); + cloud.routes.set('/2', redirect(307, '/3')); + cloud.routes.set('/3', answer); + expect(await post(cloud.origin)).toEqual({ accessToken: 'adc_agent' }); + + cloud.routes.set('/3', redirect(307, '/4')); + cloud.routes.set('/4', answer); + cloud.received.length = 0; + await expect(post(cloud.origin)).rejects.toMatchObject({ + details: { reason: 'cloud_auth_redirect_refused' }, + }); + expect(cloud.received.map(({ path }) => path)).toEqual(['/start', '/1', '/2', '/3']); +}); + +test.each([ + ['no Location', () => undefined], + ['a username', (host: string) => `http://device-secret@${host}/next`], + ['a password', (host: string) => `http://user:device-secret@${host}/next`], + ['another origin', (_host: string, other: string) => `${other}/next`], +])( + 'a redirect to %s is refused before anything is sent, without quoting the target', + async (_case, location) => { + const cloud = await listen(); + const other = await listen(); + cloud.routes.set('/start', redirect(307, location(new URL(cloud.origin).host, other.origin))); + cloud.routes.set('/next', answer); + other.routes.set('/next', answer); + + const rejection = await post(cloud.origin).then( + () => undefined, + (error: unknown) => normalizeError(error), + ); + expect(rejection?.details?.reason).toBe('cloud_auth_redirect_refused'); + expect(JSON.stringify(rejection)).not.toContain('device-secret'); + expect(cloud.received.map(({ path }) => path)).toEqual(['/start']); + expect(other.received).toEqual([]); + }, +); diff --git a/src/cli/auth-session.ts b/src/cli/auth-session.ts index 988f391131..5d3f3aa26b 100644 --- a/src/cli/auth-session.ts +++ b/src/cli/auth-session.ts @@ -5,15 +5,21 @@ import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { CliFlags } from '@agent-device/contracts/command'; import { type EnvMap } from '@agent-device/kernel/source-value'; -import { readCloudJsonResponse } from './cloud-response.ts'; - +import { + CLI_SESSION_FORMAT_VERSION, + parseCliSessionRecord, + type CliSessionRecord, +} from './cli-session-format.ts'; + +// The transport loads when a request is made, so a command that reads no cloud auth stays off it. +const postCloudAuthJson: typeof import('./cloud-auth-request.ts').postCloudAuthJson = async (o) => + (await import('./cloud-auth-request.ts')).postCloudAuthJson(o); const DEFAULT_CLOUD_BASE_URL = 'https://cloud.agent-device.dev'; const DEVICE_AUTH_START_PATH = '/api/control-plane/device-auth/start'; const DEVICE_AUTH_POLL_PATH = '/api/control-plane/device-auth/poll'; const CLI_SESSION_REFRESH_PATH = '/api/control-plane/cli-session/refresh'; const API_KEYS_PATH = '/api-keys'; const DEVICE_POLL_TIMEOUT_MS = 10 * 60 * 1000; -const HTTP_TIMEOUT_MS = 15_000; const MIN_POLL_INTERVAL_MS = 1_000; const DEFAULT_POLL_INTERVAL_MS = 5_000; // A holder keeps the session lock for one file operation, or for one token exchange, which spends @@ -32,20 +38,15 @@ const CLI_SESSION_REASONS = { tokenless: { reason: 'cli_session_refresh_unanswered', commands: ['connect'] }, // The directory holding the session file cannot be written, so its lock cannot be taken. storeUnwritable: { reason: 'cli_session_store_unwritable', commands: ['connect'] }, + // The cloud API origin named by AGENT_DEVICE_CLOUD_BASE_URL differs from the origin that issued + // the stored CLI session, so the stored credential is not sent. Log in with the named origin, or + // unset the override. + loginOriginMismatch: { reason: 'cloud_login_origin_mismatch', commands: ['connect'] }, + // The stored CLI session does not record the cloud that issued its credential, as a session saved + // by an older CLI does not, so the credential is not sent. Run agent-device auth login. + issuerUnverified: { reason: 'cli_session_issuer_unverified', commands: ['connect'] }, } as const satisfies ReasonTable<'auth'>; -export type CliSessionRecord = { - version: 1; - id: string; - cloudBaseUrl: string; - workspaceId?: string; - accountId?: string; - name?: string; - refreshCredential: string; - createdAt: string; - expiresAt?: string; -}; - export type RemoteAuthResolution = { flags: CliFlags; source: 'flag' | 'env' | 'cli-session' | 'login' | 'none'; @@ -244,7 +245,7 @@ export async function loginWithDeviceAuth(options: { throw buildNonInteractiveLoginError(options.commandLabel ?? 'agent-device connect', env); } const cloudBaseUrl = resolveCloudBaseUrl(env); - const start = await postJson({ + const start = await postCloudAuthJson({ baseUrl: cloudBaseUrl, pathName: DEVICE_AUTH_START_PATH, body: { @@ -296,7 +297,7 @@ export async function loginWithDeviceAuth(options: { // expired, so the login exchanges it instead of handing back a token of unknown age. const approvedExpiresAt = hasToken(approved.expiresAt) ? approved.expiresAt : undefined; const session: CliSessionRecord = { - version: 1, + version: CLI_SESSION_FORMAT_VERSION, id: approved.cliSession?.id ?? `cli-${Date.now().toString(36)}`, cloudBaseUrl, workspaceId: approved.cliSession?.workspaceId, @@ -325,7 +326,6 @@ export async function loginWithDeviceAuth(options: { stateDir: options.stateDir, session, flags: options.flags, - env, io: options.io, }); } catch (error) { @@ -349,25 +349,38 @@ export async function loginWithDeviceAuth(options: { } export function readCliSession(options: { stateDir: string }): CliSessionRecord | null { - const filePath = resolveCliSessionPath(options.stateDir); + const stored = readStoredCliSession(options.stateDir); + return stored === 'unverified' ? null : stored; +} + +/** Reads the session file. A missing or unreadable file answers `null`. */ +function readStoredCliSession(stateDir: string): CliSessionRecord | 'unverified' | null { + const filePath = resolveCliSessionPath(stateDir); if (!fs.existsSync(filePath)) return null; try { - const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Partial; - if ( - parsed.version !== 1 || - !hasToken(parsed.id) || - !hasToken(parsed.cloudBaseUrl) || - !hasToken(parsed.refreshCredential) || - !hasToken(parsed.createdAt) - ) { - return null; - } - return parsed as CliSessionRecord; + return parseCliSessionRecord(fs.readFileSync(filePath, 'utf8')); } catch { return null; } } +/** + * The stored session to exchange, or `null` when there is none. A session whose issuer the file does + * not establish is refused: its credential could belong to another cloud than its URL names. + */ +function readExchangeableCliSession(stateDir: string): CliSessionRecord | null { + const stored = readStoredCliSession(stateDir); + if (stored !== 'unverified') return stored; + throw new AppError( + 'UNAUTHORIZED', + 'The stored CLI session does not record the cloud that issued it, so it must be renewed.', + { + reason: CLI_SESSION_REASONS.issuerUnverified.reason, + hint: 'Run agent-device auth login, or set AGENT_DEVICE_DAEMON_AUTH_TOKEN.', + }, + ); +} + export function writeCliSession(options: { stateDir: string; session: CliSessionRecord }): void { const filePath = resolveCliSessionPath(options.stateDir); fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 }); @@ -528,16 +541,17 @@ async function resolveCliSessionAccess(options: { const { env, flags, io, stateDir } = options; // This read only asks whether there is a session to exchange, so a command that has none takes no // lock and writes nothing. The credential is read again once the lock is held. - const stored = readCliSession({ stateDir }); + const stored = readExchangeableCliSession(stateDir); if (!stored || isExpired(stored.expiresAt, io?.now)) return null; // A refresh read is not a change the cloud will not repeat: a wait that times out fails with its // typed reason, and the next command asks again. const exchanged = await withCliSessionLock( stateDir, async () => { - const session = readCliSession({ stateDir }); + const session = readExchangeableCliSession(stateDir); if (!session || isExpired(session.expiresAt, io?.now)) return null; - return await exchangeCliSessionAccess({ stateDir, session, flags, env, io }); + assertStoredSessionOrigin(session, env); + return await exchangeCliSessionAccess({ stateDir, session, flags, io }); }, { io }, ); @@ -545,10 +559,28 @@ async function resolveCliSessionAccess(options: { return { accessToken: exchanged.accessToken, ...(hasToken(exchanged.expiresAt) ? { expiresAt: exchanged.expiresAt } : {}), + // The refresh went to the stored URL. A same-origin override still names the connection. cloudBaseUrl: resolveCloudBaseUrl(env, exchanged.session.cloudBaseUrl), }; } +/** + * The stored credential goes only to the cloud that issued it. An override that names another + * origin would send it to that origin, so the command stops before any request. + */ +function assertStoredSessionOrigin(session: CliSessionRecord, env: EnvMap): void { + const storedOrigin = new URL(resolveCloudBaseUrl({}, session.cloudBaseUrl)).origin; + if (new URL(resolveCloudBaseUrl(env, session.cloudBaseUrl)).origin === storedOrigin) return; + throw new AppError( + 'UNAUTHORIZED', + 'The stored CLI session belongs to another cloud API origin.', + { + reason: CLI_SESSION_REASONS.loginOriginMismatch.reason, + hint: 'Run agent-device auth login with this AGENT_DEVICE_CLOUD_BASE_URL, or unset it.', + }, + ); +} + /** * Exchanges a session's stored credential for an access token and answers with the token and the * session record the exchange leaves behind: the last one known saved, not one a failed write only @@ -560,10 +592,9 @@ async function exchangeCliSessionAccess(options: { stateDir: string; session: CliSessionRecord; flags: CliFlags; - env: EnvMap; io?: AuthIo; }): Promise<{ accessToken: string; expiresAt?: string; session: CliSessionRecord }> { - const { env, flags, io, stateDir } = options; + const { flags, io, stateDir } = options; // The file is what a store compares against: the last record this command saw there, and // `null` once a write would land on a session it did not write. `asked` is what the cloud // accepts for this session now, which stays ahead of the file when a save failed. `saved` is @@ -579,7 +610,7 @@ async function exchangeCliSessionAccess(options: { for (let exchange = 1; ; exchange += 1) { let refreshed; try { - refreshed = await refreshAgentToken({ session: asked, flags, env, io }); + refreshed = await refreshAgentToken({ session: asked, flags, io }); } catch (error) { // Only the first exchange is required. A token already read from the cloud stays usable by // the daemon that accepted it, so a transient failure of the optional exchange that asks @@ -653,7 +684,12 @@ function storeRotatedCredential(options: { const held = file.holds; try { const stored = readCliSession({ stateDir: options.stateDir }); - if (held && stored?.id === held.id && stored.refreshCredential === held.refreshCredential) { + if ( + held && + stored?.id === held.id && + stored.cloudBaseUrl === held.cloudBaseUrl && + stored.refreshCredential === held.refreshCredential + ) { const replaced: CliSessionRecord = { ...stored, ...rotation }; writeCliSession({ stateDir: options.stateDir, session: replaced }); file.holds = replaced; @@ -677,7 +713,6 @@ function storeRotatedCredential(options: { async function refreshAgentToken(options: { session: CliSessionRecord; flags: CliFlags; - env: EnvMap; io?: AuthIo; }): Promise<{ accessToken: string; @@ -685,9 +720,9 @@ async function refreshAgentToken(options: { refreshCredential?: string; sessionExpiresAt?: string; }> { - const cloudBaseUrl = resolveCloudBaseUrl(options.env, options.session.cloudBaseUrl); - const response = await postJson({ - baseUrl: cloudBaseUrl, + // The refresh goes to the URL stored with the session, never to an override. + const response = await postCloudAuthJson({ + baseUrl: resolveCloudBaseUrl({}, options.session.cloudBaseUrl), pathName: CLI_SESSION_REFRESH_PATH, body: { refreshCredential: options.session.refreshCredential, @@ -770,7 +805,7 @@ async function pollDeviceAuth(options: { (options.interval ?? DEFAULT_POLL_INTERVAL_MS / 1000) * 1000, ); while (now() < deadline) { - const response = await postJson({ + const response = await postCloudAuthJson({ baseUrl: options.cloudBaseUrl, pathName: DEVICE_AUTH_POLL_PATH, body: { deviceCode: options.deviceCode }, @@ -793,30 +828,6 @@ async function pollDeviceAuth(options: { throw new AppError('TIMEOUT', 'Device authorization expired before approval.'); } -async function postJson(options: { - baseUrl: string; - pathName: string; - body: Record; - // di-seam-approved: same fetch-global seam as AuthIo.fetch above, threaded through this - // postJson helper as fetchImpl. - fetchImpl?: typeof fetch; - // Passed to the response reader, which calls it on a status it would otherwise reject generically. - classifyRejectedBody?: (parsed: unknown) => AppError | undefined; -}): Promise { - const fetchImpl = options.fetchImpl ?? fetch; - const response = await fetchImpl(new URL(options.pathName, options.baseUrl), { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify(options.body), - signal: AbortSignal.timeout(HTTP_TIMEOUT_MS), - }); - return await readCloudJsonResponse(response, { - invalidJsonMessage: `Cloud auth endpoint returned invalid JSON (${response.status}).`, - rejectedMessage: 'Cloud auth endpoint rejected the request.', - classifyRejectedBody: options.classifyRejectedBody, - }); -} - type UnusableDeviceAuthStartField = | 'deviceCode' | 'userCode' diff --git a/src/cli/cli-session-format.ts b/src/cli/cli-session-format.ts new file mode 100644 index 0000000000..cc1183767d --- /dev/null +++ b/src/cli/cli-session-format.ts @@ -0,0 +1,36 @@ +// Version 2 marks a session saved by a login whose every request stayed on the origin of +// `cloudBaseUrl`. A version 1 login could follow a redirect to another cloud and save that cloud's +// credential under its own URL, so a version 1 record does not establish its issuer. +export const CLI_SESSION_FORMAT_VERSION = 2; + +export type CliSessionRecord = { + version: typeof CLI_SESSION_FORMAT_VERSION; + id: string; + cloudBaseUrl: string; + workspaceId?: string; + accountId?: string; + name?: string; + refreshCredential: string; + createdAt: string; + expiresAt?: string; +}; + +/** + * Parses the session file text. A record with a credential from another format version answers + * `unverified`. Text that is not a complete record answers `null`. Text that is not JSON throws. + */ +export function parseCliSessionRecord(text: string): CliSessionRecord | 'unverified' | null { + const parsed = JSON.parse(text) as Partial | null; + if (typeof parsed !== 'object' || parsed === null || !hasText(parsed.refreshCredential)) { + return null; + } + if (parsed.version !== CLI_SESSION_FORMAT_VERSION) return 'unverified'; + if (!hasText(parsed.id) || !hasText(parsed.cloudBaseUrl) || !hasText(parsed.createdAt)) { + return null; + } + return parsed as CliSessionRecord; +} + +function hasText(value: unknown): value is string { + return typeof value === 'string' && value.trim().length > 0; +} diff --git a/src/cli/cloud-auth-request.ts b/src/cli/cloud-auth-request.ts new file mode 100644 index 0000000000..e074cf5a03 --- /dev/null +++ b/src/cli/cloud-auth-request.ts @@ -0,0 +1,86 @@ +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import { readCloudJsonResponse } from './cloud-response.ts'; + +const HTTP_TIMEOUT_MS = 15_000; +const MAX_CLOUD_AUTH_REDIRECTS = 3; +const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); +// Fetch turns a POST into a GET without a body on these. A 307 or 308 keeps the method and body. +const GET_REDIRECT_STATUSES = new Set([301, 302, 303]); + +const CLOUD_AUTH_REQUEST_REASONS = { + // A cloud auth request got a redirect it does not follow: to another origin, past the third hop, + // or to a missing Location or one with a username or password. Nothing was sent to the target. + redirectRefused: { reason: 'cloud_auth_redirect_refused', commands: ['connect'] }, +} as const satisfies ReasonTable<'auth'>; + +/** + * Posts JSON to a cloud auth endpoint and reads the JSON answer. Every auth request carries a + * credential or a device code, so a redirect is followed only to the origin of the original request, + * at most three times, and never to a target with a username or password. A 307 or 308 keeps the + * POST and its body. A 301, 302 or 303 continues the chain as a GET without the body. + */ +export async function postCloudAuthJson(options: { + baseUrl: string; + pathName: string; + body: Record; + // di-seam-approved: injects the fetch global, which has no module boundary vi.mock can + // intercept. The auth-session tests inject it for exact per-call assertions. + fetchImpl?: typeof fetch; + // Passed to the response reader, which calls it on a status it would otherwise reject generically. + classifyRejectedBody?: (parsed: unknown) => AppError | undefined; +}): Promise { + const fetchImpl = options.fetchImpl ?? fetch; + const requestUrl = new URL(options.pathName, options.baseUrl); + const post: RequestInit = { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(options.body), + }; + // One timeout covers the whole redirect chain. + const signal = AbortSignal.timeout(HTTP_TIMEOUT_MS); + let url = requestUrl; + let init = post; + for (let redirects = 0; ; redirects += 1) { + const response = await fetchImpl(url, { ...init, redirect: 'manual', signal }); + if (!REDIRECT_STATUSES.has(response.status)) { + return await readCloudJsonResponse(response, { + invalidJsonMessage: `Cloud auth endpoint returned invalid JSON (${response.status}).`, + rejectedMessage: 'Cloud auth endpoint rejected the request.', + classifyRejectedBody: options.classifyRejectedBody, + }); + } + await response.body?.cancel().catch(() => undefined); + url = readRedirectTarget(response, url, requestUrl, redirects); + if (GET_REDIRECT_STATUSES.has(response.status)) init = { method: 'GET' }; + } +} + +function readRedirectTarget( + response: Response, + current: URL, + requestUrl: URL, + redirects: number, +): URL { + const location = response.headers.get('location'); + const target = location === null ? null : URL.parse(location, current); + const refusal = describeRefusedRedirect(target, requestUrl, redirects); + if (target && !refusal) return target; + throw new AppError('COMMAND_FAILED', `Cloud auth endpoint answered with ${refusal}.`, { + reason: CLOUD_AUTH_REQUEST_REASONS.redirectRefused.reason, + status: response.status, + hint: `Cloud auth requests stay on ${requestUrl.origin}. Check that it is the cloud API origin.`, + }); +} + +function describeRefusedRedirect( + target: URL | null, + requestUrl: URL, + redirects: number, +): string | undefined { + if (!target) return 'a redirect that has no readable Location'; + // Fetch rejects such a URL with an error that quotes it, and the target can echo a credential. + if (target.username || target.password) return 'a redirect to a URL with a username or password'; + if (target.origin !== requestUrl.origin) return 'a redirect to another origin'; + if (redirects >= MAX_CLOUD_AUTH_REDIRECTS) return 'more than three redirects'; + return undefined; +} diff --git a/src/cli/commands/__tests__/auth.test.ts b/src/cli/commands/__tests__/auth.test.ts index 59424801b1..5ad41a5588 100644 --- a/src/cli/commands/__tests__/auth.test.ts +++ b/src/cli/commands/__tests__/auth.test.ts @@ -24,7 +24,7 @@ function writeStoredCliSession( writeCliSession({ stateDir, session: { - version: 1, + version: 2, id: 'cli-1', cloudBaseUrl: 'https://cloud.example.test', refreshCredential: 'refresh-credential', diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index b976c831e5..f2d2f80086 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2517,7 +2517,7 @@ agent-device disconnect --remote-config ./agent-device.remote.json ``` - `connect` saves the connection and waits to lease a device and prepare Metro until a command needs them. `connect --remote-config ` uses a local profile instead of the cloud one. -- Cloud auth: `connect` uses your stored CLI session, and starts login in an interactive shell. In CI, use an `adc_live_...` service token. Manage the CLI session with `agent-device auth status`, `auth login`, and `auth logout`. Interactive login prints the code that the browser page must show; approve only when they match. When the cloud rotates the session credential during a refresh, the CLI stores the replacement and any session expiry. One command refreshes a stored session at a time; a command that waits too long fails with a session-file lock timeout, so retry it. A revoked session fails with `cli_session_revoked`, a refresh without a token fails with `cli_session_refresh_unanswered`, and a session directory that cannot be written fails with `cli_session_store_unwritable`. +- Cloud auth: `connect` uses your stored CLI session, and starts login in an interactive shell. In CI, use an `adc_live_...` service token. Manage the CLI session with `agent-device auth status`, `auth login`, and `auth logout`. Interactive login prints the code that the browser page must show; approve only when they match. When the cloud rotates the session credential during a refresh, the CLI stores the replacement and any session expiry. One command refreshes a stored session at a time; a command that waits too long fails with a session-file lock timeout, so retry it. A revoked session fails with `cli_session_revoked`, a refresh without a token fails with `cli_session_refresh_unanswered`, and a session directory that cannot be written fails with `cli_session_store_unwritable`. A refresh goes only to the cloud origin stored with the session: an `AGENT_DEVICE_CLOUD_BASE_URL` with another origin fails with `cloud_login_origin_mismatch` until you log in again or unset it. A session saved by an older CLI fails with `cli_session_issuer_unverified`; run `agent-device auth login`. Cloud auth requests follow at most three redirects on the same origin. A 307 or 308 resends the POST; a 301, 302 or 303 continues as a GET without the body. A redirect to another origin, a fourth redirect, or a target with no readable Location or with a username or password fails with `cloud_auth_redirect_refused` before anything is sent to it. - `AGENT_DEVICE_CLOUD_BASE_URL` is the bridge API origin, which is not always the dashboard. - On a connection with a lease provider, such as the cloud or `connect proxy`, every command must name the session with `--session`, `AGENT_DEVICE_SESSION`, or config, or it fails with `REMOTE_SESSION_REQUIRED`. On other profiles, commands without a session use the most recent connection, which is safe only for one sequential workflow. To replace a connection, pass `--session --force`. - After `connect`, normal commands reuse the connection. `connection status` shows `leaseId=pending` until the first command that needs a device. diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 5045333108..b0295f9c98 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -25,6 +25,9 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `cli_session_revoked` | The cloud answered a refresh by reporting the stored session revoked. | | `cli_session_refresh_unanswered` | The refresh answered without an access token, so the CLI has nothing to send. | | `cli_session_store_unwritable` | The directory holding the session file cannot be written, so its lock cannot be taken. | +| `cloud_login_origin_mismatch` | The cloud API origin named by AGENT_DEVICE_CLOUD_BASE_URL differs from the origin that issued the stored CLI session, so the stored credential is not sent. Log in with the named origin, or unset the override. | +| `cli_session_issuer_unverified` | The stored CLI session does not record the cloud that issued its credential, as a session saved by an older CLI does not, so the credential is not sent. Run agent-device auth login. | +| `cloud_auth_redirect_refused` | A cloud auth request got a redirect it does not follow: to another origin, past the third hop, or to a missing Location or one with a username or password. Nothing was sent to the target. | ### `back` @@ -57,6 +60,9 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `cli_session_revoked` | The cloud answered a refresh by reporting the stored session revoked. | | `cli_session_refresh_unanswered` | The refresh answered without an access token, so the CLI has nothing to send. | | `cli_session_store_unwritable` | The directory holding the session file cannot be written, so its lock cannot be taken. | +| `cloud_login_origin_mismatch` | The cloud API origin named by AGENT_DEVICE_CLOUD_BASE_URL differs from the origin that issued the stored CLI session, so the stored credential is not sent. Log in with the named origin, or unset the override. | +| `cli_session_issuer_unverified` | The stored CLI session does not record the cloud that issued its credential, as a session saved by an older CLI does not, so the credential is not sent. Run agent-device auth login. | +| `cloud_auth_redirect_refused` | A cloud auth request got a redirect it does not follow: to another origin, past the third hop, or to a missing Location or one with a username or password. Nothing was sent to the target. | | `plugin-unavailable` | The provider's plugin is present but cannot serve the provider; `details.failedPlugins` names what broke. | | `plugin-not-installed` | No plugin declares this provider; `details.installCommand` is the command that adds it. |