From 1fc5c1e1f3676e36a8e1c4cb7ed3a5d09dd307b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 19:26:38 +0100 Subject: [PATCH 01/11] fix(auth): send a stored CLI session only to the cloud that issued it AGENT_DEVICE_CLOUD_BASE_URL overrode the cloud origin stored with the CLI session, so the stored refresh credential went to whatever origin the variable named. A refresh now refuses an override with another origin (UNAUTHORIZED, reason cloud_login_origin_mismatch) before any request, and cloud auth requests no longer follow redirects, which would resend a credential or device code to the redirect target. --- src/cli/__tests__/auth-session.test.ts | 42 ++++++++++++++++++++++++++ src/cli/auth-session.ts | 30 +++++++++++++----- 2 files changed, 64 insertions(+), 8 deletions(-) diff --git a/src/cli/__tests__/auth-session.test.ts b/src/cli/__tests__/auth-session.test.ts index 2f4d0eb4df..b89a69fa3b 100644 --- a/src/cli/__tests__/auth-session.test.ts +++ b/src/cli/__tests__/auth-session.test.ts @@ -172,6 +172,48 @@ test('remote auth refreshes a stored CLI session into an agent token', async () fs.rmSync(tempRoot, { recursive: true, force: true }); }); +test('a stored CLI session is sent only to the cloud that issued it, without redirects', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-origin-'); + writeCliSession({ + stateDir: tempRoot, + session: { + version: 1, + id: 'session-origin', + cloudBaseUrl: 'https://cloud.example', + refreshCredential: 'adc_refresh_secret', + createdAt: '2026-01-01T00:00:00.000Z', + }, + }); + const requests: Array<{ url: string; redirect?: RequestRedirect }> = []; + const refresh = (env: Record) => + resolveRemoteAuth({ + command: 'snapshot', + flags: { ...baseFlags, daemonBaseUrl: 'https://bridge.agent-device.dev' }, + stateDir: tempRoot, + allowInteractiveLogin: false, + env, + io: { + fetch: async (url, init) => { + requests.push({ url: String(url), redirect: init?.redirect }); + return jsonResponse({ accessToken: 'adc_agent_fresh' }); + }, + }, + }); + + await assert.rejects( + () => refresh({ AGENT_DEVICE_CLOUD_BASE_URL: 'https://elsewhere.example' }), + (error) => normalizeError(error).details?.reason === 'cloud_login_origin_mismatch', + ); + assert.deepEqual(requests, []); + + const same = await refresh({ AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example/' }); + assert.equal(same.flags.daemonAuthToken, 'adc_agent_fresh'); + assert.deepEqual(requests, [ + { url: 'https://cloud.example/api/control-plane/cli-session/refresh', redirect: 'error' }, + ]); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + test('remote auth stores a refresh credential that the cloud rotated', async () => { const tempRoot = mkdtempForTestSync('agent-device-auth-rotate-'); const session = { diff --git a/src/cli/auth-session.ts b/src/cli/auth-session.ts index 988f391131..c132ae0483 100644 --- a/src/cli/auth-session.ts +++ b/src/cli/auth-session.ts @@ -325,7 +325,6 @@ export async function loginWithDeviceAuth(options: { stateDir: options.stateDir, session, flags: options.flags, - env, io: options.io, }); } catch (error) { @@ -537,7 +536,8 @@ async function resolveCliSessionAccess(options: { async () => { const session = readCliSession({ 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 +545,24 @@ 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 storedUrl = resolveCloudBaseUrl({}, session.cloudBaseUrl); + if (new URL(resolveCloudBaseUrl(env, storedUrl)).origin === new URL(storedUrl).origin) return; + throw new AppError('UNAUTHORIZED', 'The stored CLI session belongs to another cloud API origin.', { + reason: 'cloud_login_origin_mismatch', + 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 +574,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 +592,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 @@ -677,7 +690,6 @@ function storeRotatedCredential(options: { async function refreshAgentToken(options: { session: CliSessionRecord; flags: CliFlags; - env: EnvMap; io?: AuthIo; }): Promise<{ accessToken: string; @@ -685,9 +697,9 @@ async function refreshAgentToken(options: { refreshCredential?: string; sessionExpiresAt?: string; }> { - const cloudBaseUrl = resolveCloudBaseUrl(options.env, options.session.cloudBaseUrl); + // The refresh goes to the URL stored with the session, never to an override. const response = await postJson({ - baseUrl: cloudBaseUrl, + baseUrl: resolveCloudBaseUrl({}, options.session.cloudBaseUrl), pathName: CLI_SESSION_REFRESH_PATH, body: { refreshCredential: options.session.refreshCredential, @@ -808,6 +820,8 @@ async function postJson(options: { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(options.body), + // A redirect would resend a credential or device code to the redirect target. + redirect: 'error', signal: AbortSignal.timeout(HTTP_TIMEOUT_MS), }); return await readCloudJsonResponse(response, { From b40e6f6688ab0a4e317e7c47cb31bb3a97298dc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 19:31:47 +0100 Subject: [PATCH 02/11] test(auth): move the cloud origin test beside the module in its own file auth-session.test.ts is at the 1000-line cap. --- .../auth-session-cloud-origin.test.ts | 64 +++++++++++++++++++ src/cli/__tests__/auth-session.test.ts | 42 ------------ 2 files changed, 64 insertions(+), 42 deletions(-) create mode 100644 src/cli/__tests__/auth-session-cloud-origin.test.ts 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..7d489ac428 --- /dev/null +++ b/src/cli/__tests__/auth-session-cloud-origin.test.ts @@ -0,0 +1,64 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { normalizeError } from '@agent-device/kernel/errors'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { resolveRemoteAuth, writeCliSession } from '../auth-session.ts'; + +const baseFlags = { + json: false, + help: false, + version: false, + daemonBaseUrl: 'https://daemon.example', + tenant: 'acme', + runId: 'run-123', +}; + +function jsonResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); +} + +test('a stored CLI session is sent only to the cloud that issued it, without redirects', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-origin-'); + writeCliSession({ + stateDir: tempRoot, + session: { + version: 1, + id: 'session-origin', + cloudBaseUrl: 'https://cloud.example', + refreshCredential: 'adc_refresh_secret', + createdAt: '2026-01-01T00:00:00.000Z', + }, + }); + const requests: Array<{ url: string; redirect?: RequestRedirect }> = []; + const refresh = (env: Record) => + resolveRemoteAuth({ + command: 'snapshot', + flags: { ...baseFlags, daemonBaseUrl: 'https://bridge.agent-device.dev' }, + stateDir: tempRoot, + allowInteractiveLogin: false, + env, + io: { + fetch: async (url, init) => { + requests.push({ url: String(url), redirect: init?.redirect }); + return jsonResponse({ accessToken: 'adc_agent_fresh' }); + }, + }, + }); + + await assert.rejects( + () => refresh({ AGENT_DEVICE_CLOUD_BASE_URL: 'https://elsewhere.example' }), + (error) => normalizeError(error).details?.reason === 'cloud_login_origin_mismatch', + ); + assert.deepEqual(requests, []); + + const same = await refresh({ AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example/' }); + assert.equal(same.flags.daemonAuthToken, 'adc_agent_fresh'); + assert.deepEqual(requests, [ + { url: 'https://cloud.example/api/control-plane/cli-session/refresh', redirect: 'error' }, + ]); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); diff --git a/src/cli/__tests__/auth-session.test.ts b/src/cli/__tests__/auth-session.test.ts index b89a69fa3b..2f4d0eb4df 100644 --- a/src/cli/__tests__/auth-session.test.ts +++ b/src/cli/__tests__/auth-session.test.ts @@ -172,48 +172,6 @@ test('remote auth refreshes a stored CLI session into an agent token', async () fs.rmSync(tempRoot, { recursive: true, force: true }); }); -test('a stored CLI session is sent only to the cloud that issued it, without redirects', async () => { - const tempRoot = mkdtempForTestSync('agent-device-auth-origin-'); - writeCliSession({ - stateDir: tempRoot, - session: { - version: 1, - id: 'session-origin', - cloudBaseUrl: 'https://cloud.example', - refreshCredential: 'adc_refresh_secret', - createdAt: '2026-01-01T00:00:00.000Z', - }, - }); - const requests: Array<{ url: string; redirect?: RequestRedirect }> = []; - const refresh = (env: Record) => - resolveRemoteAuth({ - command: 'snapshot', - flags: { ...baseFlags, daemonBaseUrl: 'https://bridge.agent-device.dev' }, - stateDir: tempRoot, - allowInteractiveLogin: false, - env, - io: { - fetch: async (url, init) => { - requests.push({ url: String(url), redirect: init?.redirect }); - return jsonResponse({ accessToken: 'adc_agent_fresh' }); - }, - }, - }); - - await assert.rejects( - () => refresh({ AGENT_DEVICE_CLOUD_BASE_URL: 'https://elsewhere.example' }), - (error) => normalizeError(error).details?.reason === 'cloud_login_origin_mismatch', - ); - assert.deepEqual(requests, []); - - const same = await refresh({ AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example/' }); - assert.equal(same.flags.daemonAuthToken, 'adc_agent_fresh'); - assert.deepEqual(requests, [ - { url: 'https://cloud.example/api/control-plane/cli-session/refresh', redirect: 'error' }, - ]); - fs.rmSync(tempRoot, { recursive: true, force: true }); -}); - test('remote auth stores a refresh credential that the cloud rotated', async () => { const tempRoot = mkdtempForTestSync('agent-device-auth-rotate-'); const session = { From 7900b0e9a5a02b22a96f87478a373ced48eb0f25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 19:38:32 +0100 Subject: [PATCH 03/11] fix(auth): declare the cloud login origin mismatch reason in a reason table R89 measures wire-published reason literals against the merge-base. Read the reason from a ReasonTable beside the origin check and regenerate the error reasons page. --- src/cli/auth-session.ts | 6 +++++- website/docs/docs/error-reasons.md | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/cli/auth-session.ts b/src/cli/auth-session.ts index c132ae0483..65de1aa60b 100644 --- a/src/cli/auth-session.ts +++ b/src/cli/auth-session.ts @@ -32,6 +32,10 @@ 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' }, } as const satisfies ReasonTable<'auth'>; export type CliSessionRecord = { @@ -558,7 +562,7 @@ function assertStoredSessionOrigin(session: CliSessionRecord, env: EnvMap): void const storedUrl = resolveCloudBaseUrl({}, session.cloudBaseUrl); if (new URL(resolveCloudBaseUrl(env, storedUrl)).origin === new URL(storedUrl).origin) return; throw new AppError('UNAUTHORIZED', 'The stored CLI session belongs to another cloud API origin.', { - reason: 'cloud_login_origin_mismatch', + reason: CLI_SESSION_REASONS.loginOriginMismatch.reason, hint: 'Run agent-device auth login with this AGENT_DEVICE_CLOUD_BASE_URL, or unset it.', }); } diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 5045333108..62363e9e23 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -25,6 +25,7 @@ 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. | ### `back` From b19b5745683ec1334a53e1a48190bd011ba0de59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 20:08:34 +0100 Subject: [PATCH 04/11] fix(auth): refresh at the stored URL, compare the stored origin before a rotation, and document the rule A same-origin AGENT_DEVICE_CLOUD_BASE_URL still names the connection, while the refresh goes to the URL stored with the session. A rotation is not stored over a session that a login moved to another cloud. The commands docs state the stored-origin rule and the cloud_login_origin_mismatch outcome. --- .../auth-session-cloud-origin.test.ts | 33 ++++++++++++++++++- src/cli/auth-session.ts | 7 +++- website/docs/docs/commands.md | 2 +- 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/cli/__tests__/auth-session-cloud-origin.test.ts b/src/cli/__tests__/auth-session-cloud-origin.test.ts index 7d489ac428..acb5fefb19 100644 --- a/src/cli/__tests__/auth-session-cloud-origin.test.ts +++ b/src/cli/__tests__/auth-session-cloud-origin.test.ts @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import { normalizeError } from '@agent-device/kernel/errors'; import { mkdtempForTestSync } from '@agent-device/test-kit'; -import { resolveRemoteAuth, writeCliSession } from '../auth-session.ts'; +import { readCliSession, resolveRemoteAuth, writeCliSession } from '../auth-session.ts'; const baseFlags = { json: false, @@ -62,3 +62,34 @@ test('a stored CLI session is sent only to the cloud that issued it, without red ]); 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-'); + const session = { + version: 1 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, daemonBaseUrl: 'https://bridge.agent-device.dev' }, + 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); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); diff --git a/src/cli/auth-session.ts b/src/cli/auth-session.ts index 65de1aa60b..fe0092648d 100644 --- a/src/cli/auth-session.ts +++ b/src/cli/auth-session.ts @@ -670,7 +670,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; diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index b976c831e5..06c033d560 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, and cloud auth requests do not follow redirects. - `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. From cfb0d548d388d1128c4af7b32fe6af41a908861a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 13:08:23 +0100 Subject: [PATCH 05/11] fix(auth): refuse a session that does not record its issuer and follow bounded same-origin auth redirects The stored CLI session format moves to version 2, which records the origin that issued the credential. A version 1 record, or one whose issuer is not its URL's origin, fails with cli_session_issuer_unverified before any request, and agent-device auth login replaces it. Cloud auth requests (device-auth start, poll and CLI session refresh) follow at most three 307 or 308 redirects whose target has the original request origin, with the same POST body. A cross-origin target, a fourth redirect, or a 301, 302 or 303 fails with a typed reason before anything is sent again. --- .../auth-session-cloud-origin.test.ts | 230 ++++++++++++---- .../__tests__/auth-session-exchange.test.ts | 3 +- .../__tests__/auth-session-redirect.test.ts | 260 ++++++++++++++++++ .../__tests__/auth-session-refresh.test.ts | 3 +- .../__tests__/auth-session-refusal.test.ts | 3 +- src/cli/__tests__/auth-session-umask.test.ts | 3 +- src/cli/__tests__/auth-session.test.ts | 30 +- src/cli/auth-session.ts | 114 ++++---- src/cli/cli-session-format.ts | 51 ++++ src/cli/cloud-auth-request.ts | 118 ++++++++ src/cli/commands/__tests__/auth.test.ts | 3 +- website/docs/docs/commands.md | 2 +- website/docs/docs/error-reasons.md | 9 + 13 files changed, 692 insertions(+), 137 deletions(-) create mode 100644 src/cli/__tests__/auth-session-redirect.test.ts create mode 100644 src/cli/cli-session-format.ts create mode 100644 src/cli/cloud-auth-request.ts diff --git a/src/cli/__tests__/auth-session-cloud-origin.test.ts b/src/cli/__tests__/auth-session-cloud-origin.test.ts index acb5fefb19..219a931742 100644 --- a/src/cli/__tests__/auth-session-cloud-origin.test.ts +++ b/src/cli/__tests__/auth-session-cloud-origin.test.ts @@ -1,15 +1,22 @@ 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 { readCliSession, resolveRemoteAuth, writeCliSession } from '../auth-session.ts'; +import { + loginWithDeviceAuth, + readCliSession, + resolveCliSessionPath, + resolveRemoteAuth, + writeCliSession, +} from '../auth-session.ts'; const baseFlags = { json: false, help: false, version: false, - daemonBaseUrl: 'https://daemon.example', + daemonBaseUrl: 'https://bridge.agent-device.dev', tenant: 'acme', runId: 'run-123', }; @@ -21,75 +28,182 @@ function jsonResponse(body: unknown): Response { }); } -test('a stored CLI session is sent only to the cloud that issued it, without redirects', async () => { +/** 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' }); + }, + }, + }); +} + +/** 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-'); - writeCliSession({ - stateDir: tempRoot, - session: { - version: 1, - id: 'session-origin', + try { + writeCliSession({ + stateDir: tempRoot, + session: { + version: 2, + id: 'session-origin', + cloudBaseUrl: 'https://cloud.example', + issuerOrigin: '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, ['https://cloud.example/api/control-plane/cli-session/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_secret', + issuerOrigin: 'https://cloud.example', + refreshCredential: 'adc_refresh_old', createdAt: '2026-01-01T00:00:00.000Z', - }, - }); - const requests: Array<{ url: string; redirect?: RequestRedirect }> = []; - const refresh = (env: Record) => - resolveRemoteAuth({ + }; + writeCliSession({ stateDir: tempRoot, session }); + const moved = { + ...session, + cloudBaseUrl: 'https://other-cloud.example', + issuerOrigin: 'https://other-cloud.example', + }; + + await resolveRemoteAuth({ command: 'snapshot', - flags: { ...baseFlags, daemonBaseUrl: 'https://bridge.agent-device.dev' }, + flags: baseFlags, stateDir: tempRoot, allowInteractiveLogin: false, - env, + env: {}, io: { - fetch: async (url, init) => { - requests.push({ url: String(url), redirect: init?.redirect }); - return jsonResponse({ accessToken: 'adc_agent_fresh' }); + 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' }); }, }, }); - await assert.rejects( - () => refresh({ AGENT_DEVICE_CLOUD_BASE_URL: 'https://elsewhere.example' }), - (error) => normalizeError(error).details?.reason === 'cloud_login_origin_mismatch', - ); - assert.deepEqual(requests, []); - - const same = await refresh({ AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example/' }); - assert.equal(same.flags.daemonAuthToken, 'adc_agent_fresh'); - assert.deepEqual(requests, [ - { url: 'https://cloud.example/api/control-plane/cli-session/refresh', redirect: 'error' }, - ]); - fs.rmSync(tempRoot, { recursive: true, force: true }); + assert.deepEqual(readCliSession({ stateDir: tempRoot }), moved); + } 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-'); - const session = { - version: 1 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, daemonBaseUrl: 'https://bridge.agent-device.dev' }, - 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' }); +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 loginWithDeviceAuth({ + stateDir: tempRoot, + flags: baseFlags, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example/' }, + io: { + stdinIsTTY: true, + stdoutIsTTY: true, + stderr: { write: () => true }, + openBrowser: async () => {}, + fetch: async (url) => + String(url).endsWith('/device-auth/start') + ? jsonResponse({ + deviceCode: 'device-secret', + userCode: 'ABCD-EFGH', + verificationUri: 'https://cloud.example/authorize', + }) + : jsonResponse({ + status: 'approved', + accessToken: 'adc_agent_login', + cliSession: { id: 'session-new', refreshCredential: 'adc_refresh_new' }, + }), }, - }, - }); + }); + assert.equal(login.session.version, 2); + assert.equal(login.session.issuerOrigin, 'https://cloud.example'); + + const refreshed = await refreshWith(tempRoot, {}, requests); + assert.equal(refreshed.flags.daemonAuthToken, 'adc_agent_fresh'); + assert.deepEqual(requests, ['https://cloud.example/api/control-plane/cli-session/refresh']); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('a session whose recorded issuer is not the origin of its URL is refused', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-origin-issuer-'); + try { + writeRawSession(tempRoot, { + version: 2, + id: 'session-edited', + cloudBaseUrl: 'https://cloud.example', + issuerOrigin: 'https://other-cloud.example', + refreshCredential: 'adc_refresh_other', + createdAt: '2026-01-01T00:00:00.000Z', + }); + const requests: string[] = []; - assert.deepEqual(readCliSession({ stateDir: tempRoot }), moved); - fs.rmSync(tempRoot, { recursive: true, force: true }); + await assert.rejects(() => refreshWith(tempRoot, {}, requests), isIssuerUnverified); + assert.deepEqual(requests, []); + } 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..9f87483202 100644 --- a/src/cli/__tests__/auth-session-exchange.test.ts +++ b/src/cli/__tests__/auth-session-exchange.test.ts @@ -35,9 +35,10 @@ function writeStoredSession(stateDir: string, overrides: Record writeCliSession({ stateDir, session: { - version: 1, + version: 2, id: 'session-pairing', cloudBaseUrl: 'https://cloud.example', + issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_old', createdAt: '2026-01-01T00:00:00.000Z', ...overrides, diff --git a/src/cli/__tests__/auth-session-redirect.test.ts b/src/cli/__tests__/auth-session-redirect.test.ts new file mode 100644 index 0000000000..3c4aaa0bef --- /dev/null +++ b/src/cli/__tests__/auth-session-redirect.test.ts @@ -0,0 +1,260 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { normalizeError } from '@agent-device/kernel/errors'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { + loginWithDeviceAuth, + readCliSession, + 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'; + +type SentRequest = { url: string; method?: string; body?: unknown; redirect?: RequestRedirect }; + +function jsonResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); +} + +function redirect(status: number, location: string): Response { + return new Response(null, { status, headers: { location } }); +} + +/** + * A cloud that answers each URL from `routes` and records every request it receives. A URL without + * a route answers 404, so a request that reaches an unexpected target is visible in `sent`. + */ +function fakeCloud(routes: Record Response>) { + const sent: SentRequest[] = []; + const fetch = async (url: URL | RequestInfo, init?: RequestInit): Promise => { + sent.push({ + url: String(url), + method: init?.method, + body: typeof init?.body === 'string' ? JSON.parse(init.body) : init?.body, + redirect: init?.redirect, + }); + return routes[String(url)]?.() ?? new Response('{}', { status: 404 }); + }; + return { sent, fetch }; +} + +const startAnswer = () => + jsonResponse({ + deviceCode: 'device-secret', + userCode: 'ABCD-EFGH', + verificationUri: 'https://cloud.example/authorize', + }); +const pollAnswer = () => + jsonResponse({ + status: 'approved', + accessToken: 'adc_agent_login', + cliSession: { id: 'session-login', refreshCredential: 'adc_refresh_login' }, + }); + +function login(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, + }, + }); +} + +function refresh(stateDir: string, fetch: typeof globalThis.fetch) { + writeCliSession({ + stateDir, + session: { + version: 2, + id: 'session-stored', + cloudBaseUrl: 'https://cloud.example', + issuerOrigin: 'https://cloud.example', + refreshCredential: 'adc_refresh_stored', + createdAt: '2026-01-01T00:00:00.000Z', + }, + }); + return resolveRemoteAuth({ + command: 'snapshot', + flags: baseFlags, + stateDir, + allowInteractiveLogin: false, + env: {}, + io: { fetch }, + }); +} + +const hasReason = (reason: string) => (error: unknown) => + normalizeError(error).details?.reason === reason; + +async function withStateDir(run: (stateDir: string) => Promise): Promise { + const stateDir = mkdtempForTestSync('agent-device-auth-redirect-'); + try { + await run(stateDir); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } +} + +test('a login follows a same-origin 307 at device-auth start and a 308 at poll with the same POST', async () => { + await withStateDir(async (stateDir) => { + const cloud = fakeCloud({ + [START]: () => redirect(307, '/v2/device-auth/start'), + 'https://cloud.example/v2/device-auth/start': startAnswer, + [POLL]: () => redirect(308, 'https://cloud.example/v2/device-auth/poll'), + 'https://cloud.example/v2/device-auth/poll': pollAnswer, + }); + + const result = await login(stateDir, cloud.fetch); + + assert.equal(result.accessToken, 'adc_agent_login'); + assert.deepEqual( + cloud.sent.map(({ url, method, redirect }) => ({ url, method, redirect })), + [ + START, + 'https://cloud.example/v2/device-auth/start', + POLL, + 'https://cloud.example/v2/device-auth/poll', + ].map((url) => ({ url, method: 'POST', redirect: 'manual' })), + ); + assert.deepEqual(cloud.sent[1]?.body, cloud.sent[0]?.body); + assert.deepEqual(cloud.sent[3]?.body, { deviceCode: 'device-secret' }); + }); +}); + +test('a login stops at a cross-origin redirect at device-auth start before it is followed', async () => { + await withStateDir(async (stateDir) => { + const cloud = fakeCloud({ + [START]: () => redirect(307, 'https://elsewhere.example/device-auth/start'), + }); + + await assert.rejects( + () => login(stateDir, cloud.fetch), + hasReason('cloud_auth_redirect_cross_origin'), + ); + assert.deepEqual( + cloud.sent.map(({ url }) => url), + [START], + ); + }); +}); + +test('a login stops at a cross-origin redirect at device-auth poll and stores nothing', async () => { + await withStateDir(async (stateDir) => { + const cloud = fakeCloud({ + [START]: startAnswer, + [POLL]: () => redirect(308, 'https://elsewhere.example/device-auth/poll'), + }); + + await assert.rejects( + () => login(stateDir, cloud.fetch), + hasReason('cloud_auth_redirect_cross_origin'), + ); + assert.deepEqual( + cloud.sent.map(({ url }) => url), + [START, POLL], + ); + assert.equal(readCliSession({ stateDir }), null); + }); +}); + +test('a refresh follows a same-origin 307 and sends the credential again only there', async () => { + await withStateDir(async (stateDir) => { + const cloud = fakeCloud({ + [REFRESH]: () => redirect(307, '/unlock'), + 'https://cloud.example/unlock': () => jsonResponse({ accessToken: 'adc_agent_fresh' }), + }); + + const result = await refresh(stateDir, cloud.fetch); + + assert.equal(result.flags.daemonAuthToken, 'adc_agent_fresh'); + assert.deepEqual( + cloud.sent.map(({ url, method }) => ({ url, method })), + [ + { url: REFRESH, method: 'POST' }, + { url: 'https://cloud.example/unlock', method: 'POST' }, + ], + ); + assert.deepEqual(cloud.sent[1]?.body, cloud.sent[0]?.body); + }); +}); + +test('a refresh stops at a cross-origin 308 and never sends the credential there', async () => { + await withStateDir(async (stateDir) => { + const cloud = fakeCloud({ + [REFRESH]: () => redirect(308, 'https://elsewhere.example/refresh'), + }); + + await assert.rejects( + () => refresh(stateDir, cloud.fetch), + hasReason('cloud_auth_redirect_cross_origin'), + ); + assert.deepEqual( + cloud.sent.map(({ url }) => url), + [REFRESH], + ); + }); +}); + +test('a refresh follows three same-origin redirects and refuses a fourth', async () => { + await withStateDir(async (stateDir) => { + const hops = (count: number) => { + const routes: Record Response> = {}; + let from = REFRESH; + for (let hop = 1; hop <= count; hop += 1) { + routes[from] = () => redirect(307, `/hop-${hop}`); + from = `https://cloud.example/hop-${hop}`; + } + routes[from] = () => jsonResponse({ accessToken: 'adc_agent_fresh' }); + return fakeCloud(routes); + }; + + const three = hops(3); + assert.equal((await refresh(stateDir, three.fetch)).flags.daemonAuthToken, 'adc_agent_fresh'); + assert.equal(three.sent.length, 4); + + const four = hops(4); + await assert.rejects( + () => refresh(stateDir, four.fetch), + hasReason('cloud_auth_redirect_limit'), + ); + assert.equal(four.sent.length, 4); + }); +}); + +test('a refresh refuses a 301, 302 or 303 instead of resending the POST as a GET', async () => { + await withStateDir(async (stateDir) => { + for (const status of [301, 302, 303]) { + const cloud = fakeCloud({ [REFRESH]: () => redirect(status, '/unlock') }); + + await assert.rejects( + () => refresh(stateDir, cloud.fetch), + hasReason('cloud_auth_redirect_unsupported'), + ); + assert.deepEqual( + cloud.sent.map(({ url }) => url), + [REFRESH], + ); + } + }); +}); diff --git a/src/cli/__tests__/auth-session-refresh.test.ts b/src/cli/__tests__/auth-session-refresh.test.ts index 543b7defda..68c5561008 100644 --- a/src/cli/__tests__/auth-session-refresh.test.ts +++ b/src/cli/__tests__/auth-session-refresh.test.ts @@ -37,9 +37,10 @@ function writeStoredSession(stateDir: string, overrides: Record writeCliSession({ stateDir, session: { - version: 1, + version: 2, id: 'session-refresh', cloudBaseUrl: 'https://cloud.example', + issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_old', createdAt: '2026-01-01T00:00:00.000Z', ...overrides, diff --git a/src/cli/__tests__/auth-session-refusal.test.ts b/src/cli/__tests__/auth-session-refusal.test.ts index 0faba91711..a0d262532d 100644 --- a/src/cli/__tests__/auth-session-refusal.test.ts +++ b/src/cli/__tests__/auth-session-refusal.test.ts @@ -35,9 +35,10 @@ function writeStoredSession(stateDir: string): void { writeCliSession({ stateDir, session: { - version: 1, + version: 2, id: 'session-refusal', cloudBaseUrl: 'https://cloud.example', + issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_stored', createdAt: '2026-01-01T00:00:00.000Z', }, diff --git a/src/cli/__tests__/auth-session-umask.test.ts b/src/cli/__tests__/auth-session-umask.test.ts index 80d7a4ed3c..e64e5cd7e2 100644 --- a/src/cli/__tests__/auth-session-umask.test.ts +++ b/src/cli/__tests__/auth-session-umask.test.ts @@ -9,9 +9,10 @@ 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', + issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_umask', createdAt: '2026-01-01T00:00:00.000Z', }; diff --git a/src/cli/__tests__/auth-session.test.ts b/src/cli/__tests__/auth-session.test.ts index 2f4d0eb4df..f5a3295e22 100644 --- a/src/cli/__tests__/auth-session.test.ts +++ b/src/cli/__tests__/auth-session.test.ts @@ -100,9 +100,10 @@ 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', + issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_should_not_be_used', createdAt: '2026-01-01T00:00:00.000Z', }, @@ -132,9 +133,10 @@ 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', + issuerOrigin: 'https://cloud.example', workspaceId: 'acme', refreshCredential: 'adc_refresh_secret', createdAt: '2026-01-01T00:00:00.000Z', @@ -175,9 +177,10 @@ 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', + issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_old', createdAt: '2026-01-01T00:00:00.000Z', expiresAt: '2026-12-01T00:00:00.000Z', @@ -226,9 +229,10 @@ 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', + issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_old', createdAt: '2026-01-01T00:00:00.000Z', }; @@ -286,9 +290,10 @@ 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', + issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_old', createdAt: '2026-01-01T00:00:00.000Z', }; @@ -347,9 +352,10 @@ 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', + issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_old', createdAt: '2026-01-01T00:00:00.000Z', }, @@ -465,9 +471,10 @@ 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', + issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_503', createdAt: '2026-01-01T00:00:00.000Z', }; @@ -515,9 +522,10 @@ 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', + issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_revoked', createdAt: '2026-01-01T00:00:00.000Z', }, @@ -623,9 +631,10 @@ 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', + issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_hidden', createdAt: '2026-01-01T00:00:00.000Z', }, @@ -873,9 +882,10 @@ 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', + issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_first', createdAt: '2026-01-01T00:00:00.000Z', }; diff --git a/src/cli/auth-session.ts b/src/cli/auth-session.ts index fe0092648d..7fe9539723 100644 --- a/src/cli/auth-session.ts +++ b/src/cli/auth-session.ts @@ -5,7 +5,12 @@ 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 { postCloudAuthJson } from './cloud-auth-request.ts'; +import { + CLI_SESSION_FORMAT_VERSION, + parseCliSessionRecord, + type CliSessionRecord, +} from './cli-session-format.ts'; const DEFAULT_CLOUD_BASE_URL = 'https://cloud.agent-device.dev'; const DEVICE_AUTH_START_PATH = '/api/control-plane/device-auth/start'; @@ -13,7 +18,6 @@ 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 @@ -35,21 +39,12 @@ const CLI_SESSION_REASONS = { // 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' }, + 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'; @@ -248,7 +243,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: { @@ -300,9 +295,11 @@ 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, + // Every login request stays on this origin, so the credential came from it. + issuerOrigin: new URL(cloudBaseUrl).origin, workspaceId: approved.cliSession?.workspaceId, accountId: approved.cliSession?.accountId, name: approved.cliSession?.name, @@ -352,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 }); @@ -531,14 +541,14 @@ 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; assertStoredSessionOrigin(session, env); return await exchangeCliSessionAccess({ stateDir, session, flags, io }); @@ -561,10 +571,14 @@ async function resolveCliSessionAccess(options: { function assertStoredSessionOrigin(session: CliSessionRecord, env: EnvMap): void { const storedUrl = resolveCloudBaseUrl({}, session.cloudBaseUrl); if (new URL(resolveCloudBaseUrl(env, storedUrl)).origin === new URL(storedUrl).origin) 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.', - }); + 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.', + }, + ); } /** @@ -707,7 +721,7 @@ async function refreshAgentToken(options: { sessionExpiresAt?: string; }> { // The refresh goes to the URL stored with the session, never to an override. - const response = await postJson({ + const response = await postCloudAuthJson({ baseUrl: resolveCloudBaseUrl({}, options.session.cloudBaseUrl), pathName: CLI_SESSION_REFRESH_PATH, body: { @@ -791,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 }, @@ -814,32 +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), - // A redirect would resend a credential or device code to the redirect target. - redirect: 'error', - 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..1087158342 --- /dev/null +++ b/src/cli/cli-session-format.ts @@ -0,0 +1,51 @@ +// Version 2 records the origin that issued the credential. Version 1 did not, and an older login +// could follow a redirect to another cloud and save that cloud's credential under its own URL. +export const CLI_SESSION_FORMAT_VERSION = 2; + +export type CliSessionRecord = { + version: typeof CLI_SESSION_FORMAT_VERSION; + id: string; + cloudBaseUrl: string; + /** The origin of `cloudBaseUrl` that the login reached through same-origin requests only. */ + issuerOrigin: string; + workspaceId?: string; + accountId?: string; + name?: string; + refreshCredential: string; + createdAt: string; + expiresAt?: string; +}; + +/** + * Parses the session file text. A record whose issuer the file does not establish answers + * `unverified`: an older format version, or a record whose `issuerOrigin` is not its URL's origin. + * Text that is not a record with a credential 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 || + !hasText(parsed.id) || + !hasText(parsed.cloudBaseUrl) || + !hasText(parsed.createdAt) || + parsed.issuerOrigin !== readOrigin(parsed.cloudBaseUrl) + ) { + return 'unverified'; + } + return parsed as CliSessionRecord; +} + +function readOrigin(url: string): string | undefined { + try { + return new URL(url).origin; + } catch { + return undefined; + } +} + +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..955b519c0e --- /dev/null +++ b/src/cli/cloud-auth-request.ts @@ -0,0 +1,118 @@ +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 keeps the method and body only for these. A 301, 302 or 303 would turn the POST into a GET. +const METHOD_PRESERVING_REDIRECT_STATUSES = new Set([307, 308]); + +/** Every `details.reason` a cloud auth request publishes about a redirect it does not follow. */ +const CLOUD_AUTH_REQUEST_REASONS = { + // A cloud auth request was redirected to another origin. The request was not sent there, so no + // credential or device code left the requested origin. + crossOriginRedirect: { reason: 'cloud_auth_redirect_cross_origin', commands: ['connect'] }, + // A cloud auth request was redirected more than three times within its origin. + redirectLimit: { reason: 'cloud_auth_redirect_limit', commands: ['connect'] }, + // A cloud auth request got a redirect that cannot keep its POST: a 301, 302 or 303, or one with + // no readable Location. + unsupportedRedirect: { reason: 'cloud_auth_redirect_unsupported', 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 only with a 307 or 308, which keep the method and body. Any other redirect + * fails with a typed reason before anything is sent again. + */ +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 body = JSON.stringify(options.body); + // One timeout covers the whole redirect chain. + const signal = AbortSignal.timeout(HTTP_TIMEOUT_MS); + let url = requestUrl; + for (let redirects = 0; ; redirects += 1) { + const response = await fetchImpl(url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body, + redirect: 'manual', + signal, + }); + if (!isRedirect(response)) { + 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); + } +} + +function isRedirect(response: Response): boolean { + return response.type === 'opaqueredirect' || REDIRECT_STATUSES.has(response.status); +} + +function readRedirectTarget( + response: Response, + current: URL, + requestUrl: URL, + redirects: number, +): URL { + const { status } = response; + const location = response.headers.get('location'); + const target = location ? parseUrl(location, current) : undefined; + if (!METHOD_PRESERVING_REDIRECT_STATUSES.has(status) || !target) { + throw redirectRefusal( + 'Cloud auth endpoint answered with a redirect that cannot keep the request.', + CLOUD_AUTH_REQUEST_REASONS.unsupportedRedirect.reason, + status, + requestUrl, + ); + } + if (target.origin !== requestUrl.origin) { + throw redirectRefusal( + 'Cloud auth endpoint redirected the request to another origin.', + CLOUD_AUTH_REQUEST_REASONS.crossOriginRedirect.reason, + status, + requestUrl, + ); + } + if (redirects >= MAX_CLOUD_AUTH_REDIRECTS) { + throw redirectRefusal( + 'Cloud auth endpoint redirected the request too many times.', + CLOUD_AUTH_REQUEST_REASONS.redirectLimit.reason, + status, + requestUrl, + ); + } + return target; +} + +function parseUrl(location: string, base: URL): URL | undefined { + try { + return new URL(location, base); + } catch { + return undefined; + } +} + +function redirectRefusal(message: string, reason: string, status: number, requestUrl: URL) { + return new AppError('COMMAND_FAILED', message, { + reason, + status, + hint: `Check that AGENT_DEVICE_CLOUD_BASE_URL names the cloud API origin that answers auth requests (now ${requestUrl.origin}).`, + }); +} diff --git a/src/cli/commands/__tests__/auth.test.ts b/src/cli/commands/__tests__/auth.test.ts index 59424801b1..a82a225a2a 100644 --- a/src/cli/commands/__tests__/auth.test.ts +++ b/src/cli/commands/__tests__/auth.test.ts @@ -24,9 +24,10 @@ function writeStoredCliSession( writeCliSession({ stateDir, session: { - version: 1, + version: 2, id: 'cli-1', cloudBaseUrl: 'https://cloud.example.test', + issuerOrigin: 'https://cloud.example.test', refreshCredential: 'refresh-credential', createdAt: '2026-01-01T00:00:00.000Z', ...overrides, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 06c033d560..2a687d1d53 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`. 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, and cloud auth requests do not follow redirects. +- 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 307 or 308 redirects on the same origin; a redirect to another origin, a fourth redirect, or a 301, 302 or 303 fails with `cloud_auth_redirect_cross_origin`, `cloud_auth_redirect_limit` or `cloud_auth_redirect_unsupported`. - `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 62363e9e23..501b860f0d 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -26,6 +26,10 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `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_cross_origin` | A cloud auth request was redirected to another origin. The request was not sent there, so no credential or device code left the requested origin. | +| `cloud_auth_redirect_limit` | A cloud auth request was redirected more than three times within its origin. | +| `cloud_auth_redirect_unsupported` | A cloud auth request got a redirect that cannot keep its POST: a 301, 302 or 303, or one with no readable Location. | ### `back` @@ -58,6 +62,11 @@ 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_cross_origin` | A cloud auth request was redirected to another origin. The request was not sent there, so no credential or device code left the requested origin. | +| `cloud_auth_redirect_limit` | A cloud auth request was redirected more than three times within its origin. | +| `cloud_auth_redirect_unsupported` | A cloud auth request got a redirect that cannot keep its POST: a 301, 302 or 303, or one with no readable Location. | | `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. | From 617543732e92fd076de7529abec4e14ca2b1cb45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 13:18:35 +0100 Subject: [PATCH 06/11] perf(cli): load the cloud auth transport on demand --- src/cli/auth-session.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cli/auth-session.ts b/src/cli/auth-session.ts index 7fe9539723..ae9080e7da 100644 --- a/src/cli/auth-session.ts +++ b/src/cli/auth-session.ts @@ -5,13 +5,15 @@ 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 { postCloudAuthJson } from './cloud-auth-request.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'; From 56dcb26ce22086fe1e1951f98bd4371c35c27b88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 14:16:55 +0100 Subject: [PATCH 07/11] fix(cli): follow same-origin 301/302/303 auth redirects as GET and refuse credential-bearing targets --- .../__tests__/auth-session-redirect.test.ts | 167 ++++++++++++++++-- src/cli/cloud-auth-request.ts | 47 +++-- website/docs/docs/commands.md | 2 +- website/docs/docs/error-reasons.md | 4 +- 4 files changed, 188 insertions(+), 32 deletions(-) diff --git a/src/cli/__tests__/auth-session-redirect.test.ts b/src/cli/__tests__/auth-session-redirect.test.ts index 3c4aaa0bef..51b0cd1c37 100644 --- a/src/cli/__tests__/auth-session-redirect.test.ts +++ b/src/cli/__tests__/auth-session-redirect.test.ts @@ -23,7 +23,13 @@ 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'; -type SentRequest = { url: string; method?: string; body?: unknown; redirect?: RequestRedirect }; +type SentRequest = { + url: string; + method?: string; + body?: unknown; + contentType?: string | null; + redirect?: RequestRedirect; +}; function jsonResponse(body: unknown): Response { return new Response(JSON.stringify(body), { @@ -47,6 +53,7 @@ function fakeCloud(routes: Record Response>) { url: String(url), method: init?.method, body: typeof init?.body === 'string' ? JSON.parse(init.body) : init?.body, + contentType: new Headers(init?.headers).get('content-type'), redirect: init?.redirect, }); return routes[String(url)]?.() ?? new Response('{}', { status: 404 }); @@ -242,19 +249,151 @@ test('a refresh follows three same-origin redirects and refuses a fourth', async }); }); -test('a refresh refuses a 301, 302 or 303 instead of resending the POST as a GET', async () => { +const requestShape = ({ url, method, body, contentType }: SentRequest) => ({ + url, + method, + body, + contentType, +}); +const sentAsGet = (url: string) => ({ url, method: 'GET', body: undefined, contentType: null }); +const flagFields = { + tenant: 'acme', + runId: 'run-123', + daemonBaseUrl: 'https://bridge.agent-device.dev', +}; +const postedAs = (body: Record) => ({ + method: 'POST', + body, + contentType: 'application/json', +}); +const postedStart = postedAs({ client: 'agent-device', ...flagFields }); +const postedPoll = postedAs({ deviceCode: 'device-secret' }); +const postedRefresh = postedAs({ + refreshCredential: 'adc_refresh_stored', + acceptsRotatedRefreshCredential: true, + ...flagFields, +}); + +for (const status of [301, 302, 303]) { + test(`a login follows a same-origin ${status} at device-auth start and poll as a GET without the body`, async () => { + await withStateDir(async (stateDir) => { + const cloud = fakeCloud({ + [START]: () => redirect(status, '/v2/device-auth/start'), + 'https://cloud.example/v2/device-auth/start': startAnswer, + [POLL]: () => redirect(status, 'https://cloud.example/v2/device-auth/poll'), + 'https://cloud.example/v2/device-auth/poll': pollAnswer, + }); + + const result = await login(stateDir, cloud.fetch); + + assert.equal(result.accessToken, 'adc_agent_login'); + assert.deepEqual(cloud.sent.map(requestShape), [ + { url: START, ...postedStart }, + sentAsGet('https://cloud.example/v2/device-auth/start'), + { url: POLL, ...postedPoll }, + sentAsGet('https://cloud.example/v2/device-auth/poll'), + ]); + }); + }); + + test(`a refresh follows a same-origin ${status} as a GET without the credential`, async () => { + await withStateDir(async (stateDir) => { + const cloud = fakeCloud({ + [REFRESH]: () => redirect(status, '/unlock'), + 'https://cloud.example/unlock': () => jsonResponse({ accessToken: 'adc_agent_fresh' }), + }); + + const result = await refresh(stateDir, cloud.fetch); + + assert.equal(result.flags.daemonAuthToken, 'adc_agent_fresh'); + assert.deepEqual(cloud.sent.map(requestShape), [ + { url: REFRESH, ...postedRefresh }, + sentAsGet('https://cloud.example/unlock'), + ]); + }); + }); +} + +test('a refresh keeps the POST through a 307 and continues as a GET after a 303', async () => { + await withStateDir(async (stateDir) => { + const cloud = fakeCloud({ + [REFRESH]: () => redirect(307, '/a'), + 'https://cloud.example/a': () => redirect(303, '/b'), + 'https://cloud.example/b': () => redirect(307, '/c'), + 'https://cloud.example/c': () => jsonResponse({ accessToken: 'adc_agent_fresh' }), + }); + + const result = await refresh(stateDir, cloud.fetch); + + assert.equal(result.flags.daemonAuthToken, 'adc_agent_fresh'); + assert.deepEqual(cloud.sent.map(requestShape), [ + { url: REFRESH, ...postedRefresh }, + { url: 'https://cloud.example/a', ...postedRefresh }, + sentAsGet('https://cloud.example/b'), + sentAsGet('https://cloud.example/c'), + ]); + }); +}); + +const CREDENTIAL_REDIRECT_MESSAGE = + 'Cloud auth endpoint redirected the request to a URL with a username or password.'; + +async function assertCredentialRedirectRefused( + attempt: () => Promise, + secret: string, +): Promise { + await assert.rejects(attempt, (error: unknown) => { + const normalized = normalizeError(error); + assert.equal(normalized.message, CREDENTIAL_REDIRECT_MESSAGE); + assert.equal(normalized.details?.reason, 'cloud_auth_redirect_unsupported'); + assert.equal(JSON.stringify(normalized).includes(secret), false); + return true; + }); +} + +test('a login refuses a redirect with a username or password at device-auth start before it is followed', async () => { await withStateDir(async (stateDir) => { - for (const status of [301, 302, 303]) { - const cloud = fakeCloud({ [REFRESH]: () => redirect(status, '/unlock') }); - - await assert.rejects( - () => refresh(stateDir, cloud.fetch), - hasReason('cloud_auth_redirect_unsupported'), - ); - assert.deepEqual( - cloud.sent.map(({ url }) => url), - [REFRESH], - ); - } + const cloud = fakeCloud({ + [START]: () => redirect(307, 'https://user:start-secret@cloud.example/v2/device-auth/start'), + }); + + await assertCredentialRedirectRefused(() => login(stateDir, cloud.fetch), 'start-secret'); + assert.deepEqual( + cloud.sent.map(({ url }) => url), + [START], + ); + }); +}); + +test('a login refuses a poll redirect that echoes the device code as a username', async () => { + await withStateDir(async (stateDir) => { + const cloud = fakeCloud({ + [START]: startAnswer, + [POLL]: () => redirect(308, 'https://device-secret@cloud.example/v2/device-auth/poll'), + }); + + await assertCredentialRedirectRefused(() => login(stateDir, cloud.fetch), 'device-secret'); + assert.deepEqual( + cloud.sent.map(({ url }) => url), + [START, POLL], + ); + assert.equal(readCliSession({ stateDir }), null); + }); +}); + +test('a refresh refuses a redirect that echoes the refresh credential as a password', async () => { + await withStateDir(async (stateDir) => { + const cloud = fakeCloud({ + [REFRESH]: () => redirect(307, 'https://session:adc_refresh_stored@cloud.example/unlock'), + }); + + await assertCredentialRedirectRefused( + () => refresh(stateDir, cloud.fetch), + 'adc_refresh_stored', + ); + assert.deepEqual( + cloud.sent.map(({ url }) => url), + [REFRESH], + ); }); }); diff --git a/src/cli/cloud-auth-request.ts b/src/cli/cloud-auth-request.ts index 955b519c0e..90d7a48925 100644 --- a/src/cli/cloud-auth-request.ts +++ b/src/cli/cloud-auth-request.ts @@ -4,8 +4,8 @@ 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 keeps the method and body only for these. A 301, 302 or 303 would turn the POST into a GET. -const METHOD_PRESERVING_REDIRECT_STATUSES = new Set([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]); /** Every `details.reason` a cloud auth request publishes about a redirect it does not follow. */ const CLOUD_AUTH_REQUEST_REASONS = { @@ -14,16 +14,17 @@ const CLOUD_AUTH_REQUEST_REASONS = { crossOriginRedirect: { reason: 'cloud_auth_redirect_cross_origin', commands: ['connect'] }, // A cloud auth request was redirected more than three times within its origin. redirectLimit: { reason: 'cloud_auth_redirect_limit', commands: ['connect'] }, - // A cloud auth request got a redirect that cannot keep its POST: a 301, 302 or 303, or one with - // no readable Location. + // A cloud auth request got a redirect with no readable Location, or with a Location that carries + // a username or password. The request was not sent there. unsupportedRedirect: { reason: 'cloud_auth_redirect_unsupported', 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 only with a 307 or 308, which keep the method and body. Any other redirect - * fails with a typed reason before anything is sent again. + * 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. Any other + * redirect fails with a typed reason before anything is sent again. */ export async function postCloudAuthJson(options: { baseUrl: string; @@ -41,14 +42,20 @@ export async function postCloudAuthJson(options: { // One timeout covers the whole redirect chain. const signal = AbortSignal.timeout(HTTP_TIMEOUT_MS); let url = requestUrl; + let sendsBody = true; for (let redirects = 0; ; redirects += 1) { - const response = await fetchImpl(url, { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body, - redirect: 'manual', - signal, - }); + const response = await fetchImpl( + url, + sendsBody + ? { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body, + redirect: 'manual', + signal, + } + : { method: 'GET', redirect: 'manual', signal }, + ); if (!isRedirect(response)) { return await readCloudJsonResponse(response, { invalidJsonMessage: `Cloud auth endpoint returned invalid JSON (${response.status}).`, @@ -58,6 +65,7 @@ export async function postCloudAuthJson(options: { } await response.body?.cancel().catch(() => undefined); url = readRedirectTarget(response, url, requestUrl, redirects); + if (GET_REDIRECT_STATUSES.has(response.status)) sendsBody = false; } } @@ -74,9 +82,18 @@ function readRedirectTarget( const { status } = response; const location = response.headers.get('location'); const target = location ? parseUrl(location, current) : undefined; - if (!METHOD_PRESERVING_REDIRECT_STATUSES.has(status) || !target) { + if (!target) { + throw redirectRefusal( + 'Cloud auth endpoint answered with a redirect that has no readable Location.', + CLOUD_AUTH_REQUEST_REASONS.unsupportedRedirect.reason, + status, + requestUrl, + ); + } + // Fetch rejects such a URL with an error that quotes it, and the target can echo a credential. + if (target.username || target.password) { throw redirectRefusal( - 'Cloud auth endpoint answered with a redirect that cannot keep the request.', + 'Cloud auth endpoint redirected the request to a URL with a username or password.', CLOUD_AUTH_REQUEST_REASONS.unsupportedRedirect.reason, status, requestUrl, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 2a687d1d53..9740fb56d4 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`. 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 307 or 308 redirects on the same origin; a redirect to another origin, a fourth redirect, or a 301, 302 or 303 fails with `cloud_auth_redirect_cross_origin`, `cloud_auth_redirect_limit` or `cloud_auth_redirect_unsupported`. +- 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_cross_origin`, `cloud_auth_redirect_limit` or `cloud_auth_redirect_unsupported`. - `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 501b860f0d..a6dd0f99cc 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -29,7 +29,7 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `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_cross_origin` | A cloud auth request was redirected to another origin. The request was not sent there, so no credential or device code left the requested origin. | | `cloud_auth_redirect_limit` | A cloud auth request was redirected more than three times within its origin. | -| `cloud_auth_redirect_unsupported` | A cloud auth request got a redirect that cannot keep its POST: a 301, 302 or 303, or one with no readable Location. | +| `cloud_auth_redirect_unsupported` | A cloud auth request got a redirect with no readable Location, or with a Location that carries a username or password. The request was not sent there. | ### `back` @@ -66,7 +66,7 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `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_cross_origin` | A cloud auth request was redirected to another origin. The request was not sent there, so no credential or device code left the requested origin. | | `cloud_auth_redirect_limit` | A cloud auth request was redirected more than three times within its origin. | -| `cloud_auth_redirect_unsupported` | A cloud auth request got a redirect that cannot keep its POST: a 301, 302 or 303, or one with no readable Location. | +| `cloud_auth_redirect_unsupported` | A cloud auth request got a redirect with no readable Location, or with a Location that carries a username or password. The request was not sent there. | | `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. | From 1abd533d63e1191b33ec5c84171185b4dbac66e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 14:55:44 +0100 Subject: [PATCH 08/11] fix(auth): mark a verified session by its format version and refuse auth redirects with one reason Drop issuerOrigin: login always writes the origin of cloudBaseUrl, so version 2 alone marks a session saved through the origin-checked login. Collapse the three redirect reasons into cloud_auth_redirect_refused, drop the opaqueredirect branch Node never returns, and make the hint name the request origin instead of an override a refresh does not use. Prove the transport with Node's own fetch on loopback servers, and keep one cross-origin case per auth route to prove every route uses it. --- .../auth-session-cloud-origin.test.ts | 135 +++--- .../__tests__/auth-session-exchange.test.ts | 1 - .../__tests__/auth-session-redirect.test.ts | 399 ------------------ .../__tests__/auth-session-refresh.test.ts | 1 - .../__tests__/auth-session-refusal.test.ts | 1 - src/cli/__tests__/auth-session-umask.test.ts | 1 - src/cli/__tests__/auth-session.test.ts | 10 - src/cli/__tests__/cloud-auth-request.test.ts | 141 +++++++ src/cli/auth-session.ts | 6 +- src/cli/cli-session-format.ts | 31 +- src/cli/cloud-auth-request.ts | 113 ++--- src/cli/commands/__tests__/auth.test.ts | 1 - website/docs/docs/commands.md | 2 +- website/docs/docs/error-reasons.md | 8 +- 14 files changed, 269 insertions(+), 581 deletions(-) delete mode 100644 src/cli/__tests__/auth-session-redirect.test.ts create mode 100644 src/cli/__tests__/cloud-auth-request.test.ts diff --git a/src/cli/__tests__/auth-session-cloud-origin.test.ts b/src/cli/__tests__/auth-session-cloud-origin.test.ts index 219a931742..d03cad387b 100644 --- a/src/cli/__tests__/auth-session-cloud-origin.test.ts +++ b/src/cli/__tests__/auth-session-cloud-origin.test.ts @@ -21,6 +21,10 @@ const baseFlags = { 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, @@ -45,6 +49,40 @@ function refreshWith(stateDir: string, env: Record, requests: st }); } +/** 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); @@ -69,7 +107,6 @@ test('a stored CLI session is sent only to the cloud that issued it', async () = version: 2, id: 'session-origin', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_secret', createdAt: '2026-01-01T00:00:00.000Z', }, @@ -93,7 +130,7 @@ test('a stored CLI session is sent only to the cloud that issued it', async () = requests, ); assert.equal(same.flags.daemonAuthToken, 'adc_agent_fresh'); - assert.deepEqual(requests, ['https://cloud.example/api/control-plane/cli-session/refresh']); + assert.deepEqual(requests, [REFRESH]); } finally { fs.rmSync(tempRoot, { recursive: true, force: true }); } @@ -106,16 +143,11 @@ test('a rotation is not stored over a session that a login moved to another clou version: 2 as const, id: 'session-moved', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: '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', - issuerOrigin: 'https://other-cloud.example', - }; + const moved = { ...session, cloudBaseUrl: 'https://other-cloud.example' }; await resolveRemoteAuth({ command: 'snapshot', @@ -154,56 +186,55 @@ test('a version 1 session is refused with a re-login reason, and a fresh login i assert.deepEqual(requests, []); assert.equal(readCliSession({ stateDir: tempRoot }), null); - const login = await loginWithDeviceAuth({ - stateDir: tempRoot, - flags: baseFlags, - env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example/' }, - io: { - stdinIsTTY: true, - stdoutIsTTY: true, - stderr: { write: () => true }, - openBrowser: async () => {}, - fetch: async (url) => - String(url).endsWith('/device-auth/start') - ? jsonResponse({ - deviceCode: 'device-secret', - userCode: 'ABCD-EFGH', - verificationUri: 'https://cloud.example/authorize', - }) - : jsonResponse({ - status: 'approved', - accessToken: 'adc_agent_login', - cliSession: { id: 'session-new', refreshCredential: 'adc_refresh_new' }, - }), - }, - }); + const login = await loginAt(tempRoot, deviceAuthCloud); assert.equal(login.session.version, 2); - assert.equal(login.session.issuerOrigin, 'https://cloud.example'); const refreshed = await refreshWith(tempRoot, {}, requests); assert.equal(refreshed.flags.daemonAuthToken, 'adc_agent_fresh'); - assert.deepEqual(requests, ['https://cloud.example/api/control-plane/cli-session/refresh']); + assert.deepEqual(requests, [REFRESH]); } finally { fs.rmSync(tempRoot, { recursive: true, force: true }); } }); -test('a session whose recorded issuer is not the origin of its URL is refused', async () => { - const tempRoot = mkdtempForTestSync('agent-device-auth-origin-issuer-'); - try { - writeRawSession(tempRoot, { - version: 2, - id: 'session-edited', - cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://other-cloud.example', - refreshCredential: 'adc_refresh_other', - createdAt: '2026-01-01T00:00:00.000Z', - }); - const requests: string[] = []; - - await assert.rejects(() => refreshWith(tempRoot, {}, requests), isIssuerUnverified); - assert.deepEqual(requests, []); - } 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 9f87483202..a9aa79fda9 100644 --- a/src/cli/__tests__/auth-session-exchange.test.ts +++ b/src/cli/__tests__/auth-session-exchange.test.ts @@ -38,7 +38,6 @@ function writeStoredSession(stateDir: string, overrides: Record version: 2, id: 'session-pairing', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_old', createdAt: '2026-01-01T00:00:00.000Z', ...overrides, diff --git a/src/cli/__tests__/auth-session-redirect.test.ts b/src/cli/__tests__/auth-session-redirect.test.ts deleted file mode 100644 index 51b0cd1c37..0000000000 --- a/src/cli/__tests__/auth-session-redirect.test.ts +++ /dev/null @@ -1,399 +0,0 @@ -import { test } from 'vitest'; -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import { normalizeError } from '@agent-device/kernel/errors'; -import { mkdtempForTestSync } from '@agent-device/test-kit'; -import { - loginWithDeviceAuth, - readCliSession, - 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'; - -type SentRequest = { - url: string; - method?: string; - body?: unknown; - contentType?: string | null; - redirect?: RequestRedirect; -}; - -function jsonResponse(body: unknown): Response { - return new Response(JSON.stringify(body), { - status: 200, - headers: { 'content-type': 'application/json' }, - }); -} - -function redirect(status: number, location: string): Response { - return new Response(null, { status, headers: { location } }); -} - -/** - * A cloud that answers each URL from `routes` and records every request it receives. A URL without - * a route answers 404, so a request that reaches an unexpected target is visible in `sent`. - */ -function fakeCloud(routes: Record Response>) { - const sent: SentRequest[] = []; - const fetch = async (url: URL | RequestInfo, init?: RequestInit): Promise => { - sent.push({ - url: String(url), - method: init?.method, - body: typeof init?.body === 'string' ? JSON.parse(init.body) : init?.body, - contentType: new Headers(init?.headers).get('content-type'), - redirect: init?.redirect, - }); - return routes[String(url)]?.() ?? new Response('{}', { status: 404 }); - }; - return { sent, fetch }; -} - -const startAnswer = () => - jsonResponse({ - deviceCode: 'device-secret', - userCode: 'ABCD-EFGH', - verificationUri: 'https://cloud.example/authorize', - }); -const pollAnswer = () => - jsonResponse({ - status: 'approved', - accessToken: 'adc_agent_login', - cliSession: { id: 'session-login', refreshCredential: 'adc_refresh_login' }, - }); - -function login(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, - }, - }); -} - -function refresh(stateDir: string, fetch: typeof globalThis.fetch) { - writeCliSession({ - stateDir, - session: { - version: 2, - id: 'session-stored', - cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', - refreshCredential: 'adc_refresh_stored', - createdAt: '2026-01-01T00:00:00.000Z', - }, - }); - return resolveRemoteAuth({ - command: 'snapshot', - flags: baseFlags, - stateDir, - allowInteractiveLogin: false, - env: {}, - io: { fetch }, - }); -} - -const hasReason = (reason: string) => (error: unknown) => - normalizeError(error).details?.reason === reason; - -async function withStateDir(run: (stateDir: string) => Promise): Promise { - const stateDir = mkdtempForTestSync('agent-device-auth-redirect-'); - try { - await run(stateDir); - } finally { - fs.rmSync(stateDir, { recursive: true, force: true }); - } -} - -test('a login follows a same-origin 307 at device-auth start and a 308 at poll with the same POST', async () => { - await withStateDir(async (stateDir) => { - const cloud = fakeCloud({ - [START]: () => redirect(307, '/v2/device-auth/start'), - 'https://cloud.example/v2/device-auth/start': startAnswer, - [POLL]: () => redirect(308, 'https://cloud.example/v2/device-auth/poll'), - 'https://cloud.example/v2/device-auth/poll': pollAnswer, - }); - - const result = await login(stateDir, cloud.fetch); - - assert.equal(result.accessToken, 'adc_agent_login'); - assert.deepEqual( - cloud.sent.map(({ url, method, redirect }) => ({ url, method, redirect })), - [ - START, - 'https://cloud.example/v2/device-auth/start', - POLL, - 'https://cloud.example/v2/device-auth/poll', - ].map((url) => ({ url, method: 'POST', redirect: 'manual' })), - ); - assert.deepEqual(cloud.sent[1]?.body, cloud.sent[0]?.body); - assert.deepEqual(cloud.sent[3]?.body, { deviceCode: 'device-secret' }); - }); -}); - -test('a login stops at a cross-origin redirect at device-auth start before it is followed', async () => { - await withStateDir(async (stateDir) => { - const cloud = fakeCloud({ - [START]: () => redirect(307, 'https://elsewhere.example/device-auth/start'), - }); - - await assert.rejects( - () => login(stateDir, cloud.fetch), - hasReason('cloud_auth_redirect_cross_origin'), - ); - assert.deepEqual( - cloud.sent.map(({ url }) => url), - [START], - ); - }); -}); - -test('a login stops at a cross-origin redirect at device-auth poll and stores nothing', async () => { - await withStateDir(async (stateDir) => { - const cloud = fakeCloud({ - [START]: startAnswer, - [POLL]: () => redirect(308, 'https://elsewhere.example/device-auth/poll'), - }); - - await assert.rejects( - () => login(stateDir, cloud.fetch), - hasReason('cloud_auth_redirect_cross_origin'), - ); - assert.deepEqual( - cloud.sent.map(({ url }) => url), - [START, POLL], - ); - assert.equal(readCliSession({ stateDir }), null); - }); -}); - -test('a refresh follows a same-origin 307 and sends the credential again only there', async () => { - await withStateDir(async (stateDir) => { - const cloud = fakeCloud({ - [REFRESH]: () => redirect(307, '/unlock'), - 'https://cloud.example/unlock': () => jsonResponse({ accessToken: 'adc_agent_fresh' }), - }); - - const result = await refresh(stateDir, cloud.fetch); - - assert.equal(result.flags.daemonAuthToken, 'adc_agent_fresh'); - assert.deepEqual( - cloud.sent.map(({ url, method }) => ({ url, method })), - [ - { url: REFRESH, method: 'POST' }, - { url: 'https://cloud.example/unlock', method: 'POST' }, - ], - ); - assert.deepEqual(cloud.sent[1]?.body, cloud.sent[0]?.body); - }); -}); - -test('a refresh stops at a cross-origin 308 and never sends the credential there', async () => { - await withStateDir(async (stateDir) => { - const cloud = fakeCloud({ - [REFRESH]: () => redirect(308, 'https://elsewhere.example/refresh'), - }); - - await assert.rejects( - () => refresh(stateDir, cloud.fetch), - hasReason('cloud_auth_redirect_cross_origin'), - ); - assert.deepEqual( - cloud.sent.map(({ url }) => url), - [REFRESH], - ); - }); -}); - -test('a refresh follows three same-origin redirects and refuses a fourth', async () => { - await withStateDir(async (stateDir) => { - const hops = (count: number) => { - const routes: Record Response> = {}; - let from = REFRESH; - for (let hop = 1; hop <= count; hop += 1) { - routes[from] = () => redirect(307, `/hop-${hop}`); - from = `https://cloud.example/hop-${hop}`; - } - routes[from] = () => jsonResponse({ accessToken: 'adc_agent_fresh' }); - return fakeCloud(routes); - }; - - const three = hops(3); - assert.equal((await refresh(stateDir, three.fetch)).flags.daemonAuthToken, 'adc_agent_fresh'); - assert.equal(three.sent.length, 4); - - const four = hops(4); - await assert.rejects( - () => refresh(stateDir, four.fetch), - hasReason('cloud_auth_redirect_limit'), - ); - assert.equal(four.sent.length, 4); - }); -}); - -const requestShape = ({ url, method, body, contentType }: SentRequest) => ({ - url, - method, - body, - contentType, -}); -const sentAsGet = (url: string) => ({ url, method: 'GET', body: undefined, contentType: null }); -const flagFields = { - tenant: 'acme', - runId: 'run-123', - daemonBaseUrl: 'https://bridge.agent-device.dev', -}; -const postedAs = (body: Record) => ({ - method: 'POST', - body, - contentType: 'application/json', -}); -const postedStart = postedAs({ client: 'agent-device', ...flagFields }); -const postedPoll = postedAs({ deviceCode: 'device-secret' }); -const postedRefresh = postedAs({ - refreshCredential: 'adc_refresh_stored', - acceptsRotatedRefreshCredential: true, - ...flagFields, -}); - -for (const status of [301, 302, 303]) { - test(`a login follows a same-origin ${status} at device-auth start and poll as a GET without the body`, async () => { - await withStateDir(async (stateDir) => { - const cloud = fakeCloud({ - [START]: () => redirect(status, '/v2/device-auth/start'), - 'https://cloud.example/v2/device-auth/start': startAnswer, - [POLL]: () => redirect(status, 'https://cloud.example/v2/device-auth/poll'), - 'https://cloud.example/v2/device-auth/poll': pollAnswer, - }); - - const result = await login(stateDir, cloud.fetch); - - assert.equal(result.accessToken, 'adc_agent_login'); - assert.deepEqual(cloud.sent.map(requestShape), [ - { url: START, ...postedStart }, - sentAsGet('https://cloud.example/v2/device-auth/start'), - { url: POLL, ...postedPoll }, - sentAsGet('https://cloud.example/v2/device-auth/poll'), - ]); - }); - }); - - test(`a refresh follows a same-origin ${status} as a GET without the credential`, async () => { - await withStateDir(async (stateDir) => { - const cloud = fakeCloud({ - [REFRESH]: () => redirect(status, '/unlock'), - 'https://cloud.example/unlock': () => jsonResponse({ accessToken: 'adc_agent_fresh' }), - }); - - const result = await refresh(stateDir, cloud.fetch); - - assert.equal(result.flags.daemonAuthToken, 'adc_agent_fresh'); - assert.deepEqual(cloud.sent.map(requestShape), [ - { url: REFRESH, ...postedRefresh }, - sentAsGet('https://cloud.example/unlock'), - ]); - }); - }); -} - -test('a refresh keeps the POST through a 307 and continues as a GET after a 303', async () => { - await withStateDir(async (stateDir) => { - const cloud = fakeCloud({ - [REFRESH]: () => redirect(307, '/a'), - 'https://cloud.example/a': () => redirect(303, '/b'), - 'https://cloud.example/b': () => redirect(307, '/c'), - 'https://cloud.example/c': () => jsonResponse({ accessToken: 'adc_agent_fresh' }), - }); - - const result = await refresh(stateDir, cloud.fetch); - - assert.equal(result.flags.daemonAuthToken, 'adc_agent_fresh'); - assert.deepEqual(cloud.sent.map(requestShape), [ - { url: REFRESH, ...postedRefresh }, - { url: 'https://cloud.example/a', ...postedRefresh }, - sentAsGet('https://cloud.example/b'), - sentAsGet('https://cloud.example/c'), - ]); - }); -}); - -const CREDENTIAL_REDIRECT_MESSAGE = - 'Cloud auth endpoint redirected the request to a URL with a username or password.'; - -async function assertCredentialRedirectRefused( - attempt: () => Promise, - secret: string, -): Promise { - await assert.rejects(attempt, (error: unknown) => { - const normalized = normalizeError(error); - assert.equal(normalized.message, CREDENTIAL_REDIRECT_MESSAGE); - assert.equal(normalized.details?.reason, 'cloud_auth_redirect_unsupported'); - assert.equal(JSON.stringify(normalized).includes(secret), false); - return true; - }); -} - -test('a login refuses a redirect with a username or password at device-auth start before it is followed', async () => { - await withStateDir(async (stateDir) => { - const cloud = fakeCloud({ - [START]: () => redirect(307, 'https://user:start-secret@cloud.example/v2/device-auth/start'), - }); - - await assertCredentialRedirectRefused(() => login(stateDir, cloud.fetch), 'start-secret'); - assert.deepEqual( - cloud.sent.map(({ url }) => url), - [START], - ); - }); -}); - -test('a login refuses a poll redirect that echoes the device code as a username', async () => { - await withStateDir(async (stateDir) => { - const cloud = fakeCloud({ - [START]: startAnswer, - [POLL]: () => redirect(308, 'https://device-secret@cloud.example/v2/device-auth/poll'), - }); - - await assertCredentialRedirectRefused(() => login(stateDir, cloud.fetch), 'device-secret'); - assert.deepEqual( - cloud.sent.map(({ url }) => url), - [START, POLL], - ); - assert.equal(readCliSession({ stateDir }), null); - }); -}); - -test('a refresh refuses a redirect that echoes the refresh credential as a password', async () => { - await withStateDir(async (stateDir) => { - const cloud = fakeCloud({ - [REFRESH]: () => redirect(307, 'https://session:adc_refresh_stored@cloud.example/unlock'), - }); - - await assertCredentialRedirectRefused( - () => refresh(stateDir, cloud.fetch), - 'adc_refresh_stored', - ); - assert.deepEqual( - cloud.sent.map(({ url }) => url), - [REFRESH], - ); - }); -}); diff --git a/src/cli/__tests__/auth-session-refresh.test.ts b/src/cli/__tests__/auth-session-refresh.test.ts index 68c5561008..c4b483cd87 100644 --- a/src/cli/__tests__/auth-session-refresh.test.ts +++ b/src/cli/__tests__/auth-session-refresh.test.ts @@ -40,7 +40,6 @@ function writeStoredSession(stateDir: string, overrides: Record version: 2, id: 'session-refresh', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_old', createdAt: '2026-01-01T00:00:00.000Z', ...overrides, diff --git a/src/cli/__tests__/auth-session-refusal.test.ts b/src/cli/__tests__/auth-session-refusal.test.ts index a0d262532d..556ed4e13c 100644 --- a/src/cli/__tests__/auth-session-refusal.test.ts +++ b/src/cli/__tests__/auth-session-refusal.test.ts @@ -38,7 +38,6 @@ function writeStoredSession(stateDir: string): void { version: 2, id: 'session-refusal', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_stored', createdAt: '2026-01-01T00:00:00.000Z', }, diff --git a/src/cli/__tests__/auth-session-umask.test.ts b/src/cli/__tests__/auth-session-umask.test.ts index e64e5cd7e2..fa61a0b659 100644 --- a/src/cli/__tests__/auth-session-umask.test.ts +++ b/src/cli/__tests__/auth-session-umask.test.ts @@ -12,7 +12,6 @@ test.skipIf(process.platform === 'win32')( version: 2 as const, id: 'session-first', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_umask', createdAt: '2026-01-01T00:00:00.000Z', }; diff --git a/src/cli/__tests__/auth-session.test.ts b/src/cli/__tests__/auth-session.test.ts index f5a3295e22..8c8b586d3f 100644 --- a/src/cli/__tests__/auth-session.test.ts +++ b/src/cli/__tests__/auth-session.test.ts @@ -103,7 +103,6 @@ test('remote auth leaves non-cloud remote daemons to existing daemon auth valida version: 2, id: 'session-non-cloud', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_should_not_be_used', createdAt: '2026-01-01T00:00:00.000Z', }, @@ -136,7 +135,6 @@ test('remote auth refreshes a stored CLI session into an agent token', async () version: 2, id: 'session-1', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', workspaceId: 'acme', refreshCredential: 'adc_refresh_secret', createdAt: '2026-01-01T00:00:00.000Z', @@ -180,7 +178,6 @@ test('remote auth stores a refresh credential that the cloud rotated', async () version: 2 as const, id: 'session-rotate', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_old', createdAt: '2026-01-01T00:00:00.000Z', expiresAt: '2026-12-01T00:00:00.000Z', @@ -232,7 +229,6 @@ test('a rotated credential does not replace a session another writer changed', a version: 2 as const, id: 'session-race', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_old', createdAt: '2026-01-01T00:00:00.000Z', }; @@ -293,7 +289,6 @@ test('a stored rotation is kept when the lock release fails, and the warning is version: 2 as const, id: 'session-release', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_old', createdAt: '2026-01-01T00:00:00.000Z', }; @@ -355,7 +350,6 @@ test('a timed-out session lock wait keeps a login waiting and fails a refresh re version: 2, id: 'session-timeout', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_old', createdAt: '2026-01-01T00:00:00.000Z', }, @@ -474,7 +468,6 @@ test('remote auth does not fall back to login when session refresh gets 503', as version: 2 as const, id: 'session-503', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_503', createdAt: '2026-01-01T00:00:00.000Z', }; @@ -525,7 +518,6 @@ test('remote auth fails immediately when stored CLI session is revoked', async ( version: 2, id: 'session-revoked', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_revoked', createdAt: '2026-01-01T00:00:00.000Z', }, @@ -634,7 +626,6 @@ test('auth summary and logout do not expose stored refresh credentials', async ( version: 2, id: 'session-3', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_hidden', createdAt: '2026-01-01T00:00:00.000Z', }, @@ -885,7 +876,6 @@ test('a rewritten CLI session replaces the file, so a reader never sees a partia version: 2 as const, id: 'session-first', cloudBaseUrl: 'https://cloud.example', - issuerOrigin: 'https://cloud.example', refreshCredential: 'adc_refresh_first', createdAt: '2026-01-01T00:00:00.000Z', }; 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..8968086b89 --- /dev/null +++ b/src/cli/__tests__/cloud-auth-request.test.ts @@ -0,0 +1,141 @@ +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 }; +type Route = (res: http.ServerResponse) => void; + +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: Record = {}; + 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 route = routes[req.url ?? '']; + if (route) return route(res); + res.writeHead(404).end(); + }); + }); + 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 => + (res) => + res.writeHead(status, location ? { location } : {}).end(); +const answer: Route = (res) => + res.writeHead(200, { 'content-type': 'application/json' }).end('{"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['/start'] = redirect(status, '/next'); + cloud.routes['/next'] = 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['/start'] = redirect(307, '/a'); + cloud.routes['/a'] = redirect(303, '/b'); + cloud.routes['/b'] = redirect(307, '/c'); + cloud.routes['/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['/start'] = redirect(307, '/1'); + cloud.routes['/1'] = redirect(307, '/2'); + cloud.routes['/2'] = redirect(307, '/3'); + cloud.routes['/3'] = answer; + expect(await post(cloud.origin)).toEqual({ accessToken: 'adc_agent' }); + + cloud.routes['/3'] = redirect(307, '/4'); + cloud.routes['/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['/start'] = redirect(307, location(new URL(cloud.origin).host, other.origin)); + cloud.routes['/next'] = answer; + other.routes['/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 ae9080e7da..5d3f3aa26b 100644 --- a/src/cli/auth-session.ts +++ b/src/cli/auth-session.ts @@ -300,8 +300,6 @@ export async function loginWithDeviceAuth(options: { version: CLI_SESSION_FORMAT_VERSION, id: approved.cliSession?.id ?? `cli-${Date.now().toString(36)}`, cloudBaseUrl, - // Every login request stays on this origin, so the credential came from it. - issuerOrigin: new URL(cloudBaseUrl).origin, workspaceId: approved.cliSession?.workspaceId, accountId: approved.cliSession?.accountId, name: approved.cliSession?.name, @@ -571,8 +569,8 @@ async function resolveCliSessionAccess(options: { * origin would send it to that origin, so the command stops before any request. */ function assertStoredSessionOrigin(session: CliSessionRecord, env: EnvMap): void { - const storedUrl = resolveCloudBaseUrl({}, session.cloudBaseUrl); - if (new URL(resolveCloudBaseUrl(env, storedUrl)).origin === new URL(storedUrl).origin) return; + 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.', diff --git a/src/cli/cli-session-format.ts b/src/cli/cli-session-format.ts index 1087158342..cc1183767d 100644 --- a/src/cli/cli-session-format.ts +++ b/src/cli/cli-session-format.ts @@ -1,13 +1,12 @@ -// Version 2 records the origin that issued the credential. Version 1 did not, and an older login -// could follow a redirect to another cloud and save that cloud's credential under its own URL. +// 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; - /** The origin of `cloudBaseUrl` that the login reached through same-origin requests only. */ - issuerOrigin: string; workspaceId?: string; accountId?: string; name?: string; @@ -17,35 +16,21 @@ export type CliSessionRecord = { }; /** - * Parses the session file text. A record whose issuer the file does not establish answers - * `unverified`: an older format version, or a record whose `issuerOrigin` is not its URL's origin. - * Text that is not a record with a credential answers `null`. Text that is not JSON throws. + * 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 || - !hasText(parsed.id) || - !hasText(parsed.cloudBaseUrl) || - !hasText(parsed.createdAt) || - parsed.issuerOrigin !== readOrigin(parsed.cloudBaseUrl) - ) { - return 'unverified'; + 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 readOrigin(url: string): string | undefined { - try { - return new URL(url).origin; - } catch { - return undefined; - } -} - 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 index 90d7a48925..2a2d468283 100644 --- a/src/cli/cloud-auth-request.ts +++ b/src/cli/cloud-auth-request.ts @@ -7,24 +7,17 @@ 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]); -/** Every `details.reason` a cloud auth request publishes about a redirect it does not follow. */ const CLOUD_AUTH_REQUEST_REASONS = { - // A cloud auth request was redirected to another origin. The request was not sent there, so no - // credential or device code left the requested origin. - crossOriginRedirect: { reason: 'cloud_auth_redirect_cross_origin', commands: ['connect'] }, - // A cloud auth request was redirected more than three times within its origin. - redirectLimit: { reason: 'cloud_auth_redirect_limit', commands: ['connect'] }, - // A cloud auth request got a redirect with no readable Location, or with a Location that carries - // a username or password. The request was not sent there. - unsupportedRedirect: { reason: 'cloud_auth_redirect_unsupported', commands: ['connect'] }, + // 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. Any other - * redirect fails with a typed reason before anything is sent again. + * 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; @@ -38,25 +31,18 @@ export async function postCloudAuthJson(options: { }): Promise { const fetchImpl = options.fetchImpl ?? fetch; const requestUrl = new URL(options.pathName, options.baseUrl); - const body = JSON.stringify(options.body); + 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 sendsBody = true; + let init = post; for (let redirects = 0; ; redirects += 1) { - const response = await fetchImpl( - url, - sendsBody - ? { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body, - redirect: 'manual', - signal, - } - : { method: 'GET', redirect: 'manual', signal }, - ); - if (!isRedirect(response)) { + 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.', @@ -65,71 +51,36 @@ export async function postCloudAuthJson(options: { } await response.body?.cancel().catch(() => undefined); url = readRedirectTarget(response, url, requestUrl, redirects); - if (GET_REDIRECT_STATUSES.has(response.status)) sendsBody = false; + if (GET_REDIRECT_STATUSES.has(response.status)) init = { method: 'GET' }; } } -function isRedirect(response: Response): boolean { - return response.type === 'opaqueredirect' || REDIRECT_STATUSES.has(response.status); -} - function readRedirectTarget( response: Response, current: URL, requestUrl: URL, redirects: number, ): URL { - const { status } = response; const location = response.headers.get('location'); - const target = location ? parseUrl(location, current) : undefined; - if (!target) { - throw redirectRefusal( - 'Cloud auth endpoint answered with a redirect that has no readable Location.', - CLOUD_AUTH_REQUEST_REASONS.unsupportedRedirect.reason, - status, - requestUrl, - ); - } - // Fetch rejects such a URL with an error that quotes it, and the target can echo a credential. - if (target.username || target.password) { - throw redirectRefusal( - 'Cloud auth endpoint redirected the request to a URL with a username or password.', - CLOUD_AUTH_REQUEST_REASONS.unsupportedRedirect.reason, - status, - requestUrl, - ); - } - if (target.origin !== requestUrl.origin) { - throw redirectRefusal( - 'Cloud auth endpoint redirected the request to another origin.', - CLOUD_AUTH_REQUEST_REASONS.crossOriginRedirect.reason, - status, - requestUrl, - ); - } - if (redirects >= MAX_CLOUD_AUTH_REDIRECTS) { - throw redirectRefusal( - 'Cloud auth endpoint redirected the request too many times.', - CLOUD_AUTH_REQUEST_REASONS.redirectLimit.reason, - status, - requestUrl, - ); - } - return target; -} - -function parseUrl(location: string, base: URL): URL | undefined { - try { - return new URL(location, base); - } catch { - return undefined; - } + const target = location ? URL.parse(location, current) : null; + 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 redirectRefusal(message: string, reason: string, status: number, requestUrl: URL) { - return new AppError('COMMAND_FAILED', message, { - reason, - status, - hint: `Check that AGENT_DEVICE_CLOUD_BASE_URL names the cloud API origin that answers auth requests (now ${requestUrl.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 a82a225a2a..5ad41a5588 100644 --- a/src/cli/commands/__tests__/auth.test.ts +++ b/src/cli/commands/__tests__/auth.test.ts @@ -27,7 +27,6 @@ function writeStoredCliSession( version: 2, id: 'cli-1', cloudBaseUrl: 'https://cloud.example.test', - issuerOrigin: 'https://cloud.example.test', refreshCredential: 'refresh-credential', createdAt: '2026-01-01T00:00:00.000Z', ...overrides, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 9740fb56d4..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`. 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_cross_origin`, `cloud_auth_redirect_limit` or `cloud_auth_redirect_unsupported`. +- 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 a6dd0f99cc..b0295f9c98 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -27,9 +27,7 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `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_cross_origin` | A cloud auth request was redirected to another origin. The request was not sent there, so no credential or device code left the requested origin. | -| `cloud_auth_redirect_limit` | A cloud auth request was redirected more than three times within its origin. | -| `cloud_auth_redirect_unsupported` | A cloud auth request got a redirect with no readable Location, or with a Location that carries a username or password. The request was not sent there. | +| `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` @@ -64,9 +62,7 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `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_cross_origin` | A cloud auth request was redirected to another origin. The request was not sent there, so no credential or device code left the requested origin. | -| `cloud_auth_redirect_limit` | A cloud auth request was redirected more than three times within its origin. | -| `cloud_auth_redirect_unsupported` | A cloud auth request got a redirect with no readable Location, or with a Location that carries a username or password. The request was not sent there. | +| `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. | From ef26e1f731218acf1509c81a988fcfa4f13edc90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 15:01:09 +0100 Subject: [PATCH 09/11] test(cli): dispatch loopback routes through a checked map --- src/cli/__tests__/cloud-auth-request.test.ts | 36 ++++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/cli/__tests__/cloud-auth-request.test.ts b/src/cli/__tests__/cloud-auth-request.test.ts index 8968086b89..cd1cb36027 100644 --- a/src/cli/__tests__/cloud-auth-request.test.ts +++ b/src/cli/__tests__/cloud-auth-request.test.ts @@ -26,7 +26,7 @@ afterEach(async () => { async function listen() { const received: Received[] = []; - const routes: Record = {}; + const routes = new Map(); const server = http.createServer((req, res) => { let body = ''; req.setEncoding('utf8'); @@ -38,8 +38,8 @@ async function listen() { body, contentType: req.headers['content-type'], }); - const route = routes[req.url ?? '']; - if (route) return route(res); + const route = routes.get(req.url ?? ''); + if (route !== undefined) return route(res); res.writeHead(404).end(); }); }); @@ -75,8 +75,8 @@ test.each([ [303, fetchedAsGet('/next')], ])('a same-origin %i is followed with the method fetch gives it', async (status, followed) => { const cloud = await listen(); - cloud.routes['/start'] = redirect(status, '/next'); - cloud.routes['/next'] = answer; + 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]); @@ -84,10 +84,10 @@ test.each([ test('a chain keeps the POST through a 307 and stays a GET after a 303', async () => { const cloud = await listen(); - cloud.routes['/start'] = redirect(307, '/a'); - cloud.routes['/a'] = redirect(303, '/b'); - cloud.routes['/b'] = redirect(307, '/c'); - cloud.routes['/c'] = answer; + 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([ @@ -100,14 +100,14 @@ test('a chain keeps the POST through a 307 and stays a GET after a 303', async ( test('three same-origin redirects are followed and a fourth is refused', async () => { const cloud = await listen(); - cloud.routes['/start'] = redirect(307, '/1'); - cloud.routes['/1'] = redirect(307, '/2'); - cloud.routes['/2'] = redirect(307, '/3'); - cloud.routes['/3'] = answer; + 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['/3'] = redirect(307, '/4'); - cloud.routes['/4'] = answer; + 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' }, @@ -125,9 +125,9 @@ test.each([ async (_case, location) => { const cloud = await listen(); const other = await listen(); - cloud.routes['/start'] = redirect(307, location(new URL(cloud.origin).host, other.origin)); - cloud.routes['/next'] = answer; - other.routes['/next'] = answer; + 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, From 9c9da8c613356cf48722ab282c5cf4c65deb0cd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 15:05:21 +0100 Subject: [PATCH 10/11] test(cli): serve loopback routes as canned data, not handlers --- src/cli/__tests__/cloud-auth-request.test.ts | 23 ++++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/cli/__tests__/cloud-auth-request.test.ts b/src/cli/__tests__/cloud-auth-request.test.ts index cd1cb36027..7d6da277e4 100644 --- a/src/cli/__tests__/cloud-auth-request.test.ts +++ b/src/cli/__tests__/cloud-auth-request.test.ts @@ -8,7 +8,8 @@ import { postCloudAuthJson } from '../cloud-auth-request.ts'; // followed by fetch itself and that a refused target never receives a request. type Received = { method?: string; path?: string; body: string; contentType?: string }; -type Route = (res: http.ServerResponse) => void; +/** 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[] = []; @@ -39,8 +40,8 @@ async function listen() { contentType: req.headers['content-type'], }); const route = routes.get(req.url ?? ''); - if (route !== undefined) return route(res); - res.writeHead(404).end(); + if (route === undefined) return void res.writeHead(404).end(); + res.writeHead(route.status, route.headers).end(route.body); }); }); servers.push(server); @@ -49,12 +50,16 @@ async function listen() { return { origin: `http://127.0.0.1:${port}`, received, routes }; } -const redirect = - (status: number, location?: string): Route => - (res) => - res.writeHead(status, location ? { location } : {}).end(); -const answer: Route = (res) => - res.writeHead(200, { 'content-type': 'application/json' }).end('{"accessToken":"adc_agent"}'); +const redirect = (status: number, location?: string): Route => ({ + status, + headers: location ? { 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) => From 23803c95fdfc932dc8e6d6dcf5d5ebde1a1959dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 16:08:51 +0100 Subject: [PATCH 11/11] fix(cli): resolve an empty cloud auth Location like fetch does --- src/cli/__tests__/cloud-auth-request.test.ts | 25 +++++++++++++++++--- src/cli/cloud-auth-request.ts | 2 +- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/cli/__tests__/cloud-auth-request.test.ts b/src/cli/__tests__/cloud-auth-request.test.ts index 7d6da277e4..0b7584669e 100644 --- a/src/cli/__tests__/cloud-auth-request.test.ts +++ b/src/cli/__tests__/cloud-auth-request.test.ts @@ -27,7 +27,7 @@ afterEach(async () => { async function listen() { const received: Received[] = []; - const routes = new Map(); + const routes = new Map(); const server = http.createServer((req, res) => { let body = ''; req.setEncoding('utf8'); @@ -39,7 +39,9 @@ async function listen() { body, contentType: req.headers['content-type'], }); - const route = routes.get(req.url ?? ''); + 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); }); @@ -52,7 +54,7 @@ async function listen() { const redirect = (status: number, location?: string): Route => ({ status, - headers: location ? { location } : {}, + headers: location === undefined ? {} : { location }, body: '', }); const answer: Route = { @@ -87,6 +89,23 @@ test.each([ 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')); diff --git a/src/cli/cloud-auth-request.ts b/src/cli/cloud-auth-request.ts index 2a2d468283..e074cf5a03 100644 --- a/src/cli/cloud-auth-request.ts +++ b/src/cli/cloud-auth-request.ts @@ -62,7 +62,7 @@ function readRedirectTarget( redirects: number, ): URL { const location = response.headers.get('location'); - const target = location ? URL.parse(location, current) : null; + 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}.`, {