diff --git a/packages/host-kit/src/internal/process-lock.test.ts b/packages/host-kit/src/internal/process-lock.test.ts index de3c25fd85..bccc87f9cf 100644 --- a/packages/host-kit/src/internal/process-lock.test.ts +++ b/packages/host-kit/src/internal/process-lock.test.ts @@ -50,6 +50,28 @@ test('acquireProcessLock creates and releases a lock directory', async () => { assert.equal(fs.existsSync(lockDirPath), false); }); +test.skipIf(process.platform === 'win32')( + 'acquireProcessLock keeps the lock owner-only under any umask', + async () => { + for (const umask of [0o200, 0o000]) { + const lockDirPath = path.join(tmpDir, `umask-${umask.toString(8)}.lock`); + const previousUmask = process.umask(umask); + let release: ProcessLockRelease; + try { + release = await acquireProcessLock({ lockDirPath, owner: currentProcessOwner() }); + } finally { + process.umask(previousUmask); + } + assert.equal(fs.statSync(lockDirPath).mode & 0o777, 0o700); + for (const entry of fs.readdirSync(lockDirPath)) { + assert.equal(fs.statSync(path.join(lockDirPath, entry)).mode & 0o777, 0o600); + } + await release(); + assert.equal(fs.existsSync(lockDirPath), false); + } + }, +); + test('acquireProcessLock reclaims locks owned by dead processes', async () => { const lockDirPath = path.join(tmpDir, 'stale.lock'); writeDeadLockFixture(lockDirPath, Date.now() - 10_000); diff --git a/packages/host-kit/src/internal/process-lock.ts b/packages/host-kit/src/internal/process-lock.ts index 1e9ee7e7d0..7852cdf71c 100644 --- a/packages/host-kit/src/internal/process-lock.ts +++ b/packages/host-kit/src/internal/process-lock.ts @@ -288,7 +288,7 @@ function publishClaim( ): GuardedAcquisitionOutcome { const { lockDirPath, owner } = params; try { - fs.mkdirSync(lockDirPath); + fs.mkdirSync(lockDirPath, { mode: 0o700 }); } catch (error) { if (errorCode(error) !== 'EEXIST') throw error; return { status: 'unproven' }; @@ -296,6 +296,8 @@ function publishClaim( const claimToken = crypto.randomUUID(); const claim: ProcessLockOwnerRecord = { ...owner, claimToken, claimIssuerId: CLAIM_ISSUER_ID }; try { + // The umask narrows a created mode, so the owner-only mode is set exactly. + fs.chmodSync(lockDirPath, 0o700); writeProcessLockOwner(ownerFilePath, claim); } catch (error) { try { @@ -556,6 +558,8 @@ function writeProcessLockOwner(ownerFilePath: string, owner: ProcessLockOwnerRec publishFileSync({ destination: ownerFilePath, contents: JSON.stringify(owner), + mode: 0o600, + exactMode: true, }); } @@ -618,6 +622,8 @@ function clearLockDirectory( publishFileSync({ destination: ownerFilePath, contents: JSON.stringify(owner), + mode: 0o600, + exactMode: true, publish: 'link-exclusive', }); } catch {} diff --git a/src/cli/__tests__/auth-session-exchange.test.ts b/src/cli/__tests__/auth-session-exchange.test.ts new file mode 100644 index 0000000000..9ddc281ddb --- /dev/null +++ b/src/cli/__tests__/auth-session-exchange.test.ts @@ -0,0 +1,335 @@ +import { test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { + loginWithDeviceAuth, + readCliSession, + resolveRemoteAuth, + writeCliSession, +} from '../auth-session.ts'; +import * as hostKitFile from '@agent-device/host-kit/file'; +import { normalizeError } from '@agent-device/kernel/errors'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; + +const baseFlags = { + json: false, + help: false, + version: false, + daemonBaseUrl: 'https://bridge.agent-device.dev', + tenant: 'acme', + runId: 'run-123', +}; + +/** Pinned clock: every expiry before `2026-02-01T01:00:00.000Z` used in this file is past. */ +const now = () => Date.parse('2026-02-01T01:00:00.000Z'); +const expiredToken = { accessToken: 'adc_agent_expired', expiresAt: '2026-02-01T00:30:00.000Z' }; + +function jsonResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); +} + +function writeStoredSession(stateDir: string, overrides: Record = {}): void { + writeCliSession({ + stateDir, + session: { + version: 1, + id: 'session-pairing', + cloudBaseUrl: 'https://cloud.example', + refreshCredential: 'adc_refresh_old', + createdAt: '2026-01-01T00:00:00.000Z', + ...overrides, + }, + }); +} + +/** + * A device-code login whose approval has arrived with an access token this file's clock calls + * expired, so the login goes on to exchange it, and a refresh endpoint answering with `responses`. + */ +function deviceAuthIo(options: { + refreshResponses: Response[]; + warnings: string[]; + requestPaths: string[]; +}) { + const { refreshResponses, warnings, requestPaths } = options; + return { + now, + stdinIsTTY: true as const, + stdoutIsTTY: true as const, + stderr: { + write: (chunk: string) => { + warnings.push(chunk); + return true; + }, + }, + openBrowser: async () => {}, + fetch: async (url: URL | RequestInfo): Promise => { + const href = String(url); + requestPaths.push(new URL(href).pathname); + if (href.endsWith('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/device-auth/start')) { + return jsonResponse({ + deviceCode: 'device-secret', + userCode: 'ABCD-EFGH', + verificationUri: 'https://cloud.example/authorize', + interval: 1, + }); + } + if (href.endsWith('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/device-auth/poll')) { + return jsonResponse({ + status: 'approved', + ...expiredToken, + cliSession: { + id: 'session-pairing', + refreshCredential: 'adc_refresh_login', + expiresAt: '2099-01-01T00:00:00.000Z', + }, + }); + } + return refreshResponses.shift() ?? jsonResponse({}); + }, + }; +} + +/** + * A refresh whose access token the CLI's own clock calls expired is still the token the cloud would + * accept, so the command uses it: the exchange that asks again is optional, and a transient failure + * of it cannot take that token back. A response that reports revocation is never transient. + */ +test('an optional second exchange that fails transiently keeps the token already answered', async () => { + const run = async (secondResponse: Response) => { + const tempRoot = mkdtempForTestSync('agent-device-auth-optional-exchange-'); + writeStoredSession(tempRoot); + const sent: unknown[] = []; + try { + const resolved = await resolveRemoteAuth({ + command: 'snapshot', + flags: baseFlags, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + now, + fetch: async (_url, init) => { + sent.push(JSON.parse(String(init?.body)).refreshCredential); + return sent.length === 1 ? jsonResponse(expiredToken) : secondResponse; + }, + }, + }); + return { sent, token: resolved.flags.daemonAuthToken, error: undefined as unknown }; + } catch (error) { + return { sent, token: undefined, error }; + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + }; + + const unavailable = await run(new Response('unavailable', { status: 503 })); + assert.equal(unavailable.token, 'adc_agent_expired'); + assert.deepEqual(unavailable.sent, ['adc_refresh_old', 'adc_refresh_old']); + assert.equal(unavailable.error, undefined); + + // A transport failure of the optional exchange is transient as well. + const offline = await run(Promise.reject(new Error('offline')) as unknown as Response); + assert.equal(offline.token, 'adc_agent_expired'); + + // The token is kept, so a session the cloud reports revoked is still refused. + const revoked = await run(jsonResponse({ status: 'revoked' })); + assert.equal(revoked.token, undefined); + assert.equal(normalizeError(revoked.error).details?.reason, 'cli_session_revoked'); +}); + +/** + * Only a nonempty string is the approval's access-token expiry. A response that carries any other + * value has it omitted: the login neither reads liveness from a value it cannot read nor prints an + * expiry no token was issued against. + */ +test('an approval whose access-token expiry is not a string is reported without an expiry', async () => { + const run = async (expiresAt: unknown) => { + const tempRoot = mkdtempForTestSync('agent-device-auth-approval-expiry-type-'); + const requestPaths: string[] = []; + try { + const login = await loginWithDeviceAuth({ + stateDir: tempRoot, + flags: baseFlags, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example' }, + io: { + now, + stdinIsTTY: true, + stdoutIsTTY: true, + stderr: { write: () => true }, + openBrowser: async () => {}, + fetch: async (url): Promise => { + const href = String(url); + requestPaths.push(new URL(href).pathname); + if (href.endsWith('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/device-auth/start')) { + return jsonResponse({ + deviceCode: 'device-secret', + userCode: 'ABCD-EFGH', + verificationUri: 'https://cloud.example/authorize', + interval: 1, + }); + } + if (href.endsWith('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/device-auth/poll')) { + return jsonResponse({ + status: 'approved', + accessToken: 'adc_agent_approved', + // Neither of the values a real approval sends. Read as an expiry, the object is an + // unparseable timestamp, which says expired, and the number is a date far ahead of + // the pinned clock, which says live and gets printed. + expiresAt, + cliSession: { + id: 'session-pairing', + refreshCredential: 'adc_refresh_login', + expiresAt: '2099-01-01T00:00:00.000Z', + }, + }); + } + return jsonResponse({ accessToken: 'adc_agent_exchanged' }); + }, + }, + }); + return { login, requestPaths }; + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + }; + + // The value is omitted, so nothing tells this login its token is expired: it keeps the approved + // pair and asks for nothing. + const object = await run({}); + assert.equal(object.login.accessToken, 'adc_agent_approved'); + assert.equal(object.login.expiresAt, undefined); + assert.deepEqual(object.requestPaths, [ + '/api/control-plane/device-auth/start', + '/api/control-plane/device-auth/poll', + ]); + + // The number is omitted as well, so no expiry is reported for a token nothing issued it against. + const number = await run(2272143600000); + assert.equal(number.login.accessToken, 'adc_agent_approved'); + assert.equal(number.login.expiresAt, undefined); + + // The saved session's expiry comes from the session object, which is read the same way. + assert.equal(object.login.session.expiresAt, '2099-01-01T00:00:00.000Z'); +}); + +/** + * The login reports the session it saved. A rotation the cloud handed over that the disk refused was + * not saved, so it is not reported: the credential is still asked with next time, and the token + * keeps the expiry that arrived with it. + */ +test('a login whose rotation could not be saved reports the record on disk and its own token expiry', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-login-unsaved-rotation-'); + const sessionPath = `${tempRoot}/auth/cli-session.json`; + const realPublish = hostKitFile.publishFileSync; + const publish = vi.spyOn(hostKitFile, 'publishFileSync'); + try { + // The login's own write lands; the write of the rotation does not. + let writesToSessionFile = 0; + publish.mockImplementation((options) => { + if (options.destination === sessionPath) { + writesToSessionFile += 1; + if (writesToSessionFile > 1) throw new Error('ENOSPC'); + } + return realPublish(options); + }); + const warnings: string[] = []; + const requestPaths: string[] = []; + const login = await loginWithDeviceAuth({ + stateDir: tempRoot, + flags: baseFlags, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example' }, + io: deviceAuthIo({ + warnings, + requestPaths, + refreshResponses: [ + jsonResponse({ + accessToken: 'adc_agent_live', + expiresAt: '2026-02-01T02:00:00.000Z', + refreshCredential: 'adc_refresh_rotated', + cliSession: { expiresAt: '2099-12-24T00:00:00.000Z' }, + }), + ], + }), + }); + + // The token the exchange answered with, with the expiry that arrived with it. + assert.equal(login.accessToken, 'adc_agent_live'); + assert.equal(login.expiresAt, '2026-02-01T02:00:00.000Z'); + // The record reported is the one the file holds, not the one the failed write would have made. + const stored = readCliSession({ stateDir: tempRoot })!; + assert.deepEqual( + { + id: login.session.id, + refreshCredential: login.session.refreshCredential, + expiresAt: login.session.expiresAt, + }, + { + id: stored.id, + refreshCredential: stored.refreshCredential, + expiresAt: stored.expiresAt, + }, + ); + assert.equal(login.session.refreshCredential, 'adc_refresh_login'); + assert.equal(login.session.expiresAt, '2099-01-01T00:00:00.000Z'); + assert.equal( + JSON.stringify(login.session).includes('2099-12-24'), + false, + 'the expiry of a rotation that was not saved is not reported', + ); + assert.match(warnings.join(''), /renewed CLI session could not be saved/); + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_login'); + } finally { + publish.mockRestore(); + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +/** + * When the optional second exchange fails, the login still reports the record its first exchange + * stored: the session expiry `auth status` will show, not the one the approval wrote. + */ +test('a login whose second exchange fails reports the session its first exchange stored', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-login-rotated-then-503-'); + const warnings: string[] = []; + const requestPaths: string[] = []; + try { + const login = await loginWithDeviceAuth({ + stateDir: tempRoot, + flags: baseFlags, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example' }, + io: deviceAuthIo({ + warnings, + requestPaths, + refreshResponses: [ + // The rotation is stored, and the access token comes back expired on this clock, so a + // second exchange is asked for and fails. + jsonResponse({ + ...expiredToken, + refreshCredential: 'adc_refresh_rotated', + cliSession: { expiresAt: '2099-12-24T00:00:00.000Z' }, + }), + new Response('unavailable', { status: 503 }), + ], + }), + }); + + assert.deepEqual(login.session, readCliSession({ stateDir: tempRoot })); + assert.equal(login.session.refreshCredential, 'adc_refresh_rotated'); + assert.equal(login.session.expiresAt, '2099-12-24T00:00:00.000Z'); + // The token kept is the one the cloud answered, with its own expiry. + assert.equal(login.accessToken, 'adc_agent_expired'); + assert.equal(login.expiresAt, '2026-02-01T00:30:00.000Z'); + // Nothing was lost: the login is not told to sign in again. + assert.equal(warnings.join('').includes('could not be'), false); + assert.deepEqual(requestPaths.slice(2), [ + '/api/control-plane/cli-session/refresh', + '/api/control-plane/cli-session/refresh', + ]); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); diff --git a/src/cli/__tests__/auth-session-refresh.test.ts b/src/cli/__tests__/auth-session-refresh.test.ts new file mode 100644 index 0000000000..543b7defda --- /dev/null +++ b/src/cli/__tests__/auth-session-refresh.test.ts @@ -0,0 +1,523 @@ +import { test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { + loginWithDeviceAuth, + readCliSession, + resolveCliSessionPath, + resolveRemoteAuth, + writeCliSession, +} from '../auth-session.ts'; +import * as hostKitFile from '@agent-device/host-kit/file'; +import { acquireProcessLock } from '@agent-device/host-kit/file'; +import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; +import { normalizeError } from '@agent-device/kernel/errors'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; + +const baseFlags = { + json: false, + help: false, + version: false, + daemonBaseUrl: 'https://daemon.example', + tenant: 'acme', + runId: 'run-123', +}; + +const refreshFlags = { ...baseFlags, daemonBaseUrl: 'https://bridge.agent-device.dev' }; + +function jsonResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); +} + +/** Writes a stored session the refresh commands can rotate. */ +function writeStoredSession(stateDir: string, overrides: Record = {}): void { + writeCliSession({ + stateDir, + session: { + version: 1, + id: 'session-refresh', + cloudBaseUrl: 'https://cloud.example', + refreshCredential: 'adc_refresh_old', + createdAt: '2026-01-01T00:00:00.000Z', + ...overrides, + }, + }); +} + +test('a session lock held by a logout keeps a credential read without the lock from being sent', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-locked-read-'); + writeStoredSession(tempRoot); + const owner = readCurrentOwnerIdentity(); + const releaseLock = await acquireProcessLock({ + lockDirPath: `${resolveCliSessionPath(tempRoot)}.lock`, + owner: { pid: owner.pid, startTime: owner.startTime, acquiredAtMs: Date.now() }, + description: 'test logout', + }); + const sentCredentials: unknown[] = []; + const refresh = resolveRemoteAuth({ + command: 'snapshot', + flags: { ...refreshFlags, noLogin: true }, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + fetch: async (_url, init) => { + sentCredentials.push(JSON.parse(String(init?.body)).refreshCredential); + return jsonResponse({ accessToken: 'adc_agent_1', refreshCredential: 'adc_refresh_new' }); + }, + }, + }); + + await new Promise((resolve) => setTimeout(resolve, 200)); + // No request is sent while another process holds the lock, so no credential goes out unlocked. + assert.deepEqual(sentCredentials, []); + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_old'); + // The logout's removal lands, and the lock is given back. + fs.rmSync(resolveCliSessionPath(tempRoot)); + await releaseLock(); + + await assert.rejects( + async () => await refresh, + (error: unknown) => normalizeError(error).code === 'UNAUTHORIZED', + ); + // The refresh re-read after taking the lock, found no session, and never sent the credential. + assert.deepEqual(sentCredentials, []); + assert.equal(readCliSession({ stateDir: tempRoot }), null); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + +test('a login whose approved access token already expired returns a fresh one', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-login-expired-'); + const sent: unknown[] = []; + const login = await loginWithDeviceAuth({ + stateDir: tempRoot, + flags: baseFlags, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example' }, + io: { + // The approval arrives after the token that came with it had already expired: a wait for + // another process's session lock can spend longer than the token's life. + now: () => Date.parse('2026-02-01T01:00:00.000Z'), + stdinIsTTY: true, + stdoutIsTTY: true, + openBrowser: async () => {}, + fetch: async (url, init) => { + const href = String(url); + if (href.endsWith('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/device-auth/start')) { + return jsonResponse({ + deviceCode: 'device-secret', + userCode: 'ABCD-EFGH', + verificationUri: 'https://cloud.example/authorize', + interval: 1, + }); + } + if (href.endsWith('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/device-auth/poll')) { + return jsonResponse({ + status: 'approved', + accessToken: 'adc_agent_expired', + expiresAt: '2026-02-01T00:30:00.000Z', + cliSession: { + id: 'session-expired', + refreshCredential: 'adc_refresh_login', + expiresAt: '2026-06-01T00:00:00.000Z', + }, + }); + } + sent.push(JSON.parse(String(init?.body)).refreshCredential); + return jsonResponse({ + accessToken: 'adc_agent_fresh', + expiresAt: '2026-02-01T02:00:00.000Z', + }); + }, + }, + }); + + assert.equal(login.accessToken, 'adc_agent_fresh'); + assert.equal(login.expiresAt, '2026-02-01T02:00:00.000Z'); + // The exchange ran on the session the login had just saved. + assert.deepEqual(sent, ['adc_refresh_login']); + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_login'); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + +test('a refresh that answers with an expired access token is asked again, and no further', async () => { + const run = async (responses: unknown[]) => { + const tempRoot = mkdtempForTestSync('agent-device-auth-refresh-expired-'); + writeStoredSession(tempRoot); + const sent: unknown[] = []; + try { + const result = await resolveRemoteAuth({ + command: 'snapshot', + flags: refreshFlags, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + now: () => Date.parse('2026-02-01T01:00:00.000Z'), + fetch: async (_url, init) => { + sent.push(JSON.parse(String(init?.body)).refreshCredential); + return jsonResponse(responses.shift()); + }, + }, + }); + return { sent, token: result.flags.daemonAuthToken }; + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + }; + const expired = { + accessToken: 'adc_agent_expired', + expiresAt: '2026-02-01T00:30:00.000Z', + refreshCredential: 'adc_refresh_new', + }; + + // The replacement credential is exchanged for a token that is not expired. + const once = await run([ + expired, + { accessToken: 'adc_agent_fresh', expiresAt: '2026-02-01T02:00:00.000Z' }, + ]); + assert.equal(once.token, 'adc_agent_fresh'); + assert.deepEqual(once.sent, ['adc_refresh_old', 'adc_refresh_new']); + + // A cloud that keeps answering with an expired token is asked twice, then answered with. + const endless = await run([expired, expired]); + assert.equal(endless.token, 'adc_agent_expired'); + assert.deepEqual(endless.sent, ['adc_refresh_old', 'adc_refresh_new']); +}); + +test('a rotated credential is stored with the session expiry the refresh response carries', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-rotate-expiry-'); + writeStoredSession(tempRoot, { expiresAt: '2026-06-01T00:00:00.000Z' }); + const stored = readCliSession({ stateDir: tempRoot })!; + + await resolveRemoteAuth({ + command: 'snapshot', + flags: refreshFlags, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + now: () => Date.parse('2026-02-01T00:00:00.000Z'), + fetch: async () => + jsonResponse({ + accessToken: 'adc_agent_1', + // The access token's own expiry, which is not the session's. + expiresAt: '2026-02-01T01:00:00.000Z', + refreshCredential: 'adc_refresh_new', + cliSession: { expiresAt: '2026-12-24T00:00:00.000Z' }, + }), + }, + }); + + assert.deepEqual(readCliSession({ stateDir: tempRoot }), { + ...stored, + refreshCredential: 'adc_refresh_new', + // A session expiry that slides with use replaces the one recorded at login. + expiresAt: '2026-12-24T00:00:00.000Z', + }); + + // An expiry that cannot be read is not stored: it would read back as an expired session and lock + // the CLI out of one that still works. The rotation itself is kept. + writeCliSession({ + stateDir: tempRoot, + session: { ...stored, refreshCredential: 'adc_refresh_b' }, + }); + await resolveRemoteAuth({ + command: 'snapshot', + flags: refreshFlags, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + now: () => Date.parse('2026-02-01T00:00:00.000Z'), + fetch: async () => + jsonResponse({ + accessToken: 'adc_agent_2', + refreshCredential: 'adc_refresh_c', + cliSession: { expiresAt: 'soon' }, + }), + }, + }); + assert.deepEqual(readCliSession({ stateDir: tempRoot }), { + ...stored, + refreshCredential: 'adc_refresh_c', + }); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + +test('a refresh response that reports revocation is refused even when it carries tokens', async () => { + const refusal = async (revokedField: { status: string } | { error: string }) => { + const tempRoot = mkdtempForTestSync('agent-device-auth-revoked-tokens-'); + writeStoredSession(tempRoot, { + id: 'session-revoked-tokens', + refreshCredential: 'adc_refresh_stored', + }); + try { + await assert.rejects( + async () => + await resolveRemoteAuth({ + command: 'snapshot', + flags: refreshFlags, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + fetch: async () => + jsonResponse({ + ...revokedField, + accessToken: 'adc_agent_rogue', + refreshCredential: 'adc_refresh_rogue', + }), + }, + }), + /Stored cloud CLI session was revoked/, + ); + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_stored'); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + }; + + await refusal({ status: 'revoked' }); + await refusal({ error: 'revoked' }); +}); + +test('a store of the rotated credential that fails keeps the access token and warns', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-rotate-write-'); + writeStoredSession(tempRoot, { id: 'session-write' }); + const sessionPath = resolveCliSessionPath(tempRoot); + const realPublish = hostKitFile.publishFileSync; + const publish = vi.spyOn(hostKitFile, 'publishFileSync'); + try { + // The publish of the session file fails; the lock records beside it still publish. + publish.mockImplementation((options) => { + if (options.destination === sessionPath) throw new Error('ENOSPC'); + return realPublish(options); + }); + let warning = ''; + const result = await resolveRemoteAuth({ + command: 'snapshot', + flags: refreshFlags, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + stderr: { + write: (chunk: string) => { + warning += chunk; + return true; + }, + }, + fetch: async () => + jsonResponse({ accessToken: 'adc_agent_1', refreshCredential: 'adc_refresh_new' }), + }, + }); + + assert.equal(result.flags.daemonAuthToken, 'adc_agent_1'); + assert.match(warning, /could not be saved.*agent-device auth login/); + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_old'); + } finally { + publish.mockRestore(); + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +/** + * An approved login has its session saved before the token exchange runs, so an exchange that fails + * transiently is not the login's failure: `auth login` printed a session, not a token. A caller that + * sends the token itself cannot recover, so it reports the same failure. + */ +test('an expired approval token whose exchange fails transiently keeps the login and fails the caller that spends the token', async () => { + const run = async (requiresLiveToken: boolean) => { + const tempRoot = mkdtempForTestSync('agent-device-auth-login-exchange-503-'); + const warnings: string[] = []; + const requestPaths: string[] = []; + const io = { + now: () => Date.parse('2026-02-01T01:00:00.000Z'), + stdinIsTTY: true as const, + stdoutIsTTY: true as const, + stderr: { + write: (chunk: string) => { + warnings.push(chunk); + return true; + }, + }, + openBrowser: async () => {}, + fetch: async (url: URL | RequestInfo) => { + const href = String(url); + requestPaths.push(new URL(href).pathname); + if (href.endsWith('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/device-auth/start')) { + return jsonResponse({ + deviceCode: 'device-secret', + userCode: 'ABCD-EFGH', + verificationUri: 'https://cloud.example/authorize', + interval: 1, + }); + } + if (href.endsWith('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/device-auth/poll')) { + return jsonResponse({ + status: 'approved', + accessToken: 'adc_agent_expired', + // Past on the pinned clock: the login has to exchange this token. + expiresAt: '2026-02-01T00:30:00.000Z', + cliSession: { id: 'session-503', refreshCredential: 'adc_refresh_503' }, + }); + } + return new Response('private-body-secret', { status: 503 }); + }, + }; + try { + const outcome = await (async () => { + if (!requiresLiveToken) { + const login = await loginWithDeviceAuth({ + stateDir: tempRoot, + flags: baseFlags, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example' }, + io, + }); + return { accessToken: login.accessToken, expiresAt: login.expiresAt }; + } + const resolved = await resolveRemoteAuth({ + command: 'connect', + flags: refreshFlags, + stateDir: tempRoot, + allowInteractiveLogin: true, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example' }, + io, + }); + return { accessToken: resolved.flags.daemonAuthToken, expiresAt: undefined }; + })(); + return { + outcome, + warnings, + requestPaths, + stored: readCliSession({ stateDir: tempRoot }), + }; + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + }; + + // `auth login` printed a session: it reports success, without the expiry of a token the cloud + // already said was expired, and the saved session is there for the next command. + const login = await run(false); + assert.equal(login.outcome.accessToken, 'adc_agent_expired'); + assert.equal(login.outcome.expiresAt, undefined); + assert.equal(login.stored?.id, 'session-503'); + assert.match(login.warnings.join(''), /could not be exchanged for a live access token/); + assert.deepEqual(login.requestPaths, [ + '/api/control-plane/device-auth/start', + '/api/control-plane/device-auth/poll', + '/api/control-plane/cli-session/refresh', + ]); + + // `connect` sends the token it is handed, so the same 503 fails it. + await assert.rejects( + async () => await run(true), + (error: unknown) => normalizeError(error).details?.status === 503, + ); +}); + +/** + * The login's save and the exchange of an expired approval token share one acquisition of the + * session lock, so a sibling login cannot write its own session between them and have its + * credential exchanged here. + */ +test('a login that exchanges an expired approval token does it under the acquisition that saved the session', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-login-one-lock-'); + const realAcquire = hostKitFile.acquireProcessLock; + const acquire = vi.spyOn(hostKitFile, 'acquireProcessLock'); + const events: string[] = []; + const sent: unknown[] = []; + try { + acquire.mockImplementation((async (params) => { + const release = await realAcquire(params); + events.push('acquire'); + return async () => { + events.push('release'); + await release(); + }; + }) as typeof acquire); + const login = await loginWithDeviceAuth({ + stateDir: tempRoot, + flags: baseFlags, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example' }, + io: { + now: () => Date.parse('2026-02-01T01:00:00.000Z'), + stdinIsTTY: true, + stdoutIsTTY: true, + openBrowser: async () => {}, + fetch: async (url, init) => { + const href = String(url); + if (href.endsWith('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/device-auth/start')) { + return jsonResponse({ + deviceCode: 'device-secret', + userCode: 'ABCD-EFGH', + verificationUri: 'https://cloud.example/authorize', + interval: 1, + }); + } + if (href.endsWith('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/device-auth/poll')) { + return jsonResponse({ + status: 'approved', + accessToken: 'adc_agent_expired', + expiresAt: '2026-02-01T00:30:00.000Z', + cliSession: { id: 'session-one-lock', refreshCredential: 'adc_refresh_one' }, + }); + } + events.push('refresh'); + sent.push(JSON.parse(String(init?.body)).refreshCredential); + return jsonResponse({ + accessToken: 'adc_agent_live', + expiresAt: '2026-02-01T02:00:00.000Z', + }); + }, + }, + }); + + assert.equal(login.accessToken, 'adc_agent_live'); + assert.deepEqual(sent, ['adc_refresh_one']); + assert.deepEqual(events, ['acquire', 'refresh', 'release']); + } finally { + acquire.mockRestore(); + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('parallel commands each send the stored credential, so a replacement is sent once', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-rotate-parallel-'); + writeStoredSession(tempRoot, { id: 'session-parallel' }); + // The cloud's side of the contract: the first request gets the one replacement; a request that + // presents the replaced credential is refused, which a serialized refresh never does. + const sent: unknown[] = []; + const refresh = () => + resolveRemoteAuth({ + command: 'snapshot', + flags: refreshFlags, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + fetch: async (_url, init) => { + const credential = JSON.parse(String(init?.body)).refreshCredential; + sent.push(credential); + return jsonResponse( + credential === 'adc_refresh_old' + ? { accessToken: 'adc_agent_a', refreshCredential: 'adc_refresh_new' } + : { accessToken: 'adc_agent_b' }, + ); + }, + }, + }); + + const both = await Promise.all([refresh(), refresh()]); + const tokens = both.map((result) => result.flags.daemonAuthToken); + + // The second command waited for the first to store, and read the replacement off the file. + assert.deepEqual(tokens, ['adc_agent_a', 'adc_agent_b']); + assert.deepEqual(sent, ['adc_refresh_old', 'adc_refresh_new']); + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_new'); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); diff --git a/src/cli/__tests__/auth-session-refusal.test.ts b/src/cli/__tests__/auth-session-refusal.test.ts new file mode 100644 index 0000000000..0faba91711 --- /dev/null +++ b/src/cli/__tests__/auth-session-refusal.test.ts @@ -0,0 +1,321 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { normalizeError } from '@agent-device/kernel/errors'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { + loginWithDeviceAuth, + readCliSession, + resolveCliSessionPath, + resolveRemoteAuth, + writeCliSession, +} from '../auth-session.ts'; + +const baseFlags = { + json: false, + help: false, + version: false, + daemonBaseUrl: 'https://bridge.agent-device.dev', + tenant: 'acme', + runId: 'run-123', +}; + +/** The credential a hostile response can echo back in a field the CLI does not recognize. */ +const ECHOED_CREDENTIAL = 'adc_echoed_opaque_credential'; + +function jsonResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); +} + +function writeStoredSession(stateDir: string): void { + writeCliSession({ + stateDir, + session: { + version: 1, + id: 'session-refusal', + cloudBaseUrl: 'https://cloud.example', + refreshCredential: 'adc_refresh_stored', + createdAt: '2026-01-01T00:00:00.000Z', + }, + }); +} + +function refreshWithResponse(stateDir: string, body: unknown): Promise { + return resolveRemoteAuth({ + command: 'snapshot', + flags: baseFlags, + stateDir, + allowInteractiveLogin: false, + env: {}, + io: { fetch: async () => jsonResponse(body) }, + }); +} + +/** + * A refresh refusal carries the reason this CLI declares and nothing the response supplied: the + * cloud's `status` and `error` are its text, and under those keys the redaction step does not + * recognize an opaque credential, so `--json` would print one. Only the exact `revoked` marker is + * confirmed revocation; an answer without an access token gets the tokenless reason. + */ +test('a refused refresh carries its reason and no text from the response', async () => { + const revoked = 'cli_session_revoked'; + const tokenless = 'cli_session_refresh_unanswered'; + const refusals: Array<{ name: string; body: unknown; reason: string }> = [ + { + name: 'revoked with tokens and an echoed credential in error', + body: { status: 'revoked', error: ECHOED_CREDENTIAL, accessToken: 'adc_agent_rogue' }, + reason: revoked, + }, + { + name: 'revoked with tokens and an echoed credential in status', + body: { status: ECHOED_CREDENTIAL, error: 'revoked', accessToken: 'adc_agent_rogue' }, + reason: revoked, + }, + { + name: 'no token and an echoed credential in error', + body: { status: 'unknown_status', error: ECHOED_CREDENTIAL }, + reason: tokenless, + }, + { + name: 'no token and an echoed credential in status', + body: { status: ECHOED_CREDENTIAL, error: 'unknown_error' }, + reason: tokenless, + }, + { + name: 'a successful answer that carries no access token', + body: { cliSession: { expiresAt: '2026-12-24T00:00:00.000Z' } }, + reason: tokenless, + }, + ]; + + for (const { name, body, reason } of refusals) { + const tempRoot = mkdtempForTestSync('agent-device-auth-refusal-'); + writeStoredSession(tempRoot); + try { + await assert.rejects( + async () => await refreshWithResponse(tempRoot, body), + (error: unknown) => { + const normalized = normalizeError(error); + assert.equal(normalized.code, 'UNAUTHORIZED', name); + assert.equal(normalized.details?.reason, reason, name); + assert.equal(normalized.details?.status, undefined, name); + assert.equal(normalized.details?.error, undefined, name); + // The recovery hint is this CLI's own. + assert.match(normalized.hint ?? '', /agent-device auth login/, name); + // Neither the message nor any serialized detail can carry the echoed value. + assert.equal(JSON.stringify(normalized).includes(ECHOED_CREDENTIAL), false, name); + return true; + }, + name, + ); + // A refusal stores nothing: the session stays as it was. + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_stored'); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + } +}); + +test('an approval that reports revocation over HTTP is refused and never echoes its body', async () => { + const revokedBodies: unknown[] = [ + { status: 'revoked', error: ECHOED_CREDENTIAL }, + { status: ECHOED_CREDENTIAL, error: 'revoked' }, + ]; + for (const body of revokedBodies) { + for (const status of [401, 403, 503]) { + const tempRoot = mkdtempForTestSync('agent-device-auth-revoked-http-'); + writeStoredSession(tempRoot); + try { + await assert.rejects( + async () => + await resolveRemoteAuth({ + command: 'snapshot', + flags: baseFlags, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { fetch: async () => new Response(JSON.stringify(body), { status }) }, + }), + (error: unknown) => { + const normalized = normalizeError(error); + assert.equal(normalized.code, 'UNAUTHORIZED', `${status} ${JSON.stringify(body)}`); + assert.equal( + normalized.details?.reason, + 'cli_session_revoked', + `${status} ${JSON.stringify(body)}`, + ); + // The generic status details are not attached to a classified refusal, and no text from + // the body accompanies it. + assert.equal(normalized.details?.status, undefined, `${status}`); + assert.equal( + JSON.stringify(normalized).includes(ECHOED_CREDENTIAL), + false, + `${status}`, + ); + return true; + }, + ); + assert.equal( + readCliSession({ stateDir: tempRoot })?.refreshCredential, + 'adc_refresh_stored', + ); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + } + } +}); + +/** + * A rejected response that does not carry this CLI's exact `revoked` marker keeps the generic HTTP + * refusal, so a transient status stays retriable and a credential echoed in its body stays out of it. + */ +test('a rejected refresh without the revocation marker keeps the generic status refusal', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-revoked-http-plain-'); + writeStoredSession(tempRoot); + try { + await assert.rejects( + async () => + await resolveRemoteAuth({ + command: 'snapshot', + flags: baseFlags, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + fetch: async () => + new Response( + JSON.stringify({ status: 'authorization_pending', error: ECHOED_CREDENTIAL }), + { status: 503 }, + ), + }, + }), + (error: unknown) => { + const normalized = normalizeError(error); + assert.equal(normalized.code, 'COMMAND_FAILED'); + assert.equal(normalized.details?.status, 503); + assert.equal(normalized.details?.reason, undefined); + assert.equal(normalized.retriable, true); + assert.equal(JSON.stringify(normalized).includes(ECHOED_CREDENTIAL), false); + return true; + }, + ); + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_stored'); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +/** + * A refresh that answers without an access token is not proof the session is gone, so an explicit + * login that has already saved its session keeps it and succeeds. Only the exact `revoked` marker + * takes a saved login back. + */ +test('a tokenless refresh keeps the session an explicit login saved and a revoked one fails it', async () => { + const run = async (refreshBody: unknown) => { + const tempRoot = mkdtempForTestSync('agent-device-auth-tokenless-login-'); + let warnings = ''; + try { + const login = await loginWithDeviceAuth({ + stateDir: tempRoot, + flags: { ...baseFlags, daemonBaseUrl: 'https://cloud.example' }, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example' }, + io: { + // Past the approved token's expiry, so the login has to exchange it. + now: () => Date.parse('2026-02-01T01:00:00.000Z'), + stdinIsTTY: true, + stdoutIsTTY: true, + stderr: { + write: (chunk: string) => { + warnings += chunk; + return true; + }, + }, + openBrowser: async () => {}, + fetch: async (url) => + String(url).endsWith('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/device-auth/start') + ? jsonResponse({ + deviceCode: 'device-secret', + userCode: 'ABCD-EFGH', + verificationUri: 'https://cloud.example/authorize', + interval: 1, + }) + : String(url).endsWith('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/device-auth/poll') + ? jsonResponse({ + status: 'approved', + accessToken: 'adc_agent_expired', + expiresAt: '2026-02-01T00:30:00.000Z', + cliSession: { + id: 'session-tokenless', + refreshCredential: 'adc_refresh_tokenless', + }, + }) + : jsonResponse(refreshBody), + }, + }); + return { login, warnings, error: undefined as unknown }; + } catch (error) { + return { login: undefined, warnings, error }; + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + }; + + const tokenless = await run({ cliSession: { expiresAt: '2099-12-24T00:00:00.000Z' } }); + // The login keeps the session it saved and reports no token expiry: no token came back. + assert.equal(tokenless.error, undefined); + assert.equal(tokenless.login?.accessToken, 'adc_agent_expired'); + assert.equal(tokenless.login?.expiresAt, undefined); + assert.equal(tokenless.login?.session.id, 'session-tokenless'); + assert.match(tokenless.warnings, /could not be exchanged for a live access token/); + + // The exact marker is still a refusal, even to an explicit login that has saved its session. + const revoked = await run({ status: 'revoked' }); + assert.equal(normalizeError(revoked.error).details?.reason, 'cli_session_revoked'); +}); + +test.skipIf(process.platform === 'win32')( + 'a session store that cannot be written refuses with the directory to repair', + async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-store-unwritable-'); + writeStoredSession(tempRoot); + const authDir = path.dirname(resolveCliSessionPath(tempRoot)); + fs.chmodSync(authDir, 0o500); + try { + let sent = 0; + await assert.rejects( + async () => + await resolveRemoteAuth({ + command: 'snapshot', + flags: baseFlags, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + fetch: async () => { + sent += 1; + return jsonResponse({ accessToken: 'adc_agent_1' }); + }, + }, + }), + (error: unknown) => { + const normalized = normalizeError(error); + assert.equal(normalized.details?.reason, 'cli_session_store_unwritable'); + assert.equal(normalized.details?.authDir, authDir); + // The hint names the exact directory and the command that ends the problem. + assert.ok(normalized.hint?.includes(`chmod 700 ${authDir}`)); + return true; + }, + ); + assert.equal(sent, 0); + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_stored'); + } finally { + fs.chmodSync(authDir, 0o700); + 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 1b4d87193c..2f4d0eb4df 100644 --- a/src/cli/__tests__/auth-session.test.ts +++ b/src/cli/__tests__/auth-session.test.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest'; +import { test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; @@ -11,7 +11,8 @@ import { summarizeCliSession, writeCliSession, } from '../auth-session.ts'; -import { normalizeError, type NormalizedError } from '@agent-device/kernel/errors'; +import * as hostKitFile from '@agent-device/host-kit/file'; +import { AppError, normalizeError, type NormalizedError } from '@agent-device/kernel/errors'; import { mkdtempForTestSync, recordCommandSpawns, @@ -162,6 +163,7 @@ test('remote auth refreshes a stored CLI session into an agent token', async () assert.deepEqual(bodies, [ { refreshCredential: 'adc_refresh_secret', + acceptsRotatedRefreshCredential: true, tenant: 'acme', runId: 'run-123', daemonBaseUrl: 'https://bridge.agent-device.dev', @@ -170,6 +172,296 @@ test('remote auth refreshes a stored CLI session into an agent token', async () 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 = { + version: 1 as const, + id: 'session-rotate', + cloudBaseUrl: 'https://cloud.example', + refreshCredential: 'adc_refresh_old', + createdAt: '2026-01-01T00:00:00.000Z', + expiresAt: '2026-12-01T00:00:00.000Z', + }; + writeCliSession({ stateDir: tempRoot, session }); + const sent: unknown[] = []; + const responses = [ + { accessToken: 'adc_agent_1', refreshCredential: 'adc_refresh_new' }, + { accessToken: 'adc_agent_2' }, + ]; + const refresh = () => + resolveRemoteAuth({ + command: 'snapshot', + flags: { ...baseFlags, daemonBaseUrl: 'https://bridge.agent-device.dev' }, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + now: () => Date.parse('2026-02-01T00:00:00.000Z'), + fetch: async (_url, init) => { + sent.push(JSON.parse(String(init?.body)).refreshCredential); + return jsonResponse(responses.shift()); + }, + }, + }); + + assert.equal((await refresh()).flags.daemonAuthToken, 'adc_agent_1'); + assert.deepEqual(readCliSession({ stateDir: tempRoot }), { + ...session, + refreshCredential: 'adc_refresh_new', + }); + // The next command sends the rotated credential; a response without one keeps it. + assert.equal((await refresh()).flags.daemonAuthToken, 'adc_agent_2'); + assert.deepEqual(sent, ['adc_refresh_old', 'adc_refresh_new']); + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_new'); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + +/** + * A refresh writes only when the file still holds what it sent, so a session the refresh did not + * write keeps whatever it holds. These changes happen while the refresh holds the session lock, so + * they are made by a writer that takes no lock: an older CLI build, or an edit of the file. The + * cooperating sibling's ordering, a logout or a store that completes before the lock is taken, is + * covered in auth-session-refresh.test.ts. + */ +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, + id: 'session-race', + cloudBaseUrl: 'https://cloud.example', + refreshCredential: 'adc_refresh_old', + createdAt: '2026-01-01T00:00:00.000Z', + }; + const refreshWhile = ( + change: () => void, + response: object, + stderr?: { write: (chunk: string) => boolean }, + ) => + resolveRemoteAuth({ + command: 'snapshot', + flags: { ...baseFlags, daemonBaseUrl: 'https://bridge.agent-device.dev' }, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + stderr, + fetch: async () => { + change(); + return jsonResponse(response); + }, + }, + }); + const rotated = { accessToken: 'adc_agent_1', refreshCredential: 'adc_refresh_late' }; + + // Another writer stored its own rotated credential first. + writeCliSession({ stateDir: tempRoot, session }); + const other = { ...session, refreshCredential: 'adc_refresh_other' }; + await refreshWhile(() => writeCliSession({ stateDir: tempRoot, session: other }), rotated); + assert.deepEqual(readCliSession({ stateDir: tempRoot }), other); + + // A removal that took the file away stays a removal. + writeCliSession({ stateDir: tempRoot, session }); + await refreshWhile(() => fs.rmSync(resolveCliSessionPath(tempRoot)), rotated); + assert.equal(readCliSession({ stateDir: tempRoot }), null); + + // A cloud that returns the same credential causes no write. + writeCliSession({ stateDir: tempRoot, session }); + const before = fs.statSync(resolveCliSessionPath(tempRoot)).ino; + await refreshWhile(() => {}, { + accessToken: 'adc_agent_2', + refreshCredential: 'adc_refresh_old', + }); + assert.equal(fs.statSync(resolveCliSessionPath(tempRoot)).ino, before); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + +test('logout without a stored session takes no lock and writes nothing', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-logout-empty-'); + + assert.equal(await removeCliSession({ stateDir: tempRoot }), false); + assert.equal(fs.existsSync(path.dirname(resolveCliSessionPath(tempRoot))), false); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + +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, + id: 'session-release', + cloudBaseUrl: 'https://cloud.example', + refreshCredential: 'adc_refresh_old', + createdAt: '2026-01-01T00:00:00.000Z', + }; + const failingRelease = async () => { + throw new Error('lock standing under a spent claim'); + }; + const acquire = vi.spyOn(hostKitFile, 'acquireProcessLock'); + const refresh = (stderr: { write: (chunk: string) => boolean }) => + resolveRemoteAuth({ + command: 'snapshot', + flags: { ...baseFlags, daemonBaseUrl: 'https://bridge.agent-device.dev' }, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + stderr, + fetch: async () => + jsonResponse({ accessToken: 'adc_agent_1', refreshCredential: 'adc_refresh_new' }), + }, + }); + + try { + writeCliSession({ stateDir: tempRoot, session }); + acquire.mockResolvedValueOnce(failingRelease); + const warnings: string[] = []; + const result = await refresh({ write: (chunk) => warnings.push(chunk) > 0 }); + assert.equal(result.flags.daemonAuthToken, 'adc_agent_1'); + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_new'); + assert.match(warnings.join(''), /lock could not be released cleanly/); + + // A stderr that throws does not fail the change either. + writeCliSession({ stateDir: tempRoot, session }); + acquire.mockResolvedValueOnce(failingRelease); + const thrown = await refresh({ + write: () => { + throw new Error('EPIPE'); + }, + }); + assert.equal(thrown.flags.daemonAuthToken, 'adc_agent_1'); + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_new'); + } finally { + acquire.mockRestore(); + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('a timed-out session lock wait keeps a login waiting and fails a refresh read with its reason', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-lock-timeout-'); + const timeout = new AppError('COMMAND_FAILED', 'Timed out waiting for cloud CLI session file', { + reason: 'process_lock_timeout', + }); + const acquire = vi.spyOn(hostKitFile, 'acquireProcessLock'); + const warnings: string[] = []; + const stderr = { write: (chunk: string) => warnings.push(chunk) > 0 }; + try { + writeCliSession({ + stateDir: tempRoot, + session: { + version: 1, + id: 'session-timeout', + cloudBaseUrl: 'https://cloud.example', + refreshCredential: 'adc_refresh_old', + createdAt: '2026-01-01T00:00:00.000Z', + }, + }); + // A refresh read is repeatable, so a wait that times out is the command's failure: no request is + // sent, nothing is stored, and the command does not queue forever behind the lock. + acquire.mockRejectedValueOnce(timeout); + let refreshes = 0; + await assert.rejects( + async () => + await resolveRemoteAuth({ + command: 'snapshot', + flags: { ...baseFlags, daemonBaseUrl: 'https://bridge.agent-device.dev' }, + stateDir: tempRoot, + allowInteractiveLogin: false, + env: {}, + io: { + stderr, + fetch: async () => { + refreshes += 1; + return jsonResponse({ + accessToken: 'adc_agent_1', + refreshCredential: 'adc_refresh_new', + }); + }, + }, + }), + (error: unknown) => normalizeError(error).details?.reason === 'process_lock_timeout', + ); + assert.equal(refreshes, 0); + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_old'); + assert.equal(warnings.length, 0); + + // An approved login is not repeatable, so its save waits as long as the lock is held. + acquire.mockRejectedValueOnce(timeout); + let approvals = 0; + await loginWithDeviceAuth({ + stateDir: tempRoot, + flags: baseFlags, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example' }, + io: { + stdinIsTTY: true, + stdoutIsTTY: true, + stderr, + openBrowser: async () => {}, + fetch: async (url) => { + if (String(url).endsWith('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/device-auth/start')) { + approvals += 1; + return jsonResponse({ + deviceCode: 'device-secret', + userCode: 'ABCD-EFGH', + verificationUri: 'https://cloud.example/authorize', + expiresIn: 600, + interval: 1, + }); + } + return jsonResponse({ + status: 'approved', + accessToken: 'adc_agent_login', + cliSession: { id: 'session-login', refreshCredential: 'adc_refresh_login' }, + }); + }, + }, + }); + assert.equal(approvals, 1); + assert.equal(readCliSession({ stateDir: tempRoot })?.refreshCredential, 'adc_refresh_login'); + assert.equal( + warnings.filter((line) => line.startsWith('Waiting for another agent-device process')).length, + 1, + ); + } finally { + acquire.mockRestore(); + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('device login does not print a user code that carries control characters', async () => { + const tempRoot = mkdtempForTestSync('agent-device-auth-code-'); + let stderr = ''; + await loginWithDeviceAuth({ + stateDir: tempRoot, + flags: baseFlags, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example' }, + io: { + stdinIsTTY: true, + stdoutIsTTY: true, + stderr: { + write: (chunk: string) => { + stderr += chunk; + return true; + }, + }, + openBrowser: async () => {}, + fetch: async (url) => + String(url).endsWith('/start') + ? jsonResponse({ + deviceCode: 'device-secret', + userCode: 'AB\u001b[2JCD', + verificationUri: 'https://cloud.example/authorize', + interval: 1, + }) + : jsonResponse({ + status: 'approved', + accessToken: 'adc_agent_login', + cliSession: { id: 'session-code', refreshCredential: 'adc_refresh_login' }, + }), + }, + }); + assert.equal(stderr, 'Opening https://cloud.example/authorize...\n'); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + 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 = { @@ -261,6 +553,8 @@ test('device login opens browser, stores CLI session, and returns agent token', flags: baseFlags, env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example' }, io: { + // Pinned before the approved token's expiry: past it, the login exchanges that token. + now: () => Date.parse('2026-02-01T00:00:00.000Z'), stdinIsTTY: true, stdoutIsTTY: true, stderr: { @@ -305,7 +599,7 @@ test('device login opens browser, stores CLI session, and returns agent token', assert.equal(login.accessToken, 'adc_agent_login'); assert.deepEqual(opened, ['https://cloud.example/device?user_code=ABCD-EFGH']); assert.match(stderr, /Opening https:\/\/cloud\.example\/authorize/); - assert.doesNotMatch(stderr, /ABCD-EFGH/); + assert.match(stderr, /Confirm that the browser shows this code: ABCD-EFGH\n/); assert.deepEqual(requests, [ 'https://cloud.example/api/control-plane/device-auth/start', 'https://cloud.example/api/control-plane/device-auth/poll', @@ -324,7 +618,7 @@ test('device login opens browser, stores CLI session, and returns agent token', fs.rmSync(tempRoot, { recursive: true, force: true }); }); -test('auth summary and logout do not expose stored refresh credentials', () => { +test('auth summary and logout do not expose stored refresh credentials', async () => { const tempRoot = mkdtempForTestSync('agent-device-auth-summary-'); writeCliSession({ stateDir: tempRoot, @@ -340,7 +634,7 @@ test('auth summary and logout do not expose stored refresh credentials', () => { const status = summarizeCliSession({ stateDir: tempRoot }); assert.equal(status.authenticated, true); assert.equal(JSON.stringify(status).includes('adc_refresh_hidden'), false); - assert.equal(removeCliSession({ stateDir: tempRoot }), true); + assert.equal(await removeCliSession({ stateDir: tempRoot }), true); assert.equal(summarizeCliSession({ stateDir: tempRoot }).authenticated, false); fs.rmSync(tempRoot, { recursive: true, force: true }); }); diff --git a/src/cli/__tests__/cloud-response.test.ts b/src/cli/__tests__/cloud-response.test.ts index b1990f81c0..9dc572e862 100644 --- a/src/cli/__tests__/cloud-response.test.ts +++ b/src/cli/__tests__/cloud-response.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; -import { normalizeError } from '@agent-device/kernel/errors'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { readCloudJsonResponse } from '../cloud-response.ts'; const options = { invalidJsonMessage: 'Invalid JSON', rejectedMessage: 'Cloud request rejected' }; @@ -61,3 +61,47 @@ test('malformed successful JSON never exposes response text through its cause', }, ); }); + +/** + * A caller's own marker outranks the generic status rejection, because the status of a body the + * reader understood is not yet the last word about the request. A body that is not JSON is read as + * one that carries no marker, and the status still refuses the request. + */ +test('a rejected response is offered to the classifier before its status is rejected', async () => { + const ownFailure = () => new AppError('UNAUTHORIZED', 'Own refusal.'); + const withClassifier = { ...options, classifyRejectedBody: ownFailure }; + + await assert.rejects( + readCloudJsonResponse( + new Response(JSON.stringify({ status: 'revoked' }), { status: 401 }), + withClassifier, + ), + (error: unknown) => { + const normalized = normalizeError(error); + assert.equal(normalized.message, 'Own refusal.'); + assert.equal(normalized.details?.status, undefined); + return true; + }, + ); + + // The classifier saw the body and did not claim it, so the generic refusal stands, and a body that + // is not JSON still cannot break that path. + let seen: unknown = 'not called'; + await assert.rejects( + readCloudJsonResponse(new Response('secret', { status: 503 }), { + ...options, + classifyRejectedBody: (parsed) => { + seen = parsed; + return undefined; + }, + }), + (error: unknown) => { + const normalized = normalizeError(error); + assert.equal(normalized.details?.status, 503); + assert.equal(normalized.retriable, true); + assert.deepEqual(seen, {}); + assert.doesNotMatch(JSON.stringify(normalized), /secret/); + return true; + }, + ); +}); diff --git a/src/cli/auth-session.ts b/src/cli/auth-session.ts index 3ba76c43d0..988f391131 100644 --- a/src/cli/auth-session.ts +++ b/src/cli/auth-session.ts @@ -1,7 +1,8 @@ import fs from 'node:fs'; import path from 'node:path'; -import { publishFileSync } from '@agent-device/host-kit/file'; -import { AppError } from '@agent-device/kernel/errors'; +import { acquireProcessLock, publishFileSync } from '@agent-device/host-kit/file'; +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'; @@ -15,6 +16,23 @@ 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 +// at most two request timeouts; an approved login holds it across its save and that exchange. A +// dead holder is reclaimed, so only a stuck live process makes a contender wait this long. +const CLI_SESSION_LOCK_TIMEOUT_MS = 60_000; +// A response whose access token is already expired is asked again, and no further: a cloud that +// keeps answering with an expired token must not keep a command refreshing. +const MAX_CLI_SESSION_TOKEN_EXCHANGES = 2; + +/** Every `details.reason` the CLI session store publishes. */ +const CLI_SESSION_REASONS = { + // The cloud answered a refresh by reporting the stored session revoked. + revoked: { reason: 'cli_session_revoked', commands: ['connect'] }, + // The refresh answered without an access token, so the CLI has nothing to send. + 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'] }, +} as const satisfies ReasonTable<'auth'>; export type CliSessionRecord = { version: 1; @@ -60,7 +78,14 @@ type DeviceAuthPollResponse = { type CliSessionRefreshResponse = { accessToken?: string; + /** A replacement for the stored credential, when the cloud rotates it on refresh. */ + refreshCredential?: string; + /** The access token's expiry. Not the session's: read `cliSession.expiresAt` for that. */ expiresAt?: string; + cliSession?: { + /** The session expiry, which a cloud may slide with use. */ + expiresAt?: string; + }; status?: string; error?: string; }; @@ -136,6 +161,8 @@ export async function resolveRemoteAuth(options: { flags: options.flags, env, io: options.io, + // The command sends this token itself, so a failed exchange is the command's failure. + requiresLiveToken: true, }); return { flags: { ...options.flags, daemonAuthToken: login.accessToken }, @@ -188,6 +215,8 @@ export async function resolveCloudAccessForConnect(options: { env, io: options.io, commandLabel: 'agent-device connect', + // `connect` sends this token itself, so a failed exchange is the command's failure. + requiresLiveToken: true, }); return { accessToken: login.accessToken, @@ -201,6 +230,9 @@ export async function loginWithDeviceAuth(options: { env: EnvMap; io?: AuthIo; commandLabel?: string; + // Whether the caller spends the returned access token itself. `connect` does, so a token exchange + // that fails is its failure. `auth login` only prints the session, so it keeps the approved pair. + requiresLiveToken?: boolean; }): Promise<{ accessToken: string; expiresAt?: string; @@ -230,7 +262,10 @@ export async function loginWithDeviceAuth(options: { ? start.verificationUriComplete : start.verificationUri; if (authMode === 'local-browser') { - writeStderr(options.io, `Opening ${start.verificationUri}...\n`); + writeStderr( + options.io, + `Opening ${start.verificationUri}...\n${describeUserCode(start.userCode)}`, + ); await openBrowser(verificationUrl, options.io); } else { const printableUrl = appendUserCode(start.verificationUri, start.userCode); @@ -254,6 +289,12 @@ export async function loginWithDeviceAuth(options: { throw new AppError('UNAUTHORIZED', 'Device authorization did not return CLI credentials.'); } const nowIso = new Date(options.io?.now?.() ?? Date.now()).toISOString(); + const approvedToken = approved.accessToken; + // Only a nonempty string counts as the approval's access-token expiry, so it is omitted for any + // other value: one would reach `Date.parse` as a foreign object, which throws there after the + // session is already saved. A string that cannot be read is kept: `isExpired` calls such a token + // 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, id: approved.cliSession?.id ?? `cli-${Date.now().toString(36)}`, @@ -265,12 +306,46 @@ export async function loginWithDeviceAuth(options: { createdAt: nowIso, expiresAt: approved.cliSession?.expiresAt, }; - writeCliSession({ stateDir: options.stateDir, session }); - return { - accessToken: approved.accessToken, - expiresAt: approved.expiresAt, - session, - }; + return await withCliSessionLock( + options.stateDir, + async (): Promise<{ accessToken: string; expiresAt?: string; session: CliSessionRecord }> => { + writeCliSession({ stateDir: options.stateDir, session }); + if (!isExpired(approvedExpiresAt, options.io?.now)) + return { + accessToken: approvedToken, + ...(hasToken(approvedExpiresAt) ? { expiresAt: approvedExpiresAt } : {}), + session, + }; + // The approval's access token already expired: its expiry says nothing about the login's + // answer, so the transient-failure path below reports the approved pair without one. + try { + // The exchange runs on the record just saved, under the same acquisition that saved it: + // another login cannot write between the two and have its credential exchanged here. + return await exchangeCliSessionAccess({ + stateDir: options.stateDir, + session, + flags: options.flags, + env, + io: options.io, + }); + } catch (error) { + // A session the cloud reported revoked is refused even to an explicit login. Every other + // failure is transient, and the approved session is already saved: a caller that spends the + // token itself needs the live one and propagates, while `auth login` only prints the session + // and succeeds. An exchange that stored anything returned rather than threw, so the record + // the file holds is still the approved one written above. + if (options.requiresLiveToken || isCliSessionRevoked(error)) throw error; + warnBestEffort( + options.io, + 'Warning: the saved CLI session could not be exchanged for a live access token. ' + + 'The next command will refresh it.\n', + ); + // The approved pair, without the expiry of a token whose exchange never answered. + return { accessToken: approvedToken, session }; + } + }, + { io: options.io, keepWaiting: true }, + ); } export function readCliSession(options: { stateDir: string }): CliSessionRecord | null { @@ -304,11 +379,112 @@ export function writeCliSession(options: { stateDir: string; session: CliSession }); } -export function removeCliSession(options: { stateDir: string }): boolean { +export async function removeCliSession(options: { stateDir: string }): Promise { const filePath = resolveCliSessionPath(options.stateDir); if (!fs.existsSync(filePath)) return false; - fs.rmSync(filePath, { force: true }); - return true; + return await withCliSessionLock(options.stateDir, () => { + if (!fs.existsSync(filePath)) return false; + fs.rmSync(filePath, { force: true }); + return true; + }); +} + +/** + * Serializes the changes to the session file: a login's write, a logout's removal, and the read, + * token exchange and write that store a rotated credential. Device approval polling stays outside. + * `keepWaiting` is for a change the cloud will not repeat — an approved login: a timed-out wait + * warns and waits again, and the change is never dropped. A read the cloud will answer again leaves + * it off, so a command fails with the lock's typed reason instead of queueing behind a stuck + * sibling. A change that took effect is reported as done even when the lock is not given back + * cleanly: that release failure is a warning, and the next contender reclaims the spent claim. + */ +async function withCliSessionLock( + stateDir: string, + task: () => Result | Promise, + options: { io?: AuthIo; keepWaiting?: boolean } = {}, +): Promise { + const sessionPath = resolveCliSessionPath(stateDir); + const release = await acquireCliSessionLock(sessionPath, options); + let result: Result; + try { + result = await task(); + } catch (error) { + await release().catch(() => undefined); + throw error; + } + await release().catch(() => { + warnBestEffort( + options.io, + 'Warning: the CLI session file lock could not be released cleanly.\n', + ); + }); + return result; +} + +/** + * Takes the session file lock, waiting as `keepWaiting` asks. The lock state is written beside the + * session file, so the auth directory must be writable: a refusal to write there is reported as a + * storage problem that names the directory, not as a filesystem error. + */ +async function acquireCliSessionLock( + sessionPath: string, + options: { io?: AuthIo; keepWaiting?: boolean }, +): Promise>> { + const { io } = options; + const authDir = path.dirname(sessionPath); + const owner = readCurrentOwnerIdentity(); + const acquire = () => + acquireProcessLock({ + lockDirPath: `${sessionPath}.lock`, + owner: { pid: owner.pid, startTime: owner.startTime, acquiredAtMs: Date.now() }, + timeoutMs: CLI_SESSION_LOCK_TIMEOUT_MS, + description: 'cloud CLI session file', + }); + let release: Awaited> | undefined; + while (!release) { + try { + fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); + release = await acquire(); + } catch (error) { + const fault = unwritableSessionStore(error, authDir); + if (fault) throw fault; + if (!options.keepWaiting || !isProcessLockTimeout(error)) throw error; + warnBestEffort( + io, + 'Waiting for another agent-device process to release the CLI session file...\n', + ); + } + } + return release; +} + +function isProcessLockTimeout(error: unknown): boolean { + return error instanceof AppError && error.details?.reason === 'process_lock_timeout'; +} + +/** + * The typed refusal for a filesystem fault that stops the store from writing, or `undefined` for + * every other error. The hint names the directory to repair, because that is the one step that ends + * it. + */ +function unwritableSessionStore(error: unknown, authDir: string): AppError | undefined { + const code = + typeof error === 'object' && error !== null && 'code' in error + ? String((error as { code?: unknown }).code) + : undefined; + if (code !== 'EACCES' && code !== 'EPERM' && code !== 'EROFS') return undefined; + const fix = `Run \`chmod 700 ${authDir}\`, or point AGENT_DEVICE_STATE_DIR at a private directory you own.`; + return new AppError( + 'COMMAND_FAILED', + `The CLI session store ${authDir} cannot be written.`, + { + reason: CLI_SESSION_REASONS.storeUnwritable.reason, + authDir, + fix, + hint: fix, + }, + error instanceof Error ? error : undefined, + ); } export function resolveCliSessionPath(stateDir: string): string { @@ -348,59 +524,234 @@ async function resolveCliSessionAccess(options: { flags: CliFlags; env: EnvMap; io?: AuthIo; -}): Promise<{ accessToken: string; cloudBaseUrl: string } | null> { - const session = readCliSession({ stateDir: options.stateDir }); - if (!session || isExpired(session.expiresAt, options.io?.now)) { - return null; +}): Promise<{ accessToken: string; expiresAt?: string; cloudBaseUrl: string } | null> { + 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 }); + 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 }); + if (!session || isExpired(session.expiresAt, io?.now)) return null; + return await exchangeCliSessionAccess({ stateDir, session, flags, env, io }); + }, + { io }, + ); + if (!exchanged) return null; + return { + accessToken: exchanged.accessToken, + ...(hasToken(exchanged.expiresAt) ? { expiresAt: exchanged.expiresAt } : {}), + cloudBaseUrl: resolveCloudBaseUrl(env, exchanged.session.cloudBaseUrl), + }; +} + +/** + * 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 + * changed in memory. When the cloud rotates the credential, the next exchange asks with the + * replacement even when storing it failed. The session file lock is held here, so the caller's write + * of the record it exchanges cannot be separated from this exchange. + */ +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; + // 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 + // the last record known saved, which is what the caller reports: a token the cloud accepted + // outranks a record the disk never took. + const file = { holds: options.session as CliSessionRecord | null }; + let asked = options.session; + // The last record known saved, which is what the caller reports: the record written before this + // exchange ran, or a newer one a rotation stored. A record a write only changed in memory is not + // it, so a login never prints an expiry the file does not hold. + let saved = options.session; + let received: { accessToken: string; expiresAt?: string } | undefined; + for (let exchange = 1; ; exchange += 1) { + let refreshed; + try { + refreshed = await refreshAgentToken({ session: asked, flags, env, 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 + // again keeps it, paired with the record as last stored. A confirmed revocation is never + // transient and always propagates. + if (!received || isCliSessionRevoked(error)) throw error; + return { ...received, session: saved }; + } + const rotation = readCredentialRotation(refreshed, asked.refreshCredential); + if (rotation) { + ({ asked, saved } = storeRotatedCredential({ + stateDir, + asked, + saved, + file, + rotation, + io, + })); + } + received = { + accessToken: refreshed.accessToken, + ...(hasToken(refreshed.expiresAt) ? { expiresAt: refreshed.expiresAt } : {}), + }; + if (!isExpired(refreshed.expiresAt, io?.now) || exchange >= MAX_CLI_SESSION_TOKEN_EXCHANGES) { + return { ...received, session: saved }; + } } - const refreshed = await refreshAgentToken({ - session, - flags: options.flags, - env: options.env, - io: options.io, - }); +} + +/** + * Reads the credential rotation a refresh response asks for, or `null` when it carries none. A + * session expiry in the response is part of the rotation: a cloud whose session expiry slides with + * use tells the CLI so here. The response's own `expiresAt` is the access token's expiry, not this. + */ +function readCredentialRotation( + refreshed: { refreshCredential?: string; sessionExpiresAt?: string }, + sentCredential: string, +): { refreshCredential: string; expiresAt?: string } | null { + const refreshCredential = refreshed.refreshCredential; + if (!hasToken(refreshCredential) || refreshCredential === sentCredential) return null; + // A timestamp that cannot be read would make `isExpired` call the session expired, so one bad + // response would lock the CLI out of a working session. It is kept out of the record. + const readable = (value: string) => Number.isFinite(Date.parse(value)); return { - accessToken: refreshed.accessToken, - cloudBaseUrl: resolveCloudBaseUrl(options.env, session.cloudBaseUrl), + refreshCredential, + ...(hasToken(refreshed.sessionExpiresAt) && readable(refreshed.sessionExpiresAt) + ? { expiresAt: refreshed.sessionExpiresAt } + : {}), }; } +/** + * Stores the credential that replaced the one this command asked with, and answers with the record + * the next exchange asks with, together with the last record known saved. Only a record this + * function wrote counts as saved: a rotation the disk refused is asked with again and never + * reported, so a command cannot print an expiry the file does not hold. The session file lock is held + * here, and the file is read again first: a change visible on that read (another command's store, a + * login, a logout) wins, the file is no longer this command's to write, and nothing is written. A + * failed write keeps the command's access token and warns, because the cloud refuses the old + * credential after its grace period. + */ +function storeRotatedCredential(options: { + stateDir: string; + asked: CliSessionRecord; + saved: CliSessionRecord; + file: { holds: CliSessionRecord | null }; + rotation: { refreshCredential: string; expiresAt?: string }; + io?: AuthIo; +}): { asked: CliSessionRecord; saved: CliSessionRecord } { + const { asked, saved, file, rotation } = options; + const held = file.holds; + try { + const stored = readCliSession({ stateDir: options.stateDir }); + if (held && stored?.id === held.id && stored.refreshCredential === held.refreshCredential) { + const replaced: CliSessionRecord = { ...stored, ...rotation }; + writeCliSession({ stateDir: options.stateDir, session: replaced }); + file.holds = replaced; + return { asked: replaced, saved: replaced }; + } + } catch { + warnBestEffort( + options.io, + 'Warning: the renewed CLI session could not be saved. ' + + 'If the next command is not authenticated, run agent-device auth login.\n', + ); + // The file is still the record this command read, and the save of the next rotation is compared + // to it, so a later save is tried again rather than skipped. + return { asked: { ...asked, ...rotation }, saved }; + } + // A session this command did not write: keep asking with what the cloud last gave. + file.holds = null; + return { asked: { ...asked, ...rotation }, saved }; +} + async function refreshAgentToken(options: { session: CliSessionRecord; flags: CliFlags; env: EnvMap; io?: AuthIo; -}): Promise<{ accessToken: string; expiresAt?: string }> { +}): Promise<{ + accessToken: string; + expiresAt?: string; + refreshCredential?: string; + sessionExpiresAt?: string; +}> { const cloudBaseUrl = resolveCloudBaseUrl(options.env, options.session.cloudBaseUrl); const response = await postJson({ baseUrl: cloudBaseUrl, pathName: CLI_SESSION_REFRESH_PATH, body: { refreshCredential: options.session.refreshCredential, + // This CLI stores a replacement credential from the response, so the cloud may rotate it. + // Commands run in parallel and each refreshes, so a cloud that rotates must: issue at most + // one replacement for a credential; answer a request that still presents the replaced + // credential with an access token and no further replacement; and keep the replaced + // credential valid for a grace period that covers commands already in flight. + acceptsRotatedRefreshCredential: true, tenant: options.flags.tenant, runId: options.flags.runId, daemonBaseUrl: options.flags.daemonBaseUrl, session: options.flags.session, }, fetchImpl: options.io?.fetch, + classifyRejectedBody: (parsed) => readCliSessionRevocation(parsed), }); + // Revocation is answered before the tokens: a response that reports it is refused even when it + // also carries credentials. The refusal names only its own reason: `status` and `error` are + // response-supplied text and can echo a credential back into the command's output. + const revoked = readCliSessionRevocation(response); + if (revoked) throw revoked; if (hasToken(response.accessToken)) { - return { accessToken: response.accessToken, expiresAt: response.expiresAt }; - } - if (response.status === 'revoked' || response.error === 'revoked') { - throw new AppError('UNAUTHORIZED', 'Stored cloud CLI session was revoked.', { - hint: 'Run agent-device auth login again, or set AGENT_DEVICE_DAEMON_AUTH_TOKEN.', - status: response.status, - error: response.error, - }); + return { + accessToken: response.accessToken, + expiresAt: response.expiresAt, + ...(hasToken(response.refreshCredential) + ? { refreshCredential: response.refreshCredential } + : {}), + ...(hasToken(response.cliSession?.expiresAt) + ? { sessionExpiresAt: response.cliSession.expiresAt } + : {}), + }; } + // The cloud refused to answer without reporting the session revoked, so this CLI has no token to + // send and no proof the session is gone: `auth login` keeps the session it saved, and a caller + // that spends a token itself reports this one reason. throw new AppError('UNAUTHORIZED', 'Failed to refresh CLI session.', { hint: 'Run agent-device auth login again, or set AGENT_DEVICE_DAEMON_AUTH_TOKEN.', - status: response.status, - error: response.error, + reason: CLI_SESSION_REASONS.tokenless.reason, }); } +/** + * This CLI's refusal for a refresh response that reports the session revoked, or `undefined` for one + * that carries neither revocation marker. Only the exact `revoked` marker counts, so any other + * `status` or `error` stays whatever the generic HTTP handling makes of the response. The response's + * own text is never copied: a hostile value under those keys can echo a credential into output. + */ +function readCliSessionRevocation(parsed: unknown): AppError | undefined { + if (typeof parsed !== 'object' || parsed === null) return undefined; + const { status, error } = parsed as { status?: unknown; error?: unknown }; + if (status !== 'revoked' && error !== 'revoked') return undefined; + return new AppError('UNAUTHORIZED', 'Stored cloud CLI session was revoked.', { + hint: 'Run agent-device auth login again, or set AGENT_DEVICE_DAEMON_AUTH_TOKEN.', + reason: CLI_SESSION_REASONS.revoked.reason, + }); +} + +/** Whether a failure is this module's refusal of a session the cloud will not refresh again. */ +function isCliSessionRevoked(error: unknown): boolean { + return error instanceof AppError && error.details?.reason === CLI_SESSION_REASONS.revoked.reason; +} + async function pollDeviceAuth(options: { cloudBaseUrl: string; deviceCode: string; @@ -449,6 +800,8 @@ async function postJson(options: { // 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), { @@ -460,6 +813,7 @@ async function postJson(options: { return await readCloudJsonResponse(response, { invalidJsonMessage: `Cloud auth endpoint returned invalid JSON (${response.status}).`, rejectedMessage: 'Cloud auth endpoint rejected the request.', + classifyRejectedBody: options.classifyRejectedBody, }); } @@ -564,6 +918,16 @@ function shouldUseCloudAuth(daemonBaseUrl: string, env: EnvMap): boolean { } } +/** + * The line that lets the user compare the code in the browser with the terminal. A code with + * characters outside letters, digits and dashes is not printed. + */ +function describeUserCode(userCode: string): string { + return /^[A-Za-z0-9-]{4,32}$/.test(userCode) + ? `Confirm that the browser shows this code: ${userCode}\n` + : ''; +} + function appendUserCode(verificationUri: string, userCode: string): string { const url = new URL(verificationUri); url.searchParams.set('user_code', userCode); @@ -581,6 +945,28 @@ async function openBrowser(url: string, io?: AuthIo): Promise { } } +/** Streams that already carry the listener that absorbs a late write error. */ +const errorAbsorbingStreams = new WeakSet(); + +/** + * Writes a warning that must not change the result of a change that already took effect. A + * closed stderr fails the write synchronously, or later with an EPIPE `error` event; both are + * dropped. Each stream gets one absorbing listener, because the event fires after the write callback. + */ +function warnBestEffort(io: AuthIo | undefined, text: string): void { + const stream = io?.stderr ?? process.stderr; + const emitter = stream as Partial; + if (emitter.on && !errorAbsorbingStreams.has(stream)) { + emitter.on('error', () => {}); + errorAbsorbingStreams.add(stream); + } + try { + stream.write(text); + } catch { + // A warning is optional output. + } +} + function writeStderr(io: AuthIo | undefined, text: string): void { (io?.stderr ?? process.stderr).write(text); } diff --git a/src/cli/cloud-response.ts b/src/cli/cloud-response.ts index 6e6bb62a2d..c65104340b 100644 --- a/src/cli/cloud-response.ts +++ b/src/cli/cloud-response.ts @@ -5,11 +5,29 @@ export async function readCloudJsonResponse( options: { invalidJsonMessage: string; rejectedMessage: string; + // Reads a caller's own markers out of a response that is not JSON and answers with its own + // failure. A rejected HTTP status means nothing until this has run, so a marker the caller + // classifies outranks the generic status rejection. + classifyRejectedBody?: (parsed: unknown) => AppError | undefined; }, ): Promise { const text = await response.text(); + const status = response.status; + let parsed: unknown = {}; + if (text.trim().length > 0) { + try { + parsed = JSON.parse(text); + } catch { + // Only a body that cannot be read can hold a marker, so a body that is not JSON is read as one + // that carries none, and the status below still refuses the request. + if (response.ok) throw new AppError('COMMAND_FAILED', options.invalidJsonMessage, { status }); + } + } if (!response.ok) { - const status = response.status; + // A marker the caller recognizes is its answer to this request, so it is read before the status + // is rejected generically. The failure it raises is the caller's own: no body text is copied. + const classified = options.classifyRejectedBody?.(parsed); + if (classified) throw classified; const code = status === 401 || status === 403 ? 'UNAUTHORIZED' : 'COMMAND_FAILED'; throw new AppError(code, options.rejectedMessage, { status, @@ -18,13 +36,5 @@ export async function readCloudJsonResponse( : {}), }); } - let parsed: unknown = {}; - if (text.trim().length > 0) { - try { - parsed = JSON.parse(text); - } catch { - throw new AppError('COMMAND_FAILED', options.invalidJsonMessage, { status: response.status }); - } - } return parsed as T; } diff --git a/src/cli/commands/__tests__/auth.test.ts b/src/cli/commands/__tests__/auth.test.ts index 4ea5103835..59424801b1 100644 --- a/src/cli/commands/__tests__/auth.test.ts +++ b/src/cli/commands/__tests__/auth.test.ts @@ -10,6 +10,13 @@ afterEach(() => { vi.unstubAllGlobals(); }); +function jsonResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); +} + function writeStoredCliSession( stateDir: string, overrides: Partial[0]['session']> = {}, @@ -91,21 +98,20 @@ test('auth login completes a device-code flow and stores the CLI session', async { status: 200, headers: { 'content-type': 'application/json' } }, ); } - return new Response( - JSON.stringify({ - status: 'approved', - accessToken: 'access-token-1', - expiresAt: '2026-02-01T00:00:00.000Z', - cliSession: { - id: 'cli-7', - refreshCredential: 'refresh-credential-7', - workspaceId: 'ws-7', - accountId: 'acct-7', - expiresAt: '2026-06-01T00:00:00.000Z', - }, - }), - { status: 200, headers: { 'content-type': 'application/json' } }, - ); + return jsonResponse({ + status: 'approved', + accessToken: 'access-token-1', + // Both far future: a login whose approved token is still live asks for nothing, so start + // and poll are the only calls. + expiresAt: '2099-01-01T00:00:00.000Z', + cliSession: { + id: 'cli-7', + refreshCredential: 'refresh-credential-7', + workspaceId: 'ws-7', + accountId: 'acct-7', + expiresAt: '2099-06-01T00:00:00.000Z', + }, + }); }), ); @@ -144,6 +150,175 @@ test('auth login completes a device-code flow and stores the CLI session', async } }); +test('auth login exchanges an approved access token that already expired for a live one', async () => { + const stateDir = mkdtempForTestSync('agent-device-auth-login-expired-token-'); + const requestUrls: string[] = []; + let sentCredential: unknown; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: URL | RequestInfo, init?: RequestInit) => { + const url = new URL(String(input)); + requestUrls.push(url.pathname); + if (url.pathname === '/api/control-plane/cli-session/refresh') { + sentCredential = JSON.parse(String(init?.body)).refreshCredential; + // No token expiry, so a login that reported one here would be reporting the expired + // approval's. The session expiry it slides is a third date. + return jsonResponse({ + accessToken: 'access-token-live', + refreshCredential: 'refresh-credential-9', + cliSession: { expiresAt: '2099-12-24T00:00:00.000Z' }, + }); + } + if (url.pathname === '/api/control-plane/device-auth/start') { + return jsonResponse({ + deviceCode: 'device-code-1', + userCode: 'ABCD-1234', + verificationUri: 'https://cloud.example.test/login', + interval: 1, + }); + } + return jsonResponse({ + status: 'approved', + accessToken: 'access-token-expired', + // Past, against any clock this run happens on: the token the login must not hand back. + expiresAt: '2001-01-01T00:00:00.000Z', + cliSession: { + id: 'cli-8', + refreshCredential: 'refresh-credential-8', + // Far future: the saved session stays usable, which is what lets the exchange run. + expiresAt: '2099-01-01T00:00:00.000Z', + }, + }); + }), + ); + + const previousStdinIsTTY = process.stdin.isTTY; + const previousStdoutIsTTY = process.stdout.isTTY; + (process.stdin as { isTTY?: boolean }).isTTY = true; + (process.stdout as { isTTY?: boolean }).isTTY = true; + try { + const result = await runCliCapture(['auth', 'login', '--state-dir', stateDir, '--json'], { + env: { + AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example.test', + SSH_CONNECTION: '10.0.0.1 50000 10.0.0.2 22', + CI: undefined, + GITHUB_ACTIONS: undefined, + BUILDKITE: undefined, + }, + }); + + assert.equal(result.code, null); + const data = JSON.parse(result.stdout).data as { + agentTokenExpiresAt?: string; + expiresAt?: string; + sessionId?: string; + }; + // The exchange answered without a token expiry, so none is reported: the expired approval's is + // not reused for a token that is not expired. + assert.equal(data.agentTokenExpiresAt, undefined); + // The session reported is the record the exchange left in the file, expiry and all. + assert.equal(data.expiresAt, '2099-12-24T00:00:00.000Z'); + assert.equal(data.sessionId, 'cli-8'); + assert.deepEqual(requestUrls, [ + '/api/control-plane/device-auth/start', + '/api/control-plane/device-auth/poll', + '/api/control-plane/cli-session/refresh', + ]); + assert.equal(sentCredential, 'refresh-credential-8'); + const stored = JSON.parse( + fs.readFileSync(path.join(stateDir, 'auth', 'cli-session.json'), 'utf8'), + ) as { expiresAt?: string; refreshCredential?: string }; + assert.equal(stored.refreshCredential, 'refresh-credential-9'); + assert.equal(stored.expiresAt, '2099-12-24T00:00:00.000Z'); + } finally { + (process.stdin as { isTTY?: boolean }).isTTY = previousStdinIsTTY; + (process.stdout as { isTTY?: boolean }).isTTY = previousStdoutIsTTY; + } +}); + +/** + * The approved session is saved before its already-expired access token is exchanged, so a refresh + * that fails transiently cannot take the login back: the command prints the session, and the next + * command refreshes it. + */ +test('auth login succeeds when the exchange of its expired approval token gets 503', async () => { + const stateDir = mkdtempForTestSync('agent-device-auth-login-503-'); + const requestPaths: string[] = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: URL | RequestInfo) => { + const url = new URL(String(input)); + requestPaths.push(url.pathname); + if (url.pathname === '/api/control-plane/device-auth/start') { + return jsonResponse({ + deviceCode: 'device-code-1', + userCode: 'ABCD-1234', + verificationUri: 'https://cloud.example.test/login', + interval: 1, + }); + } + if (url.pathname === '/api/control-plane/device-auth/poll') { + return jsonResponse({ + status: 'approved', + accessToken: 'access-token-expired', + // Past on any clock this run happens on, so the login has to exchange this token. + expiresAt: '2001-01-01T00:00:00.000Z', + cliSession: { + id: 'cli-9', + refreshCredential: 'refresh-credential-9', + expiresAt: '2099-01-01T00:00:00.000Z', + }, + }); + } + return new Response('unavailable', { status: 503 }); + }), + ); + + const previousStdinIsTTY = process.stdin.isTTY; + const previousStdoutIsTTY = process.stdout.isTTY; + (process.stdin as { isTTY?: boolean }).isTTY = true; + (process.stdout as { isTTY?: boolean }).isTTY = true; + try { + const result = await runCliCapture(['auth', 'login', '--state-dir', stateDir, '--json'], { + env: { + AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example.test', + SSH_CONNECTION: '10.0.0.1 50000 10.0.0.2 22', + CI: undefined, + GITHUB_ACTIONS: undefined, + BUILDKITE: undefined, + }, + }); + + assert.equal(result.code, null); + const data = JSON.parse(result.stdout).data as { + authenticated?: boolean; + sessionId?: string; + expiresAt?: string; + agentTokenExpiresAt?: string; + }; + assert.equal(data.authenticated, true); + assert.equal(data.sessionId, 'cli-9'); + assert.equal(data.expiresAt, '2099-01-01T00:00:00.000Z'); + // The exchange never answered, so no token expiry is reported. + assert.equal(data.agentTokenExpiresAt, undefined); + assert.match(result.stderr, /could not be exchanged for a live access token/); + assert.deepEqual(requestPaths, [ + '/api/control-plane/device-auth/start', + '/api/control-plane/device-auth/poll', + '/api/control-plane/cli-session/refresh', + ]); + // The session the login saved is what `auth status` will show. + const stored = JSON.parse( + fs.readFileSync(path.join(stateDir, 'auth', 'cli-session.json'), 'utf8'), + ) as { id?: string; refreshCredential?: string }; + assert.equal(stored.id, 'cli-9'); + assert.equal(stored.refreshCredential, 'refresh-credential-9'); + } finally { + (process.stdin as { isTTY?: boolean }).isTTY = previousStdinIsTTY; + (process.stdout as { isTTY?: boolean }).isTTY = previousStdoutIsTTY; + } +}); + test('auth logout removes a stored session and reports it', async () => { const stateDir = mkdtempForTestSync('agent-device-auth-logout-removed-'); writeStoredCliSession(stateDir); diff --git a/src/cli/commands/auth.ts b/src/cli/commands/auth.ts index 797f127335..2e5774816d 100644 --- a/src/cli/commands/auth.ts +++ b/src/cli/commands/auth.ts @@ -36,7 +36,7 @@ export const authCommand: ClientCommandHandler = async ({ positionals, flags, ho return true; } if (subcommand === 'logout') { - const removed = removeCliSession({ stateDir }); + const removed = await removeCliSession({ stateDir }); await writeCommandOutput(flags, { authenticated: false, removed }, () => removed ? 'Removed stored cloud CLI session.' : 'No stored cloud CLI session.', ); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index aa98a01ae1..209017416b 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2516,7 +2516,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`. +- 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`. - `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 20cc7127d6..5045333108 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -18,6 +18,14 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `native_audit_blocked_by_alert` | Apple's audit failed while a system alert covered the app; answer the alert, then retry. | | `native-audit-invalid-result` | The runner answered the native audit with a missing or malformed result. | +### `auth` + +| Reason | Meaning | +| --- | --- | +| `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. | + ### `back` | Reason | Meaning | @@ -46,6 +54,9 @@ Treat a reason that this page does not list as unknown, not as an error in the r | Reason | Meaning | | --- | --- | +| `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. | | `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. |