From 13962000984feb2e796e1536c697cf8981f1f8e2 Mon Sep 17 00:00:00 2001 From: Suneeth12 Date: Sun, 6 Dec 2026 01:52:32 +0530 Subject: [PATCH 1/6] fix(cli): sweep expired stale-login and unbound bookings locally --- .../cli-cloud-session-identity.test.ts | 186 ++++++++++++++++++ src/cli/connection/active-connection.ts | 8 +- src/cli/connection/cloud-access.ts | 40 +++- .../cloud-connection-record.test.ts | 21 +- src/cli/connection/cloud-connection-record.ts | 13 +- 5 files changed, 253 insertions(+), 15 deletions(-) diff --git a/src/__tests__/cli-cloud-session-identity.test.ts b/src/__tests__/cli-cloud-session-identity.test.ts index 8242922c8c..9301803c82 100644 --- a/src/__tests__/cli-cloud-session-identity.test.ts +++ b/src/__tests__/cli-cloud-session-identity.test.ts @@ -666,3 +666,189 @@ test("a direct profile that redirects to another state directory checks identity expect(result.calls).toEqual([]); expect(readCloudConnection(location)?.id).toBe(hostedDevice.id); }); + +test.each(sessions)( + 'a stale v1 login sweeps expired proxy-front files of session %s locally without using saved credentials', + async (session) => { + const { env, front, location } = await bookProxyFront(session); + expire(location); + const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth'); + fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(authDir, 'cli-session.json'), + JSON.stringify({ + version: 1, + id: 'stale-login', + cloudBaseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL, + refreshCredential: 'stale-refresh-credential', + createdAt: new Date().toISOString(), + }), + { mode: 0o600 }, + ); + const staleEnv: Env = { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }; + + const result = await runCliCapture(['connection', 'status', '--session', session, '--json'], { + env: staleEnv, + sendToDaemon: front, + }); + expect(JSON.parse(result.stdout).error.details.reason).toBe( + 'cloud_connection_credential_mismatch', + ); + expect(result.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + }, +); + +test.each(sessions)( + 'a malformed saved login sweeps expired proxy-front files of session %s locally without using saved credentials', + async (session) => { + const { env, front, location } = await bookProxyFront(session); + expire(location); + const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth'); + fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync(path.join(authDir, 'cli-session.json'), '{', { mode: 0o600 }); + const unreadableEnv: Env = { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }; + + const result = await runCliCapture(['connection', 'status', '--session', session, '--json'], { + env: unreadableEnv, + sendToDaemon: front, + }); + expect(JSON.parse(result.stdout).error.details.reason).toBe( + 'cloud_connection_credential_mismatch', + ); + expect(result.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + }, +); + +test.skipIf(process.platform === 'win32')( + 'an unreadable saved login sweeps expired proxy-front files locally without using saved credentials', + async () => { + const { env, front, location } = await bookProxyFront('cloud-qa'); + expire(location); + const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth'); + const sessionFile = path.join(authDir, 'cli-session.json'); + fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync(sessionFile, '{"version":2}', { mode: 0o600 }); + fs.chmodSync(sessionFile, 0o000); + try { + const result = await runCliCapture( + ['connection', 'status', '--session', 'cloud-qa', '--json'], + { + env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }, + sendToDaemon: front, + }, + ); + expect(JSON.parse(result.stdout).error.details.reason).toBe( + 'cloud_connection_credential_mismatch', + ); + expect(result.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + } finally { + fs.chmodSync(sessionFile, 0o600); + } + }, +); + +test('forget with a stale v1 login clears a bound booking locally without saved credentials and refuses with no identity source', async () => { + const { env, front, location } = await bookProxyFront('cloud-qa'); + const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth'); + fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(authDir, 'cli-session.json'), + JSON.stringify({ + version: 1, + id: 'stale-login', + cloudBaseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL, + refreshCredential: 'stale-refresh-credential', + createdAt: new Date().toISOString(), + }), + { mode: 0o600 }, + ); + const staleEnv: Env = { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }; + + const forgotten = await runCliCapture( + ['disconnect', '--forget', '--session', 'cloud-qa', '--json'], + { env: staleEnv, sendToDaemon: front }, + ); + expect(forgotten.code, forgotten.stdout).toBeNull(); + expect(JSON.parse(forgotten.stdout).data).toMatchObject({ forgotten: true }); + expect(forgotten.calls).toEqual([]); + expect(readCloudConnection(location)).toBeNull(); + + const second = await book('cloud-qa', 'api-key'); + removeRemoteConnectionState(second.location); + const secondAuthDir = path.join(second.env.AGENT_DEVICE_STATE_DIR, 'auth'); + fs.mkdirSync(secondAuthDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(secondAuthDir, 'cli-session.json'), + JSON.stringify({ + version: 1, + id: 'stale-login', + cloudBaseUrl: second.env.AGENT_DEVICE_CLOUD_BASE_URL, + refreshCredential: 'stale-refresh-credential', + createdAt: new Date().toISOString(), + }), + { mode: 0o600 }, + ); + fs.writeFileSync(path.join(cloudConnectionDir(second.location), 'record.json'), '{'); + const refused = await runCliCapture( + ['disconnect', '--forget', '--session', 'cloud-qa', '--json'], + { env: { ...second.env, AGENT_DEVICE_CLOUD_API_KEY: undefined } }, + ); + expect(JSON.parse(refused.stdout).error.details.reason).toBe( + 'cloud_connection_credential_mismatch', + ); +}); + +test.each(sessions)( + 'the sweep clears an expired pending booking of session %s that has no account binding', + async (session) => { + const { env, front, location } = await bookProxyFront(session); + const { accountBinding: _unbound, ...record } = readCloudConnection(location)!; + removeRemoteConnectionState(location); + writeCloudConnection(location, { + ...record, + phase: 'pending', + deadlineAt: new Date(Date.now() - 1000).toISOString(), + }); + + const result = await runCliCapture(['connection', 'status', '--json'], { + env, + sendToDaemon: front, + }); + expect(result.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + }, +); + +test.each(sessions)( + 'the sweep clears an expired unbound proxy-front booking of session %s without sending saved credentials', + async (session) => { + const { env, front, location } = await bookProxyFront(session); + const { accountBinding: _unbound, ...record } = readCloudConnection(location)!; + writeCloudConnection(location, { + ...record, + deadlineAt: new Date(Date.now() - 1000).toISOString(), + }); + + const foreignOrigin: Env = { + ...env, + AGENT_DEVICE_CLOUD_BASE_URL: 'https://other-cloud.example', + AGENT_DEVICE_CLOUD_API_KEY_ORIGIN: 'https://other-cloud.example', + }; + const refused = await runCliCapture(['connection', 'status', '--json'], { + env: foreignOrigin, + sendToDaemon: front, + }); + expect(refused.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(true); + + const swept = await runCliCapture(['connection', 'status', '--json'], { + env, + sendToDaemon: front, + }); + expect(swept.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + }, +); diff --git a/src/cli/connection/active-connection.ts b/src/cli/connection/active-connection.ts index 7b01dc09b5..29229fd6eb 100644 --- a/src/cli/connection/active-connection.ts +++ b/src/cli/connection/active-connection.ts @@ -8,6 +8,7 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { type CloudConnectionRecord, type ConnectionLocation, + type ExpiredBookingAdmission, type ProxyFrontAttachment, CLOUD_CONNECTION_REASONS, cleanExpiredCloudAttachments, @@ -112,12 +113,11 @@ function admitsExpiredBooking( stateDir: string, env: HostEnvironment['env'], record: CloudConnectionRecord, -): boolean { +): ExpiredBookingAdmission | null { try { - admitHostedCaller({ stateDir, env, booking: record }, 'use'); - return true; + return admitHostedCaller({ stateDir, env, booking: record }, 'clear'); } catch { - return false; + return null; } } diff --git a/src/cli/connection/cloud-access.ts b/src/cli/connection/cloud-access.ts index 4d8e4855ef..3a14ef8ed5 100644 --- a/src/cli/connection/cloud-access.ts +++ b/src/cli/connection/cloud-access.ts @@ -1,4 +1,5 @@ import { createHash } from 'node:crypto'; +import { lstatIfPresent } from '@agent-device/host-kit/file'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { EnvMap } from '@agent-device/kernel/source-value'; import { @@ -7,6 +8,7 @@ import { loginWithDeviceAuth, readStoredCliSession, resolveCliSessionAccess, + resolveCliSessionPath, } from '../auth-session.ts'; import type { CloudSessionBinding } from '@agent-device/remote/remote-connection-state'; import { containsCloudCredential } from '../cloud-response.ts'; @@ -100,8 +102,8 @@ export function readCloudCaller( env: EnvMap, savedOrigin: string, ): CloudCallerIdentity | undefined { - if (!presentsCloudCredential(stateDir, env)) return undefined; - return readCallerIdentity(env, savedOrigin, readStoredCliSession(stateDir)); + const caller = readCloudCallerForPurpose(stateDir, env, savedOrigin, 'use'); + return caller === 'unverified' ? undefined : caller; } /** @@ -133,7 +135,8 @@ export function admitHostedCaller( if (purpose === 'use' || presentsCloudCredential(stateDir, env)) throw credentialMismatch(); return { mayUseSavedCredentials: false }; } - const caller = readCloudCaller(stateDir, env, booking.origin); + const caller = readCloudCallerForPurpose(stateDir, env, booking.origin, purpose); + if (caller === 'unverified') return { mayUseSavedCredentials: false }; if (caller) assertCloudConnectionCaller(booking, caller); const verifiable = booking.accountBinding !== undefined; if (purpose === 'use' && !verifiable) throw credentialMismatch(); @@ -156,19 +159,41 @@ export function admitPairedHostedCaller( admitHostedCaller({ stateDir: location.stateDir, env, booking: record }, 'use'); } +function readStoredLogin(stateDir: string): ReturnType { + const stored = readStoredCliSession(stateDir); + if (stored !== null) return stored; + try { + return lstatIfPresent(resolveCliSessionPath(stateDir)) ? 'unverified' : null; + } catch { + return 'unverified'; + } +} + function presentsCloudCredential(stateDir: string, env: EnvMap): boolean { - return Boolean(env.AGENT_DEVICE_CLOUD_API_KEY?.trim() || readStoredCliSession(stateDir)); + return Boolean(env.AGENT_DEVICE_CLOUD_API_KEY?.trim() || readStoredLogin(stateDir)); } function credentialMismatch() { return cloudConnectionUnavailable(CLOUD_CONNECTION_REASONS.credentialMismatch.reason); } +function readCloudCallerForPurpose( + stateDir: string, + env: EnvMap, + savedOrigin: string, + purpose: HostedCallerPurpose, +): CloudCallerIdentity | 'unverified' | undefined { + const login = readStoredLogin(stateDir); + if (!env.AGENT_DEVICE_CLOUD_API_KEY?.trim() && !login) return undefined; + return readCallerIdentity(env, savedOrigin, login, purpose === 'clear'); +} + function readCallerIdentity( env: EnvMap, savedOrigin: string, login: ReturnType, -): CloudCallerIdentity { + allowUnverified: boolean, +): CloudCallerIdentity | 'unverified' { // Another configured origin or key origin is another identity, not a malformed request. let cloudBaseUrl: string; let key: string | undefined; @@ -186,7 +211,10 @@ function readCallerIdentity( } if (key) return { cloudBaseUrl, accountBinding: identityDigest('api-key', key) }; // A login file that does not establish its issuer establishes no account either. - if (!login || login === 'unverified') throw credentialMismatch(); + if (!login || login === 'unverified') { + if (allowUnverified) return 'unverified'; + throw credentialMismatch(); + } return { cloudBaseUrl: URL.parse(login.cloudBaseUrl)?.origin ?? login.cloudBaseUrl, accountBinding: hostedLoginBinding(login.accountId, login.id), diff --git a/src/cli/connection/cloud-connection-record.test.ts b/src/cli/connection/cloud-connection-record.test.ts index 9db897e74e..9049f48353 100644 --- a/src/cli/connection/cloud-connection-record.test.ts +++ b/src/cli/connection/cloud-connection-record.test.ts @@ -111,7 +111,7 @@ test('an expired proxy front is released with its attachment before the attachme const released: unknown[] = []; await cleanExpiredCloudAttachments( location.stateDir, - () => true, + () => ({ mayUseSavedCredentials: true }), async () => { throw new Error('a limrun daemon is not retired for a proxy front'); }, @@ -124,12 +124,29 @@ test('an expired proxy front is released with its attachment before the attachme expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); }); +test('an expired proxy-front attachment is removed without releasing when saved credentials are not admitted', async () => { + const location = expiredProxyFrontLocation(); + const released: unknown[] = []; + await cleanExpiredCloudAttachments( + location.stateDir, + () => ({ mayUseSavedCredentials: false }), + async () => { + throw new Error('a limrun daemon is not retired for a proxy front'); + }, + async (_location, attachment) => { + released.push(attachment); + }, + ); + expect(released).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); +}); + test('an expired proxy-front attachment is removed even when its release fails', async () => { const location = expiredProxyFrontLocation(); const attempts: unknown[] = []; await cleanExpiredCloudAttachments( location.stateDir, - () => true, + () => ({ mayUseSavedCredentials: true }), async () => undefined, async (_location, attachment) => { attempts.push(attachment); diff --git a/src/cli/connection/cloud-connection-record.ts b/src/cli/connection/cloud-connection-record.ts index 53147bd677..4b31c7c212 100644 --- a/src/cli/connection/cloud-connection-record.ts +++ b/src/cli/connection/cloud-connection-record.ts @@ -553,13 +553,17 @@ function isExpired(record: CloudConnectionRecord): boolean { return record.deadlineAt !== undefined && Date.parse(record.deadlineAt) <= Date.now(); } +export type ExpiredBookingAdmission = { + mayUseSavedCredentials: boolean; +}; + /** * Clears what expired bookings left in the state directory. Only a booking that `admits` accepts * is touched, so a caller never tears down a booking that another identity made. */ export async function cleanExpiredCloudAttachments( stateDir: string, - admits: (record: CloudConnectionRecord) => boolean, + admits: (record: CloudConnectionRecord) => ExpiredBookingAdmission | null, retireExpiredDaemon: (location: ConnectionLocation, generation: string) => Promise, releaseExpiredProxyFront: ( location: ConnectionLocation, @@ -581,11 +585,14 @@ export async function cleanExpiredCloudAttachments( if (!location) continue; await tryWithConnectionLock(location, async () => { let current: CloudConnectionRecord | null; + let admission: ExpiredBookingAdmission | null; let kind: unknown; let proxyFront: ProxyFrontAttachment | undefined; try { current = readCloudConnection(location); - if (!current || !isExpired(current) || !admits(current)) return; + if (!current || !isExpired(current)) return; + admission = admits(current); + if (!admission) return; // Saved state of another booking is left for the explicit local recovery. const state = readRemoteConnectionState(location); if (state && !samePairedBooking(state.cloudSession, current)) return; @@ -595,7 +602,7 @@ export async function cleanExpiredCloudAttachments( } catch { return; } - if (proxyFront && current.phase !== 'pending') { + if (proxyFront && current.phase !== 'pending' && admission.mayUseSavedCredentials) { await releaseExpiredProxyFront(location, proxyFront).catch(() => undefined); removeCloudAttachment(location); } else if (current.phase === 'pending' || kind === 'agent-device-daemon') { From fb6b16b22346ac34b81cf8c22ed7b6cdc09dd004 Mon Sep 17 00:00:00 2001 From: Suneeth12 Date: Sun, 6 Dec 2026 11:53:49 +0530 Subject: [PATCH 2/6] fix(cli): keep local-only cloud cleanup provider-free and preserve unbound teardown sidecars --- .../cli-cloud-limrun-attachment.test.ts | 79 ++++ .../cli-cloud-session-identity.test.ts | 359 ++++++++++++------ src/cli.ts | 2 +- src/cli/connection/active-connection.ts | 20 +- src/cli/connection/cloud-access.ts | 24 +- src/cli/connection/cloud-connect.ts | 21 +- .../cloud-connection-record.test.ts | 38 ++ src/cli/connection/cloud-connection-record.ts | 6 +- src/cli/connection/cloud-plugin-attachment.ts | 19 +- 9 files changed, 431 insertions(+), 137 deletions(-) diff --git a/src/__tests__/cli-cloud-limrun-attachment.test.ts b/src/__tests__/cli-cloud-limrun-attachment.test.ts index 38913aaf87..4f655567aa 100644 --- a/src/__tests__/cli-cloud-limrun-attachment.test.ts +++ b/src/__tests__/cli-cloud-limrun-attachment.test.ts @@ -302,3 +302,82 @@ test('disconnect preserves recovery when a startup owns the lock before publishi expect((await runCliCapture(['disconnect', '--json'], { env })).code).toBeNull(); expect(mock.mock.calls.filter(([, init]) => init.method === 'DELETE')).toHaveLength(1); }); + +test.each(['stale-v1-login', 'unbound'] as const)( + 'local-only sweep of an expired Limrun booking (%s) removes its attachment without stopping its daemon', + async (mode) => { + const env = limrunEnv('current'); + const location = locationOf(env); + const broker = stubCloudApi(); + broker.mockResolvedValueOnce(Response.json(limrunLease('ios'), { status: 201 })); + expect((await runCliCapture(args('ios'), { env })).code).toBeNull(); + writeHostedDaemonRegistration(location); + const { accountBinding, ...unboundRecord } = readCloudConnection(location)!; + writeCloudConnection(location, { + ...(mode === 'unbound' ? unboundRecord : { ...unboundRecord, accountBinding }), + deadlineAt: new Date(0).toISOString(), + }); + let sweepEnv: Record = env; + if (mode === 'stale-v1-login') { + const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth'); + fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(authDir, 'cli-session.json'), + JSON.stringify({ + version: 1, + id: 'stale-login', + cloudBaseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL, + refreshCredential: 'stale-refresh-credential', + createdAt: new Date().toISOString(), + }), + { mode: 0o600 }, + ); + sweepEnv = { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }; + } + + await runCliCapture(['connection', 'status', '--session', location.session, '--json'], { + env: sweepEnv, + }); + + expect(stop).not.toHaveBeenCalled(); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + }, +); + +test('forget with a stale v1 login clears a paired Limrun booking locally without stopping its daemon', async () => { + const env = limrunEnv('current'); + const location = locationOf(env); + const broker = stubCloudApi(); + broker.mockResolvedValueOnce(Response.json(limrunLease('ios'), { status: 201 })); + expect((await runCliCapture(args('ios'), { env })).code).toBeNull(); + const record = readCloudConnection(location)!; + const daemonDir = hostedPluginDaemonDir(location, record); + writeHostedDaemonRegistration(location); + const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth'); + fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(authDir, 'cli-session.json'), + JSON.stringify({ + version: 1, + id: 'stale-login', + cloudBaseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL, + refreshCredential: 'stale-refresh-credential', + createdAt: new Date().toISOString(), + }), + { mode: 0o600 }, + ); + + const forgotten = await runCliCapture( + ['disconnect', '--forget', '--session', location.session, '--json'], + { env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined } }, + ); + + expect(forgotten.code, forgotten.stdout).toBeNull(); + expect(JSON.parse(forgotten.stdout).data).toMatchObject({ forgotten: true, released: false }); + expect(stop).not.toHaveBeenCalled(); + expect(forgotten.stderr).toContain('local daemon may still be running'); + expect(forgotten.stderr).toContain(daemonDir); + expect(readCloudConnection(location)).toBeNull(); + expect(readRemoteConnectionState(location)).toBeNull(); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); +}); diff --git a/src/__tests__/cli-cloud-session-identity.test.ts b/src/__tests__/cli-cloud-session-identity.test.ts index 9301803c82..bf40062e4e 100644 --- a/src/__tests__/cli-cloud-session-identity.test.ts +++ b/src/__tests__/cli-cloud-session-identity.test.ts @@ -667,50 +667,53 @@ test("a direct profile that redirects to another state directory checks identity expect(readCloudConnection(location)?.id).toBe(hostedDevice.id); }); -test.each(sessions)( - 'a stale v1 login sweeps expired proxy-front files of session %s locally without using saved credentials', - async (session) => { - const { env, front, location } = await bookProxyFront(session); - expire(location); - const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth'); - fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); - fs.writeFileSync( - path.join(authDir, 'cli-session.json'), - JSON.stringify({ - version: 1, - id: 'stale-login', - cloudBaseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL, - refreshCredential: 'stale-refresh-credential', - createdAt: new Date().toISOString(), - }), - { mode: 0o600 }, - ); - const staleEnv: Env = { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }; +function writeRawLogin(stateDir: string, content: string): string { + const authDir = path.join(stateDir, 'auth'); + fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); + const file = path.join(authDir, 'cli-session.json'); + fs.writeFileSync(file, content, { mode: 0o600 }); + return file; +} - const result = await runCliCapture(['connection', 'status', '--session', session, '--json'], { - env: staleEnv, - sendToDaemon: front, - }); - expect(JSON.parse(result.stdout).error.details.reason).toBe( - 'cloud_connection_credential_mismatch', - ); - expect(result.calls).toEqual([]); - expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); - }, -); +function writeStaleV1Login(env: Env): string { + return writeRawLogin( + env.AGENT_DEVICE_STATE_DIR, + JSON.stringify({ + version: 1, + id: 'stale-login', + cloudBaseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL, + refreshCredential: 'stale-refresh-credential', + createdAt: new Date().toISOString(), + }), + ); +} -test.each(sessions)( - 'a malformed saved login sweeps expired proxy-front files of session %s locally without using saved credentials', - async (session) => { +function expireUnbound( + location: { stateDir: string; session: string }, + extra: Partial>> = {}, +): void { + const { accountBinding: _unbound, ...record } = readCloudConnection(location)!; + writeCloudConnection(location, { + ...record, + ...extra, + deadlineAt: new Date(Date.now() - 1000).toISOString(), + }); +} + +test.each( + sessions.flatMap((session) => + (['stale-v1', 'malformed'] as const).map((kind) => [session, kind] as const), + ), +)( + 'an unverifiable (%s / %s) login sweeps expired proxy-front files locally without saved credentials', + async (session, kind) => { const { env, front, location } = await bookProxyFront(session); expire(location); - const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth'); - fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); - fs.writeFileSync(path.join(authDir, 'cli-session.json'), '{', { mode: 0o600 }); - const unreadableEnv: Env = { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }; + if (kind === 'stale-v1') writeStaleV1Login(env); + else writeRawLogin(env.AGENT_DEVICE_STATE_DIR, '{'); const result = await runCliCapture(['connection', 'status', '--session', session, '--json'], { - env: unreadableEnv, + env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }, sendToDaemon: front, }); expect(JSON.parse(result.stdout).error.details.reason).toBe( @@ -722,54 +725,44 @@ test.each(sessions)( ); test.skipIf(process.platform === 'win32')( - 'an unreadable saved login sweeps expired proxy-front files locally without using saved credentials', + 'an unreadable saved login sweeps expired proxy-front files locally without saved credentials, even with another base URL', async () => { - const { env, front, location } = await bookProxyFront('cloud-qa'); - expire(location); - const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth'); - const sessionFile = path.join(authDir, 'cli-session.json'); - fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); - fs.writeFileSync(sessionFile, '{"version":2}', { mode: 0o600 }); - fs.chmodSync(sessionFile, 0o000); - try { - const result = await runCliCapture( - ['connection', 'status', '--session', 'cloud-qa', '--json'], - { - env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }, - sendToDaemon: front, - }, - ); - expect(JSON.parse(result.stdout).error.details.reason).toBe( - 'cloud_connection_credential_mismatch', - ); - expect(result.calls).toEqual([]); - expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); - } finally { - fs.chmodSync(sessionFile, 0o600); + for (const baseUrl of [undefined, 'https://other-cloud.example']) { + const { env, front, location } = await bookProxyFront('cloud-qa'); + expire(location); + const sessionFile = writeRawLogin(env.AGENT_DEVICE_STATE_DIR, '{"version":2}'); + fs.chmodSync(sessionFile, 0o000); + try { + const result = await runCliCapture( + ['connection', 'status', '--session', 'cloud-qa', '--json'], + { + env: { + ...env, + AGENT_DEVICE_CLOUD_API_KEY: undefined, + ...(baseUrl ? { AGENT_DEVICE_CLOUD_BASE_URL: baseUrl } : {}), + }, + sendToDaemon: front, + }, + ); + expect(JSON.parse(result.stdout).error.details.reason).toBe( + 'cloud_connection_credential_mismatch', + ); + expect(result.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + } finally { + fs.chmodSync(sessionFile, 0o600); + } } }, ); test('forget with a stale v1 login clears a bound booking locally without saved credentials and refuses with no identity source', async () => { const { env, front, location } = await bookProxyFront('cloud-qa'); - const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth'); - fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); - fs.writeFileSync( - path.join(authDir, 'cli-session.json'), - JSON.stringify({ - version: 1, - id: 'stale-login', - cloudBaseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL, - refreshCredential: 'stale-refresh-credential', - createdAt: new Date().toISOString(), - }), - { mode: 0o600 }, - ); - const staleEnv: Env = { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }; + writeStaleV1Login(env); const forgotten = await runCliCapture( ['disconnect', '--forget', '--session', 'cloud-qa', '--json'], - { env: staleEnv, sendToDaemon: front }, + { env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }, sendToDaemon: front }, ); expect(forgotten.code, forgotten.stdout).toBeNull(); expect(JSON.parse(forgotten.stdout).data).toMatchObject({ forgotten: true }); @@ -778,19 +771,7 @@ test('forget with a stale v1 login clears a bound booking locally without saved const second = await book('cloud-qa', 'api-key'); removeRemoteConnectionState(second.location); - const secondAuthDir = path.join(second.env.AGENT_DEVICE_STATE_DIR, 'auth'); - fs.mkdirSync(secondAuthDir, { recursive: true, mode: 0o700 }); - fs.writeFileSync( - path.join(secondAuthDir, 'cli-session.json'), - JSON.stringify({ - version: 1, - id: 'stale-login', - cloudBaseUrl: second.env.AGENT_DEVICE_CLOUD_BASE_URL, - refreshCredential: 'stale-refresh-credential', - createdAt: new Date().toISOString(), - }), - { mode: 0o600 }, - ); + writeStaleV1Login(second.env); fs.writeFileSync(path.join(cloudConnectionDir(second.location), 'record.json'), '{'); const refused = await runCliCapture( ['disconnect', '--forget', '--session', 'cloud-qa', '--json'], @@ -802,36 +783,20 @@ test('forget with a stale v1 login clears a bound booking locally without saved }); test.each(sessions)( - 'the sweep clears an expired pending booking of session %s that has no account binding', + 'the sweep clears an expired pending or unbound proxy-front booking of session %s without sending saved credentials', async (session) => { - const { env, front, location } = await bookProxyFront(session); - const { accountBinding: _unbound, ...record } = readCloudConnection(location)!; - removeRemoteConnectionState(location); - writeCloudConnection(location, { - ...record, - phase: 'pending', - deadlineAt: new Date(Date.now() - 1000).toISOString(), + const pending = await bookProxyFront(session); + removeRemoteConnectionState(pending.location); + expireUnbound(pending.location, { phase: 'pending' }); + const pendingSweep = await runCliCapture(['connection', 'status', '--json'], { + env: pending.env, + sendToDaemon: pending.front, }); + expect(pendingSweep.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(pending.location))).toBe(false); - const result = await runCliCapture(['connection', 'status', '--json'], { - env, - sendToDaemon: front, - }); - expect(result.calls).toEqual([]); - expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); - }, -); - -test.each(sessions)( - 'the sweep clears an expired unbound proxy-front booking of session %s without sending saved credentials', - async (session) => { const { env, front, location } = await bookProxyFront(session); - const { accountBinding: _unbound, ...record } = readCloudConnection(location)!; - writeCloudConnection(location, { - ...record, - deadlineAt: new Date(Date.now() - 1000).toISOString(), - }); - + expireUnbound(location); const foreignOrigin: Env = { ...env, AGENT_DEVICE_CLOUD_BASE_URL: 'https://other-cloud.example', @@ -852,3 +817,167 @@ test.each(sessions)( expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); }, ); + +test.each(['malformed', 'stale-v1'] as const)( + 'an unverifiable (%s) login without an API key sweeps an expired booking even with another AGENT_DEVICE_CLOUD_BASE_URL', + async (kind) => { + const { env, front, location } = await bookProxyFront('cloud-qa'); + expire(location); + if (kind === 'stale-v1') writeStaleV1Login(env); + else writeRawLogin(env.AGENT_DEVICE_STATE_DIR, '{'); + + const result = await runCliCapture( + ['connection', 'status', '--session', 'cloud-qa', '--json'], + { + env: { + ...env, + AGENT_DEVICE_CLOUD_API_KEY: undefined, + AGENT_DEVICE_CLOUD_BASE_URL: 'https://other-cloud.example', + }, + sendToDaemon: front, + }, + ); + expect(JSON.parse(result.stdout).error.details.reason).toBe( + 'cloud_connection_credential_mismatch', + ); + expect(result.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + }, +); + +test('a verified v2 login with another AGENT_DEVICE_CLOUD_BASE_URL still does not sweep an expired booking', async () => { + const { env, front, location } = await bookProxyFront('cloud-qa'); + expire(location); + storeLogin(env, 'owner-login'); + + await runCliCapture(['connection', 'status', '--session', 'cloud-qa', '--json'], { + env: { + ...env, + AGENT_DEVICE_CLOUD_API_KEY: undefined, + AGENT_DEVICE_CLOUD_BASE_URL: 'https://other-cloud.example', + }, + sendToDaemon: front, + }); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(true); +}); + +test.each(sessions)( + 'plain disconnect on an expired unbound proxy-front booking of session %s keeps the sidecar so broker-verified teardown releases its lease', + async (session) => { + const { env, front, fetchMock, location } = await bookProxyFront(session); + expireUnbound(location); + fetchMock.mockImplementation(async (url: URL, init: RequestInit) => { + if (init.method === 'GET' && url.pathname === '/v1/sessions') { + return Response.json({ id: proxyFrontDevice.id, state: 'settled' }); + } + return new Response(null, { status: 204 }); + }); + + const disconnected = await runCliCapture(['disconnect', '--session', session, '--json'], { + env, + sendToDaemon: front, + }); + expect(disconnected.code, disconnected.stdout).toBeNull(); + expect(disconnected.calls.map(({ command }) => command)).toEqual(['lease_release']); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + expect(readCloudConnection(location)).toBeNull(); + }, +); + +test('connect cloud --force and unfinished disconnect keep an expired unbound proxy-front sidecar while other sessions sweep locally', async () => { + const forceCase = await bookProxyFront('cloud-qa'); + expireUnbound(forceCase.location); + forceCase.fetchMock.mockImplementation(async (url: URL, init: RequestInit) => { + if (init.method === 'GET' && url.pathname === '/v1/sessions') { + return Response.json({ id: proxyFrontDevice.id, state: 'settled' }); + } + if (init.method === 'POST' && url.pathname === '/v1/sessions') { + return Response.json(proxyFrontDevice, { status: 201 }); + } + return new Response(null, { status: 204 }); + }); + const replaced = await runCliCapture([...connectArgs, '--session', 'cloud-qa', '--force'], { + env: forceCase.env, + sendToDaemon: forceCase.front, + }); + expect(replaced.code, replaced.stdout).toBeNull(); + expect(replaced.calls.map(({ command }) => command)).toContain('lease_release'); + + const pendingCase = await bookProxyFront('cloud-qa'); + expireUnbound(pendingCase.location, { phase: 'pending' }); + pendingCase.fetchMock.mockImplementation(async (url: URL, init: RequestInit) => { + if (init.method === 'GET' && url.pathname === '/v1/sessions') { + return Response.json({ id: proxyFrontDevice.id, state: 'settled' }); + } + return new Response(null, { status: 204 }); + }); + const refused = await runCliCapture(['disconnect', '--session', 'cloud-qa', '--json'], { + env: pendingCase.env, + sendToDaemon: async (req) => + req.command === 'lease_release' + ? { ok: false, error: { code: 'COMMAND_FAILED', message: 'release denied' } } + : { ok: true, data: {} }, + }); + expect(refused.code).toBe(1); + expect(JSON.parse(refused.stdout).error.details.reason).toBe('cloud_connect_rollback_failed'); + expect(fs.existsSync(cloudAttachmentPath(pendingCase.location))).toBe(true); + + const otherCase = await bookProxyFront('cloud-qa'); + expireUnbound(otherCase.location); + const disconnected = await runCliCapture(['disconnect', '--session', 'other-session', '--json'], { + env: otherCase.env, + sendToDaemon: otherCase.front, + }); + expect(disconnected.code, disconnected.stdout).toBeNull(); + expect(disconnected.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(otherCase.location))).toBe(false); +}); + +test('forget recovers an orphan attachment with no identity source when cli-session.json is malformed or unreadable', async () => { + const malformedCase = await book('cloud-qa', 'api-key'); + removeRemoteConnectionState(malformedCase.location); + const recordFile = path.join(cloudConnectionDir(malformedCase.location), 'record.json'); + fs.writeFileSync(recordFile, '{'); + writeRawLogin(malformedCase.env.AGENT_DEVICE_STATE_DIR, '{'); + const forgotten = await runCliCapture( + ['disconnect', '--forget', '--session', 'cloud-qa', '--json'], + { env: { ...malformedCase.env, AGENT_DEVICE_CLOUD_API_KEY: undefined } }, + ); + expect(forgotten.code, forgotten.stdout).toBeNull(); + expect(JSON.parse(forgotten.stdout).data).toMatchObject({ forgotten: true }); + expect(fs.existsSync(recordFile)).toBe(false); + expect(fs.existsSync(cloudAttachmentPath(malformedCase.location))).toBe(false); + + if (process.platform === 'win32') return; + const unreadableCase = await book('cloud-qa', 'api-key'); + removeRemoteConnectionState(unreadableCase.location); + const unreadableRecord = path.join(cloudConnectionDir(unreadableCase.location), 'record.json'); + fs.writeFileSync(unreadableRecord, '{'); + const sessionFile = writeRawLogin(unreadableCase.env.AGENT_DEVICE_STATE_DIR, '{"version":2}'); + fs.chmodSync(sessionFile, 0o000); + try { + const recovered = await runCliCapture( + ['disconnect', '--forget', '--session', 'cloud-qa', '--json'], + { env: { ...unreadableCase.env, AGENT_DEVICE_CLOUD_API_KEY: undefined } }, + ); + expect(recovered.code, recovered.stdout).toBeNull(); + expect(JSON.parse(recovered.stdout).data).toMatchObject({ forgotten: true }); + expect(fs.existsSync(unreadableRecord)).toBe(false); + expect(fs.existsSync(cloudAttachmentPath(unreadableCase.location))).toBe(false); + } finally { + fs.chmodSync(sessionFile, 0o600); + } +}); + +test('plain disconnect with a malformed cli-session.json keeps reporting cloud_api_key_required', async () => { + const { env, fetchMock, location } = await book('cloud-qa', 'api-key'); + writeRawLogin(env.AGENT_DEVICE_STATE_DIR, '{'); + + const refused = await runCliCapture(['disconnect', '--session', 'cloud-qa', '--json'], { + env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }, + }); + expect(refused.code).toBe(1); + expect(JSON.parse(refused.stdout).error.details.reason).toBe('cloud_api_key_required'); + expect(brokerCalls(fetchMock)).toEqual([]); + expect(readCloudConnection(location)?.id).toBe(hostedDevice.id); +}); diff --git a/src/cli.ts b/src/cli.ts index 0744b6f880..2edcf364e0 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -454,7 +454,7 @@ async function resolveRunContextOrExit( forget: effectiveFlags.forget, stateDir: daemonPaths.baseDir, host: base.host, - session: effectiveFlags.session ?? flags.session, + session: defaults?.claimed?.session ?? effectiveFlags.session ?? flags.session, binding: cloudSession, remoteConfig: effectiveFlags.remoteConfig, remoteRoute: [ diff --git a/src/cli/connection/active-connection.ts b/src/cli/connection/active-connection.ts index 29229fd6eb..31dd48446e 100644 --- a/src/cli/connection/active-connection.ts +++ b/src/cli/connection/active-connection.ts @@ -43,8 +43,15 @@ export async function resolveCloudAdmission(options: { }) { const { command, usesSessions, stateDir, session, binding } = options; if (!usesSessions || command === 'auth' || (command === 'disconnect' && options.forget)) return; + const teardownSession = + command === 'disconnect' || command === 'connect' ? (session ?? 'default') : undefined; const sweep = () => - sweepAdmittedExpiredBookings(stateDir, options.host, options.releaseProxyFrontLease); + sweepAdmittedExpiredBookings( + stateDir, + options.host, + options.releaseProxyFrontLease, + teardownSession, + ); if (command === 'connect' || command === 'connection' || command === 'disconnect') { await sweep(); return; @@ -83,10 +90,11 @@ async function sweepAdmittedExpiredBookings( stateDir: string, host: HostEnvironment, release: ReleaseProxyFrontLease | undefined, + teardownSession?: string, ): Promise { await cleanExpiredCloudAttachments( stateDir, - (record) => admitsExpiredBooking(stateDir, host.env, record), + (record) => admitsExpiredBooking(stateDir, host.env, record, teardownSession), async (location, generation) => { const { stopHostedPluginDaemon } = await import('./cloud-plugin-attachment.ts'); await stopHostedPluginDaemon(location, generation, host); @@ -113,7 +121,15 @@ function admitsExpiredBooking( stateDir: string, env: HostEnvironment['env'], record: CloudConnectionRecord, + teardownSession?: string, ): ExpiredBookingAdmission | null { + if ( + teardownSession && + record.session === teardownSession && + record.accountBinding === undefined + ) { + return null; + } try { return admitHostedCaller({ stateDir, env, booking: record }, 'clear'); } catch { diff --git a/src/cli/connection/cloud-access.ts b/src/cli/connection/cloud-access.ts index 3a14ef8ed5..51d9106fe1 100644 --- a/src/cli/connection/cloud-access.ts +++ b/src/cli/connection/cloud-access.ts @@ -102,8 +102,8 @@ export function readCloudCaller( env: EnvMap, savedOrigin: string, ): CloudCallerIdentity | undefined { - const caller = readCloudCallerForPurpose(stateDir, env, savedOrigin, 'use'); - return caller === 'unverified' ? undefined : caller; + if (!presentsCloudCredential(stateDir, env)) return undefined; + return readCallerIdentity(env, savedOrigin, readStoredCliSession(stateDir)); } /** @@ -170,7 +170,7 @@ function readStoredLogin(stateDir: string): ReturnType, - allowUnverified: boolean, -): CloudCallerIdentity | 'unverified' { +): CloudCallerIdentity { // Another configured origin or key origin is another identity, not a malformed request. let cloudBaseUrl: string; let key: string | undefined; @@ -211,10 +214,7 @@ function readCallerIdentity( } if (key) return { cloudBaseUrl, accountBinding: identityDigest('api-key', key) }; // A login file that does not establish its issuer establishes no account either. - if (!login || login === 'unverified') { - if (allowUnverified) return 'unverified'; - throw credentialMismatch(); - } + if (!login || login === 'unverified') throw credentialMismatch(); return { cloudBaseUrl: URL.parse(login.cloudBaseUrl)?.origin ?? login.cloudBaseUrl, accountBinding: hostedLoginBinding(login.accountId, login.id), diff --git a/src/cli/connection/cloud-connect.ts b/src/cli/connection/cloud-connect.ts index 147170b0db..914fbbd1a1 100644 --- a/src/cli/connection/cloud-connect.ts +++ b/src/cli/connection/cloud-connect.ts @@ -41,7 +41,11 @@ import { type CloudConnectionRecord, type ConnectionLocation, } from './cloud-connection-record.ts'; -import { hostedPluginDaemonDir, stopHostedPluginDaemon } from './cloud-plugin-attachment.ts'; +import { + hasHostedPluginDaemonRegistration, + hostedPluginDaemonDir, + stopHostedPluginDaemon, +} from './cloud-plugin-attachment.ts'; import { isLegacyCloudProfile } from './active-connection.ts'; import { releaseProxyFrontConnectionLease } from '../commands/connection-lease-transaction.ts'; import { @@ -701,7 +705,9 @@ export async function forgetCloudConnection(options: { : null; if (!hasFiles && !hostedState) return null; const [daemonStateDir] = await Promise.all([ - stopHostedDaemonForForget(location, binding, host), + usesSavedCredentials + ? stopHostedDaemonForForget(location, binding, host) + : unstoppedHostedDaemonDir(location, binding, host), binding?.transport === 'agent-device-daemon' && usesSavedCredentials ? settleWithin( () => releaseProxyFrontTeardownLease(client, location, hostedState), @@ -734,6 +740,17 @@ async function stopHostedDaemonForForget( if (!stopped) return hostedPluginDaemonDir(location, binding); } +function unstoppedHostedDaemonDir( + location: ConnectionLocation, + binding: CloudSessionBinding | undefined, + host: HostEnvironment, +): string | undefined { + if (!binding || binding.transport === 'agent-device-daemon') return undefined; + return hasHostedPluginDaemonRegistration(location, binding.generation, host) + ? hostedPluginDaemonDir(location, binding) + : undefined; +} + function removeCloudState( location: ConnectionLocation, state: RemoteConnectionState | null, diff --git a/src/cli/connection/cloud-connection-record.test.ts b/src/cli/connection/cloud-connection-record.test.ts index 9049f48353..312860cff3 100644 --- a/src/cli/connection/cloud-connection-record.test.ts +++ b/src/cli/connection/cloud-connection-record.test.ts @@ -141,6 +141,44 @@ test('an expired proxy-front attachment is removed without releasing when saved expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); }); +test('an expired plugin attachment is removed directly without retiring its daemon when saved credentials are not admitted', async () => { + const stateDir = mkdtempForTestSync('cloud-record-plugin-expiry-'); + const location = { stateDir, session: 'plugin-expiry-qa' }; + writeCloudConnection(location, { + session: location.session, + generation: 'generation-1', + phase: 'committed', + origin: 'https://cloud.example', + fingerprint: 'fingerprint-1', + id: '00000000-0000-4000-8000-000000000001', + deadlineAt: new Date(Date.now() - 1000).toISOString(), + }); + writeCloudAttachment( + location, + { + kind: 'plugin', + plugin: '@agent-device/limrun', + token: 'scoped-plugin-token', + expiresAt: new Date(Date.now() - 1000).toISOString(), + data: { kind: 'limrun-instance' }, + }, + 'generation-1', + ); + const retired: string[] = []; + await cleanExpiredCloudAttachments( + location.stateDir, + () => ({ mayUseSavedCredentials: false }), + async (_location, generation) => { + retired.push(generation); + }, + async () => { + throw new Error('a proxy front is not released for a plugin attachment'); + }, + ); + expect(retired).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); +}); + test('an expired proxy-front attachment is removed even when its release fails', async () => { const location = expiredProxyFrontLocation(); const attempts: unknown[] = []; diff --git a/src/cli/connection/cloud-connection-record.ts b/src/cli/connection/cloud-connection-record.ts index 4b31c7c212..18ecf190de 100644 --- a/src/cli/connection/cloud-connection-record.ts +++ b/src/cli/connection/cloud-connection-record.ts @@ -605,7 +605,11 @@ export async function cleanExpiredCloudAttachments( if (proxyFront && current.phase !== 'pending' && admission.mayUseSavedCredentials) { await releaseExpiredProxyFront(location, proxyFront).catch(() => undefined); removeCloudAttachment(location); - } else if (current.phase === 'pending' || kind === 'agent-device-daemon') { + } else if ( + current.phase === 'pending' || + kind === 'agent-device-daemon' || + !admission.mayUseSavedCredentials + ) { removeCloudAttachment(location); } else { await retireExpiredDaemon(location, current.generation).then( diff --git a/src/cli/connection/cloud-plugin-attachment.ts b/src/cli/connection/cloud-plugin-attachment.ts index 8e6f77bd67..f36c84d8e7 100644 --- a/src/cli/connection/cloud-plugin-attachment.ts +++ b/src/cli/connection/cloud-plugin-attachment.ts @@ -4,6 +4,7 @@ import type { AttachmentInput } from '@agent-device/contracts/hosted-attachment' import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import { AppError, cloudPluginRequiredError, type ReasonTable } from '@agent-device/kernel/errors'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { lstatIfPresent } from '@agent-device/host-kit/file'; import { pluginInstallCommand } from '@agent-device/contracts/plugin-installation'; import { readVersion } from '@agent-device/host-kit/version'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; @@ -72,6 +73,19 @@ export function hostedPluginDaemonDir( return path.join(cloudConnectionDir(location), 'daemon-' + key.slice(0, 20)); } +export function hasHostedPluginDaemonRegistration( + location: ConnectionLocation, + generation: string, + host: HostEnvironment, +): boolean { + const paths = resolveDaemonPaths(hostedPluginDaemonDir(location, { generation }), host); + try { + return Boolean(lstatIfPresent(paths.infoPath) || lstatIfPresent(paths.lockPath)); + } catch { + return true; + } +} + export async function stopHostedPluginDaemon( location: ConnectionLocation, generation: string | undefined, @@ -85,10 +99,7 @@ export async function stopHostedPluginDaemon( await import('@agent-device/daemon-contracts/daemon-registration'); const expected = { session: location.session, generation }; let identity = readDaemonStopIdentity(paths.infoPath, expected); - if ( - identity.ownership === 'absent' && - (await import('@agent-device/host-kit/file')).lstatIfPresent(paths.lockPath) - ) { + if (identity.ownership === 'absent' && lstatIfPresent(paths.lockPath)) { const { recoverAbandonedDaemonRegistration } = await import('@agent-device/daemon-contracts/daemon-registration-owner'); const retirement = await recoverAbandonedDaemonRegistration({ paths, observed: null }); From 913e32ae1ed463d239674c5758be52c5b2ccd59a Mon Sep 17 00:00:00 2001 From: Suneeth12 Date: Sun, 6 Dec 2026 13:22:22 +0530 Subject: [PATCH 3/6] fix(cli): verify pairing and broker ownership before unfinished connect teardown --- .../cli-cloud-record-recovery.test.ts | 97 +++++++++++++++++++ src/cli/commands/connection-hosted.ts | 10 +- src/cli/connection/cloud-connect.ts | 33 ++++++- 3 files changed, 135 insertions(+), 5 deletions(-) diff --git a/src/__tests__/cli-cloud-record-recovery.test.ts b/src/__tests__/cli-cloud-record-recovery.test.ts index d494643602..191206501b 100644 --- a/src/__tests__/cli-cloud-record-recovery.test.ts +++ b/src/__tests__/cli-cloud-record-recovery.test.ts @@ -4,6 +4,7 @@ import path from 'node:path'; import { afterEach, expect, test, vi } from 'vitest'; import { writeCliSession } from '../cli/auth-session.ts'; import { + cloudAttachmentPath, cloudConnectionDir, prepareCloudConnection, readCloudConnection, @@ -17,9 +18,11 @@ import { hostedDevice, locationOf, postKey, + proxyFrontDevice, stubCloudApi, timeOutAllocation, timeOutNextCreate, + withLeaseAllocation, } from './cli-cloud-session.fixtures.ts'; afterEach(() => { @@ -286,3 +289,97 @@ test('an inconclusive refusal to end an observed allocation keeps its lease ID', expect((await runCliCapture(['disconnect', '--json'], { env })).code).toBeNull(); expect(fetchMock.mock.calls.at(-1)?.[0].pathname).toBe(`/v1/sessions/${hostedDevice.id}`); }); + +async function bookExpiredUnboundUnfinishedProxyFront(phase: 'pending' | 'closing') { + const env = cloudEnv(); + const location = locationOf(env); + const front = withLeaseAllocation(); + const broker = stubCloudApi(proxyFrontDevice); + expect((await runCliCapture(connectArgs, { env, sendToDaemon: front })).code).toBeNull(); + expect( + ( + await runCliCapture( + ['open', 'com.apple.Preferences', '--session', location.session, '--json'], + { + env, + sendToDaemon: front, + }, + ) + ).code, + ).toBeNull(); + const { accountBinding: _unbound, ...record } = readCloudConnection(location)!; + writeCloudConnection(location, { + ...record, + phase, + hostedLeaseId: 'proposed-lease-id', + deadlineAt: new Date(Date.now() - 1000).toISOString(), + }); + broker.mockClear(); + return { env, location, front, broker }; +} + +test.each([ + { phase: 'pending' as const, force: false }, + { phase: 'pending' as const, force: true }, + { phase: 'closing' as const, force: false }, + { phase: 'closing' as const, force: true }, +])( + 'connect (force=$force) on an expired unbound $phase proxy-front booking refuses another account before any lease teardown', + async ({ phase, force }) => { + const { env, location, front, broker } = await bookExpiredUnboundUnfinishedProxyFront(phase); + broker.mockImplementation(async (_url: URL, init: RequestInit) => { + if (init.method === 'GET') return Response.json({ error: 'not_found' }, { status: 404 }); + return new Response(null, { status: 204 }); + }); + + const args = force ? [...connectArgs, '--force'] : connectArgs; + const refused = await runCliCapture(args, { + env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: 'other-account-api-key' }, + sendToDaemon: front, + }); + + expect(refused.code).toBe(1); + expect(JSON.parse(refused.stdout).error.details.reason).toBe( + 'cloud_connection_allocation_unconfirmed', + ); + expect(refused.calls).toEqual([]); + expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET']); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(true); + expect(readCloudConnection(location)?.phase).toBe(phase); + expect(readCloudConnection(location)?.accountBinding).toBeUndefined(); + }, +); + +test('connect on an expired unbound unfinished proxy-front booking releases its lease once the owner proves allocation and refuses unpaired state', async () => { + const unpaired = await bookExpiredUnboundUnfinishedProxyFront('pending'); + writeCloudConnection(unpaired.location, { + ...readCloudConnection(unpaired.location)!, + generation: 'different-generation', + }); + const blocked = await runCliCapture(connectArgs, { + env: unpaired.env, + sendToDaemon: unpaired.front, + }); + expect(blocked.code).toBe(1); + expect(JSON.parse(blocked.stdout).error.details.reason).toBe('cloud_connection_changed'); + expect(blocked.calls).toEqual([]); + expect(unpaired.broker).not.toHaveBeenCalled(); + + const owned = await bookExpiredUnboundUnfinishedProxyFront('pending'); + owned.broker.mockImplementation(async (url: URL, init: RequestInit) => { + if (init.method === 'GET' && url.pathname === '/v1/sessions') { + return Response.json({ id: proxyFrontDevice.id, state: 'settled' }); + } + if (init.method === 'POST' && url.pathname === '/v1/sessions') { + return Response.json(proxyFrontDevice, { status: 201 }); + } + return new Response(null, { status: 204 }); + }); + const replaced = await runCliCapture(connectArgs, { + env: owned.env, + sendToDaemon: owned.front, + }); + expect(replaced.code, replaced.stdout).toBeNull(); + expect(replaced.calls.map(({ command }) => command)).toContain('lease_release'); + expect(owned.broker.mock.calls.map(([, init]) => init.method)).not.toContain('DELETE'); +}); diff --git a/src/cli/commands/connection-hosted.ts b/src/cli/commands/connection-hosted.ts index f923d8c2bd..20e0835a77 100644 --- a/src/cli/commands/connection-hosted.ts +++ b/src/cli/commands/connection-hosted.ts @@ -54,7 +54,6 @@ import { type ConnectionLocation, } from '../connection/cloud-connection-record.ts'; import { - assertUncommittedGenerationAccess, sendReceiptWithin, cleanupFailureCodes, closeHostedGeneration, @@ -63,6 +62,7 @@ import { openHostedGeneration, releaseCloudConnection, releaseUncommittedLease, + verifyUncommittedGenerationCleanup, type CloudConnectionRelease, type HostedGenerationClose, type OpenedHostedGeneration, @@ -390,8 +390,10 @@ async function cleanUncommittedGeneration( ): Promise { const record = readCloudConnectionQuietly(location); if (!record || record.phase === 'committed') return; - assertUncommittedGenerationAccess(record, access); - const closed = await timings.measure('cleanup', () => closeWithin(params, location, access)); + const closed = await timings.measure('cleanup', async () => { + const proven = await verifyUncommittedGenerationCleanup(location, record, access); + return await closeWithin(params, location, access, proven); + }); if (closed.kind !== 'released') throw leftoverCleanupFailure(closed.cause); forgetUncommittedGeneration(location, record); } @@ -424,6 +426,7 @@ async function closeWithin( params: ConnectionCommandParams, location: ConnectionLocation, access: HostedCloudAccess, + proven?: { id: string; active: boolean }, ): Promise { const abandoned = new AbortController(); const close = () => @@ -432,6 +435,7 @@ async function closeWithin( access, () => releaseLease(params, location, abandoned.signal), abandoned.signal, + proven, ); const outcome = await settleWithin(close, CLEANUP_TIMEOUT_MS).catch((error: unknown) => ({ kind: 'failed' as const, diff --git a/src/cli/connection/cloud-connect.ts b/src/cli/connection/cloud-connect.ts index 914fbbd1a1..732d9626c5 100644 --- a/src/cli/connection/cloud-connect.ts +++ b/src/cli/connection/cloud-connect.ts @@ -176,19 +176,29 @@ export async function closeHostedGeneration( access: HostedCloudAccess, releaseLease: () => Promise, abandoned: AbortSignal, + proven?: { id: string; active: boolean }, ): Promise { const record = readCloudConnectionQuietly(location); if (!record || record.phase === 'committed') return { kind: 'released' }; + if (record.accountBinding === undefined && !record.brokerReleased && !proven) { + throw cloudConnectionUnavailable(CLOUD_CONNECTION_REASONS.allocationUnconfirmed.reason); + } if (record.phase === 'pending') { // The fence goes up before any cleanup step: no command uses the candidate state after this. writeGeneration(location, 'pending', 'close', { ...record, phase: 'closing', rollback: true }); } + const endBroker = () => + proven + ? proven.active + ? deleteCloudSession(access, proven.id) + : Promise.resolve() + : endBrokerSession(access, record); const [lease, broker] = await Promise.allSettled([ releaseLease(), // A confirmed end is saved at once, so a later absence of that booking counts as released. record.brokerReleased ? Promise.resolve() - : endBrokerSession(access, record).then(() => { + : endBroker().then(() => { // The caller has left the lock: a late confirmation is logged below, never saved. if (abandoned.aborted) return; const current = readCloudConnectionQuietly(location); @@ -244,7 +254,7 @@ const UNBOUND_RELEASED_HINT = `The hosted session has ended, but its record name * lookup proves the owner, so only a record that names its account lets that account release the * lease; an unbound one is left to `disconnect --forget`. */ -export function assertUncommittedGenerationAccess( +function assertUncommittedGenerationAccess( record: CloudConnectionRecord, access: HostedCloudAccess, ): void { @@ -257,6 +267,25 @@ export function assertUncommittedGenerationAccess( assertCloudConnectionCaller(record, access); } +/** + * Verifies pairing and broker ownership before an unfinished generation reaches attachment + * teardown. An unbound booking proves its owner through the broker lookup first. + */ +export async function verifyUncommittedGenerationCleanup( + location: ConnectionLocation, + record: CloudConnectionRecord, + access: HostedCloudAccess, +): Promise<{ id: string; active: boolean } | undefined> { + assertUncommittedGenerationAccess(record, access); + cloudBindingForTeardown(location, readRemoteConnectionState(location), record); + if (record.accountBinding !== undefined || record.brokerReleased) return undefined; + const found = await lookupRecordedAllocation(access, record); + record.accountBinding = hostedCloudAccountBinding(access); + record.id = found.id; + writeCloudConnection(location, record); + return found; +} + /** * Removes what an uncommitted generation left locally. The caller holds the connection lock; a * newer generation's files are never touched. From 1efe60152092d0f54e74b68a194d7bc62dd49bf9 Mon Sep 17 00:00:00 2001 From: Suneeth12 Date: Sun, 6 Dec 2026 13:55:00 +0530 Subject: [PATCH 4/6] fix(cli): clear empty legacy pending reservation on canonical not_found --- .../cli-cloud-record-recovery.test.ts | 94 +++++++++++++++++++ src/cli/commands/connection-hosted.ts | 16 +++- src/cli/connection/cloud-connect.ts | 45 +++++++-- 3 files changed, 145 insertions(+), 10 deletions(-) diff --git a/src/__tests__/cli-cloud-record-recovery.test.ts b/src/__tests__/cli-cloud-record-recovery.test.ts index 191206501b..59d517b500 100644 --- a/src/__tests__/cli-cloud-record-recovery.test.ts +++ b/src/__tests__/cli-cloud-record-recovery.test.ts @@ -383,3 +383,97 @@ test('connect on an expired unbound unfinished proxy-front booking releases its expect(replaced.calls.map(({ command }) => command)).toContain('lease_release'); expect(owned.broker.mock.calls.map(([, init]) => init.method)).not.toContain('DELETE'); }); + +test.each([false, true])( + 'connect (force=%s) clears an ID-less legacy pending reservation on canonical not_found and continues', + async (force) => { + const env = cloudEnv(); + const location = locationOf(env); + const reservation = writeLegacyPending(env); + const broker = stubCloudApi(); + broker.mockResolvedValueOnce(Response.json({ error: 'not_found' }, { status: 404 })); + + const result = await runCliCapture(force ? [...connectArgs, '--force'] : connectArgs, { env }); + expect(result.code, result.stdout).toBeNull(); + expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET', 'POST']); + const committed = readCloudConnection(location); + expect(committed?.phase).toBe('committed'); + expect(committed?.generation).not.toBe(reservation.generation); + }, +); + +test.each([ + { + label: '500 lookup error', + setup: () => {}, + response: () => new Response(null, { status: 500 }), + }, + { + label: 'non-canonical 404', + setup: () => {}, + response: () => Response.json({ error: 'other' }, { status: 404 }), + }, + { + label: 'record with allocation ID', + setup: (location: ReturnType) => { + writeCloudConnection(location, { ...readCloudConnection(location)!, id: hostedDevice.id }); + }, + response: () => Response.json({ error: 'not_found' }, { status: 404 }), + }, + { + label: 'record with hostedLeaseId', + setup: (location: ReturnType) => { + writeCloudConnection(location, { + ...readCloudConnection(location)!, + hostedLeaseId: 'proposed-lease-id', + }); + }, + response: () => Response.json({ error: 'not_found' }, { status: 404 }), + }, + { + label: 'reservation with attachment file', + setup: (location: ReturnType) => { + fs.writeFileSync(cloudAttachmentPath(location), '{}', { mode: 0o600 }); + }, + response: () => Response.json({ error: 'not_found' }, { status: 404 }), + }, + { + label: 'broker allocation ID mismatch', + setup: (location: ReturnType) => { + writeCloudConnection(location, { ...readCloudConnection(location)!, id: hostedDevice.id }); + }, + response: () => Response.json({ id: '00000000-0000-4000-8000-000000000099', state: 'running' }), + }, +])( + 'connect keeps refusing an unbound pending reservation on $label', + async ({ setup, response }) => { + const env = cloudEnv(); + const location = locationOf(env); + const reservation = writeLegacyPending(env); + setup(location); + const broker = stubCloudApi(); + broker.mockResolvedValueOnce(response()); + + const refused = await runCliCapture(connectArgs, { env }); + expect(refused.code).toBe(1); + expect(JSON.parse(refused.stdout).error.details.reason).toBe( + 'cloud_connection_allocation_unconfirmed', + ); + expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET']); + expect(readCloudConnection(location)?.generation).toBe(reservation.generation); + }, +); + +test('connect ends an active broker allocation found for an ID-less legacy pending reservation', async () => { + const env = cloudEnv(); + const location = locationOf(env); + const reservation = writeLegacyPending(env); + const broker = stubCloudApi(); + broker.mockResolvedValueOnce(Response.json({ id: hostedDevice.id, state: 'running' })); + broker.mockResolvedValueOnce(new Response(null, { status: 204 })); + + const result = await runCliCapture(connectArgs, { env }); + expect(result.code, result.stdout).toBeNull(); + expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET', 'DELETE', 'POST']); + expect(readCloudConnection(location)?.generation).not.toBe(reservation.generation); +}); diff --git a/src/cli/commands/connection-hosted.ts b/src/cli/commands/connection-hosted.ts index 20e0835a77..2937bf8959 100644 --- a/src/cli/commands/connection-hosted.ts +++ b/src/cli/commands/connection-hosted.ts @@ -48,6 +48,7 @@ import { cloudSessionEnded, readCloudConnection, refuseContendedConnection, + removeCloudConnection, withConnectionLock, writeCloudConnection, type CloudConnectionRecord, @@ -390,11 +391,18 @@ async function cleanUncommittedGeneration( ): Promise { const record = readCloudConnectionQuietly(location); if (!record || record.phase === 'committed') return; - const closed = await timings.measure('cleanup', async () => { - const proven = await verifyUncommittedGenerationCleanup(location, record, access); - return await closeWithin(params, location, access, proven); + const outcome = await timings.measure('cleanup', async () => { + const plan = await verifyUncommittedGenerationCleanup(location, record, access); + if (plan.kind === 'clear-reservation') return plan; + return await closeWithin(params, location, access, plan.proven); }); - if (closed.kind !== 'released') throw leftoverCleanupFailure(closed.cause); + if (outcome.kind === 'clear-reservation') { + if (readCloudConnectionQuietly(location)?.generation === record.generation) { + removeCloudConnection(location); + } + return; + } + if (outcome.kind !== 'released') throw leftoverCleanupFailure(outcome.cause); forgetUncommittedGeneration(location, record); } diff --git a/src/cli/connection/cloud-connect.ts b/src/cli/connection/cloud-connect.ts index 732d9626c5..009864b8c5 100644 --- a/src/cli/connection/cloud-connect.ts +++ b/src/cli/connection/cloud-connect.ts @@ -9,6 +9,7 @@ import { } from '@agent-device/remote/remote-connection-state'; import { AppError, errorMessage } from '@agent-device/kernel/errors'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { lstatIfPresent } from '@agent-device/host-kit/file'; import { settleWithin } from '@agent-device/host-kit/settle-within'; import { createCloudSession, @@ -24,6 +25,7 @@ import type { ReceiptTiming } from './connect-timings.ts'; import { ReadyTarget, type ConnectBudget } from './hosted-readiness.ts'; import { assertCloudRecordSession, + cloudAttachmentPath, samePairedBooking, cloudConnectionUnavailable, CLOUD_CONNECTION_DROP_CREDENTIAL_HINT, @@ -267,23 +269,54 @@ function assertUncommittedGenerationAccess( assertCloudConnectionCaller(record, access); } +function hasAttachmentEntry(location: ConnectionLocation): boolean { + try { + return lstatIfPresent(cloudAttachmentPath(location)) !== undefined; + } catch { + return true; + } +} + /** * Verifies pairing and broker ownership before an unfinished generation reaches attachment - * teardown. An unbound booking proves its owner through the broker lookup first. + * teardown. An unbound booking proves its owner through the broker lookup first; a reservation + * with no allocation ID, lease ID, saved state, or attachment clears on canonical `not_found`. */ export async function verifyUncommittedGenerationCleanup( location: ConnectionLocation, record: CloudConnectionRecord, access: HostedCloudAccess, -): Promise<{ id: string; active: boolean } | undefined> { +): Promise< + { kind: 'close'; proven?: { id: string; active: boolean } } | { kind: 'clear-reservation' } +> { assertUncommittedGenerationAccess(record, access); - cloudBindingForTeardown(location, readRemoteConnectionState(location), record); - if (record.accountBinding !== undefined || record.brokerReleased) return undefined; - const found = await lookupRecordedAllocation(access, record); + const state = readRemoteConnectionState(location); + cloudBindingForTeardown(location, state, record); + if (record.accountBinding !== undefined || record.brokerReleased) return { kind: 'close' }; + let found: { id: string; active: boolean } | undefined; + try { + found = await lookupCloudSession(access, record.generation); + } catch { + throw cloudConnectionUnavailable(CLOUD_CONNECTION_REASONS.allocationUnconfirmed.reason); + } + if (!found) { + if ( + record.id === undefined && + record.hostedLeaseId === undefined && + state === null && + !hasAttachmentEntry(location) + ) { + return { kind: 'clear-reservation' }; + } + throw cloudConnectionUnavailable(CLOUD_CONNECTION_REASONS.allocationUnconfirmed.reason); + } + if (record.id !== undefined && record.id !== found.id) { + throw cloudConnectionUnavailable(CLOUD_CONNECTION_REASONS.allocationUnconfirmed.reason); + } record.accountBinding = hostedCloudAccountBinding(access); record.id = found.id; writeCloudConnection(location, record); - return found; + return { kind: 'close', proven: found }; } /** From 0590d8acd894954dd1619e916d44c1512299cc92 Mon Sep 17 00:00:00 2001 From: Suneeth12 Date: Sun, 6 Dec 2026 15:58:17 +0530 Subject: [PATCH 5/6] fix(cli): confirm saved state absence before clearing legacy reservations --- .../remote/src/remote-connection-state.ts | 23 ++- .../cli-cloud-limrun-attachment.test.ts | 76 +++---- .../cli-cloud-record-recovery.test.ts | 133 ++++++++----- .../cli-cloud-session-identity.test.ts | 188 +++++++----------- src/cli/commands/connection-hosted.ts | 2 +- src/cli/connection/active-connection.ts | 11 +- src/cli/connection/cloud-access.ts | 24 +-- src/cli/connection/cloud-connect.ts | 97 +++++---- .../cloud-connection-record.test.ts | 95 ++++----- src/cli/connection/cloud-connection-record.ts | 38 ++-- 10 files changed, 338 insertions(+), 349 deletions(-) diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index f172848e39..f5d842372f 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -274,6 +274,18 @@ export function readRemoteConnectionState(options: { stateDir: string; session: string; }): RemoteConnectionState | null { + const observed = observeRemoteConnectionState(options); + return observed.kind === 'valid' ? observed.state : null; +} + +export function observeRemoteConnectionState(options: { + stateDir: string; + session: string; +}): + | { kind: 'absent' } + | { kind: 'invalid' } + | { kind: 'unknown' } + | { kind: 'valid'; state: RemoteConnectionState } { const recordsDir = remoteConnectionRecordsDir(options.stateDir); const canonical = canonicalRemoteConnectionStatePath(recordsDir, options.session); // The older path is read first. A move links the session's own path before it retires the older @@ -295,11 +307,12 @@ export function readRemoteConnectionState(options: { } return observedRemoteConnectionState(options.session, canonical, file.record); } + if (legacyPath !== canonical && legacy.kind === 'unknown') return { kind: 'unknown' }; return legacy.kind === 'owned' && legacy.session === options.session && isMovableLegacyRecord(recordsDir, legacyPath, legacy) ? observedRemoteConnectionState(options.session, legacyPath, legacy.record) - : null; + : { kind: 'absent' }; } /** @@ -372,10 +385,12 @@ function observedRemoteConnectionState( session: string, recordPath: string, record: Record, -): RemoteConnectionState | null { - if (isRemoteConnectionState(record)) return normalizeStoredProvider(record); +): { kind: 'invalid' } | { kind: 'valid'; state: RemoteConnectionState } { + if (isRemoteConnectionState(record)) { + return { kind: 'valid', state: normalizeStoredProvider(record) }; + } warnInvalidRecord(session, recordPath); - return null; + return { kind: 'invalid' }; } function normalizeStoredProvider(record: RemoteConnectionState): RemoteConnectionState { diff --git a/src/__tests__/cli-cloud-limrun-attachment.test.ts b/src/__tests__/cli-cloud-limrun-attachment.test.ts index 4f655567aa..155ae8a2c1 100644 --- a/src/__tests__/cli-cloud-limrun-attachment.test.ts +++ b/src/__tests__/cli-cloud-limrun-attachment.test.ts @@ -303,56 +303,17 @@ test('disconnect preserves recovery when a startup owns the lock before publishi expect(mock.mock.calls.filter(([, init]) => init.method === 'DELETE')).toHaveLength(1); }); -test.each(['stale-v1-login', 'unbound'] as const)( - 'local-only sweep of an expired Limrun booking (%s) removes its attachment without stopping its daemon', - async (mode) => { - const env = limrunEnv('current'); - const location = locationOf(env); - const broker = stubCloudApi(); - broker.mockResolvedValueOnce(Response.json(limrunLease('ios'), { status: 201 })); - expect((await runCliCapture(args('ios'), { env })).code).toBeNull(); - writeHostedDaemonRegistration(location); - const { accountBinding, ...unboundRecord } = readCloudConnection(location)!; - writeCloudConnection(location, { - ...(mode === 'unbound' ? unboundRecord : { ...unboundRecord, accountBinding }), - deadlineAt: new Date(0).toISOString(), - }); - let sweepEnv: Record = env; - if (mode === 'stale-v1-login') { - const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth'); - fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); - fs.writeFileSync( - path.join(authDir, 'cli-session.json'), - JSON.stringify({ - version: 1, - id: 'stale-login', - cloudBaseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL, - refreshCredential: 'stale-refresh-credential', - createdAt: new Date().toISOString(), - }), - { mode: 0o600 }, - ); - sweepEnv = { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }; - } - - await runCliCapture(['connection', 'status', '--session', location.session, '--json'], { - env: sweepEnv, - }); - - expect(stop).not.toHaveBeenCalled(); - expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); - }, -); - -test('forget with a stale v1 login clears a paired Limrun booking locally without stopping its daemon', async () => { +async function bookLimrunWithDaemon() { const env = limrunEnv('current'); const location = locationOf(env); const broker = stubCloudApi(); broker.mockResolvedValueOnce(Response.json(limrunLease('ios'), { status: 201 })); expect((await runCliCapture(args('ios'), { env })).code).toBeNull(); - const record = readCloudConnection(location)!; - const daemonDir = hostedPluginDaemonDir(location, record); writeHostedDaemonRegistration(location); + return { env, location }; +} + +function writeStaleV1Login(env: ReturnType): void { const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth'); fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); fs.writeFileSync( @@ -366,6 +327,33 @@ test('forget with a stale v1 login clears a paired Limrun booking locally withou }), { mode: 0o600 }, ); +} + +test.each(['stale-v1-login', 'unbound'] as const)( + 'local-only sweep of an expired Limrun booking (%s) removes its attachment without stopping its daemon', + async (mode) => { + const { env, location } = await bookLimrunWithDaemon(); + const record = readCloudConnection(location)!; + const { accountBinding: _unbound, ...unbound } = record; + writeCloudConnection(location, { + ...(mode === 'unbound' ? unbound : record), + deadlineAt: new Date(0).toISOString(), + }); + if (mode === 'stale-v1-login') writeStaleV1Login(env); + + await runCliCapture(['connection', 'status', '--session', location.session, '--json'], { + env: mode === 'stale-v1-login' ? { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined } : env, + }); + + expect(stop).not.toHaveBeenCalled(); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + }, +); + +test('forget with a stale v1 login clears a paired Limrun booking locally without stopping its daemon', async () => { + const { env, location } = await bookLimrunWithDaemon(); + const daemonDir = hostedPluginDaemonDir(location, readCloudConnection(location)!); + writeStaleV1Login(env); const forgotten = await runCliCapture( ['disconnect', '--forget', '--session', location.session, '--json'], diff --git a/src/__tests__/cli-cloud-record-recovery.test.ts b/src/__tests__/cli-cloud-record-recovery.test.ts index 59d517b500..9a74cb78b4 100644 --- a/src/__tests__/cli-cloud-record-recovery.test.ts +++ b/src/__tests__/cli-cloud-record-recovery.test.ts @@ -295,18 +295,13 @@ async function bookExpiredUnboundUnfinishedProxyFront(phase: 'pending' | 'closin const location = locationOf(env); const front = withLeaseAllocation(); const broker = stubCloudApi(proxyFrontDevice); - expect((await runCliCapture(connectArgs, { env, sendToDaemon: front })).code).toBeNull(); - expect( - ( - await runCliCapture( - ['open', 'com.apple.Preferences', '--session', location.session, '--json'], - { - env, - sendToDaemon: front, - }, - ) - ).code, - ).toBeNull(); + const connected = await runCliCapture(connectArgs, { env, sendToDaemon: front }); + expect(connected.code).toBeNull(); + const opened = await runCliCapture( + ['open', 'com.apple.Preferences', '--session', location.session, '--json'], + { env, sendToDaemon: front }, + ); + expect(opened.code).toBeNull(); const { accountBinding: _unbound, ...record } = readCloudConnection(location)!; writeCloudConnection(location, { ...record, @@ -327,10 +322,7 @@ test.each([ 'connect (force=$force) on an expired unbound $phase proxy-front booking refuses another account before any lease teardown', async ({ phase, force }) => { const { env, location, front, broker } = await bookExpiredUnboundUnfinishedProxyFront(phase); - broker.mockImplementation(async (_url: URL, init: RequestInit) => { - if (init.method === 'GET') return Response.json({ error: 'not_found' }, { status: 404 }); - return new Response(null, { status: 204 }); - }); + broker.mockResolvedValueOnce(Response.json({ error: 'not_found' }, { status: 404 })); const args = force ? [...connectArgs, '--force'] : connectArgs; const refused = await runCliCapture(args, { @@ -366,15 +358,7 @@ test('connect on an expired unbound unfinished proxy-front booking releases its expect(unpaired.broker).not.toHaveBeenCalled(); const owned = await bookExpiredUnboundUnfinishedProxyFront('pending'); - owned.broker.mockImplementation(async (url: URL, init: RequestInit) => { - if (init.method === 'GET' && url.pathname === '/v1/sessions') { - return Response.json({ id: proxyFrontDevice.id, state: 'settled' }); - } - if (init.method === 'POST' && url.pathname === '/v1/sessions') { - return Response.json(proxyFrontDevice, { status: 201 }); - } - return new Response(null, { status: 204 }); - }); + owned.broker.mockResolvedValueOnce(Response.json({ id: proxyFrontDevice.id, state: 'settled' })); const replaced = await runCliCapture(connectArgs, { env: owned.env, sendToDaemon: owned.front, @@ -402,46 +386,37 @@ test.each([false, true])( }, ); -test.each([ - { - label: '500 lookup error', - setup: () => {}, - response: () => new Response(null, { status: 500 }), - }, +test.each<{ + label: string; + setup?: (location: ReturnType) => void; + response?: () => Response; +}>([ + { label: '500 lookup error', response: () => new Response(null, { status: 500 }) }, { label: 'non-canonical 404', - setup: () => {}, response: () => Response.json({ error: 'other' }, { status: 404 }), }, { label: 'record with allocation ID', - setup: (location: ReturnType) => { - writeCloudConnection(location, { ...readCloudConnection(location)!, id: hostedDevice.id }); - }, - response: () => Response.json({ error: 'not_found' }, { status: 404 }), + setup: (location) => + writeCloudConnection(location, { ...readCloudConnection(location)!, id: hostedDevice.id }), }, { label: 'record with hostedLeaseId', - setup: (location: ReturnType) => { + setup: (location) => writeCloudConnection(location, { ...readCloudConnection(location)!, hostedLeaseId: 'proposed-lease-id', - }); - }, - response: () => Response.json({ error: 'not_found' }, { status: 404 }), + }), }, { label: 'reservation with attachment file', - setup: (location: ReturnType) => { - fs.writeFileSync(cloudAttachmentPath(location), '{}', { mode: 0o600 }); - }, - response: () => Response.json({ error: 'not_found' }, { status: 404 }), + setup: (location) => fs.writeFileSync(cloudAttachmentPath(location), '{}', { mode: 0o600 }), }, { label: 'broker allocation ID mismatch', - setup: (location: ReturnType) => { - writeCloudConnection(location, { ...readCloudConnection(location)!, id: hostedDevice.id }); - }, + setup: (location) => + writeCloudConnection(location, { ...readCloudConnection(location)!, id: hostedDevice.id }), response: () => Response.json({ id: '00000000-0000-4000-8000-000000000099', state: 'running' }), }, ])( @@ -450,9 +425,11 @@ test.each([ const env = cloudEnv(); const location = locationOf(env); const reservation = writeLegacyPending(env); - setup(location); + setup?.(location); const broker = stubCloudApi(); - broker.mockResolvedValueOnce(response()); + broker.mockResolvedValueOnce( + response ? response() : Response.json({ error: 'not_found' }, { status: 404 }), + ); const refused = await runCliCapture(connectArgs, { env }); expect(refused.code).toBe(1); @@ -477,3 +454,61 @@ test('connect ends an active broker allocation found for an ID-less legacy pendi expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET', 'DELETE', 'POST']); expect(readCloudConnection(location)?.generation).not.toBe(reservation.generation); }); + +test.each([ + { session: 'cloud-qa', force: false }, + { session: 'cloud-qa', force: true }, + { session: 'Cloud-QA', force: false }, +])( + 'connect (session=$session, force=$force) refuses an ID-less pending reservation beside a legacy-transport saved connection', + async ({ session, force }) => { + const env = { ...cloudEnv(), AGENT_DEVICE_SESSION: session }; + const location = locationOf(env); + const reservation = writeLegacyPending(env); + const recordsDir = path.join(location.stateDir, 'remote-connections'); + fs.mkdirSync(recordsDir, { recursive: true, mode: 0o700 }); + const legacyStatePath = path.join(recordsDir, `${session}.json`); + fs.writeFileSync( + legacyStatePath, + JSON.stringify({ + version: 1, + session, + remoteConfigPath: path.join( + location.stateDir, + 'remote-connections', + 'generated', + 'legacy.json', + ), + remoteConfigHash: 'hash', + tenant: 'tenant', + runId: 'run-1', + leaseId: 'legacy-lease-id', + cloudSession: { + id: '00000000-0000-4000-8000-000000000077', + baseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL, + vendor: 'limrun', + transport: 'limrun', + deadlineAt: new Date(Date.now() + 60_000).toISOString(), + generation: 'other-generation', + }, + connectedAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }), + { mode: 0o600 }, + ); + const broker = stubCloudApi(); + broker.mockResolvedValueOnce(Response.json({ error: 'not_found' }, { status: 404 })); + + const args = force + ? [...connectArgs, '--session', session, '--force'] + : [...connectArgs, '--session', session]; + const refused = await runCliCapture(args, { env }); + expect(refused.code).toBe(1); + expect(JSON.parse(refused.stdout).error.details.reason).toBe( + 'cloud_connection_allocation_unconfirmed', + ); + expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET']); + expect(readCloudConnection(location)?.generation).toBe(reservation.generation); + expect(fs.existsSync(legacyStatePath)).toBe(true); + }, +); diff --git a/src/__tests__/cli-cloud-session-identity.test.ts b/src/__tests__/cli-cloud-session-identity.test.ts index bf40062e4e..519a7366f4 100644 --- a/src/__tests__/cli-cloud-session-identity.test.ts +++ b/src/__tests__/cli-cloud-session-identity.test.ts @@ -700,20 +700,25 @@ function expireUnbound( }); } -test.each( - sessions.flatMap((session) => - (['stale-v1', 'malformed'] as const).map((kind) => [session, kind] as const), - ), -)( - 'an unverifiable (%s / %s) login sweeps expired proxy-front files locally without saved credentials', - async (session, kind) => { - const { env, front, location } = await bookProxyFront(session); - expire(location); - if (kind === 'stale-v1') writeStaleV1Login(env); - else writeRawLogin(env.AGENT_DEVICE_STATE_DIR, '{'); - +async function assertLocalSweepWithLogin( + session: string, + kind: 'stale-v1' | 'malformed' | 'unreadable', + baseUrl?: string, +): Promise { + const { env, front, location } = await bookProxyFront(session); + expire(location); + const sessionFile = + kind === 'stale-v1' + ? writeStaleV1Login(env) + : writeRawLogin(env.AGENT_DEVICE_STATE_DIR, kind === 'malformed' ? '{' : '{"version":2}'); + if (kind === 'unreadable') fs.chmodSync(sessionFile, 0o000); + try { const result = await runCliCapture(['connection', 'status', '--session', session, '--json'], { - env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }, + env: { + ...env, + AGENT_DEVICE_CLOUD_API_KEY: undefined, + ...(baseUrl ? { AGENT_DEVICE_CLOUD_BASE_URL: baseUrl } : {}), + }, sendToDaemon: front, }); expect(JSON.parse(result.stdout).error.details.reason).toBe( @@ -721,38 +726,28 @@ test.each( ); expect(result.calls).toEqual([]); expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + } finally { + if (kind === 'unreadable') fs.chmodSync(sessionFile, 0o600); + } +} + +test.each([ + ...sessions.flatMap((session) => + (['stale-v1', 'malformed'] as const).map((kind) => [session, kind, undefined] as const), + ), + ['cloud-qa', 'stale-v1', 'https://other-cloud.example'] as const, + ['cloud-qa', 'malformed', 'https://other-cloud.example'] as const, +])( + 'an unverifiable (%s / %s / baseUrl=%s) login sweeps expired proxy-front files locally without saved credentials', + async (session, kind, baseUrl) => { + await assertLocalSweepWithLogin(session, kind, baseUrl); }, ); -test.skipIf(process.platform === 'win32')( - 'an unreadable saved login sweeps expired proxy-front files locally without saved credentials, even with another base URL', - async () => { - for (const baseUrl of [undefined, 'https://other-cloud.example']) { - const { env, front, location } = await bookProxyFront('cloud-qa'); - expire(location); - const sessionFile = writeRawLogin(env.AGENT_DEVICE_STATE_DIR, '{"version":2}'); - fs.chmodSync(sessionFile, 0o000); - try { - const result = await runCliCapture( - ['connection', 'status', '--session', 'cloud-qa', '--json'], - { - env: { - ...env, - AGENT_DEVICE_CLOUD_API_KEY: undefined, - ...(baseUrl ? { AGENT_DEVICE_CLOUD_BASE_URL: baseUrl } : {}), - }, - sendToDaemon: front, - }, - ); - expect(JSON.parse(result.stdout).error.details.reason).toBe( - 'cloud_connection_credential_mismatch', - ); - expect(result.calls).toEqual([]); - expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); - } finally { - fs.chmodSync(sessionFile, 0o600); - } - } +test.skipIf(process.platform === 'win32').each([undefined, 'https://other-cloud.example'])( + 'an unreadable saved login (baseUrl=%s) sweeps expired proxy-front files locally without saved credentials', + async (baseUrl) => { + await assertLocalSweepWithLogin('cloud-qa', 'unreadable', baseUrl); }, ); @@ -818,33 +813,6 @@ test.each(sessions)( }, ); -test.each(['malformed', 'stale-v1'] as const)( - 'an unverifiable (%s) login without an API key sweeps an expired booking even with another AGENT_DEVICE_CLOUD_BASE_URL', - async (kind) => { - const { env, front, location } = await bookProxyFront('cloud-qa'); - expire(location); - if (kind === 'stale-v1') writeStaleV1Login(env); - else writeRawLogin(env.AGENT_DEVICE_STATE_DIR, '{'); - - const result = await runCliCapture( - ['connection', 'status', '--session', 'cloud-qa', '--json'], - { - env: { - ...env, - AGENT_DEVICE_CLOUD_API_KEY: undefined, - AGENT_DEVICE_CLOUD_BASE_URL: 'https://other-cloud.example', - }, - sendToDaemon: front, - }, - ); - expect(JSON.parse(result.stdout).error.details.reason).toBe( - 'cloud_connection_credential_mismatch', - ); - expect(result.calls).toEqual([]); - expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); - }, -); - test('a verified v2 login with another AGENT_DEVICE_CLOUD_BASE_URL still does not sweep an expired booking', async () => { const { env, front, location } = await bookProxyFront('cloud-qa'); expire(location); @@ -866,12 +834,7 @@ test.each(sessions)( async (session) => { const { env, front, fetchMock, location } = await bookProxyFront(session); expireUnbound(location); - fetchMock.mockImplementation(async (url: URL, init: RequestInit) => { - if (init.method === 'GET' && url.pathname === '/v1/sessions') { - return Response.json({ id: proxyFrontDevice.id, state: 'settled' }); - } - return new Response(null, { status: 204 }); - }); + fetchMock.mockResolvedValueOnce(Response.json({ id: proxyFrontDevice.id, state: 'settled' })); const disconnected = await runCliCapture(['disconnect', '--session', session, '--json'], { env, @@ -887,15 +850,9 @@ test.each(sessions)( test('connect cloud --force and unfinished disconnect keep an expired unbound proxy-front sidecar while other sessions sweep locally', async () => { const forceCase = await bookProxyFront('cloud-qa'); expireUnbound(forceCase.location); - forceCase.fetchMock.mockImplementation(async (url: URL, init: RequestInit) => { - if (init.method === 'GET' && url.pathname === '/v1/sessions') { - return Response.json({ id: proxyFrontDevice.id, state: 'settled' }); - } - if (init.method === 'POST' && url.pathname === '/v1/sessions') { - return Response.json(proxyFrontDevice, { status: 201 }); - } - return new Response(null, { status: 204 }); - }); + forceCase.fetchMock.mockResolvedValueOnce( + Response.json({ id: proxyFrontDevice.id, state: 'settled' }), + ); const replaced = await runCliCapture([...connectArgs, '--session', 'cloud-qa', '--force'], { env: forceCase.env, sendToDaemon: forceCase.front, @@ -905,12 +862,9 @@ test('connect cloud --force and unfinished disconnect keep an expired unbound pr const pendingCase = await bookProxyFront('cloud-qa'); expireUnbound(pendingCase.location, { phase: 'pending' }); - pendingCase.fetchMock.mockImplementation(async (url: URL, init: RequestInit) => { - if (init.method === 'GET' && url.pathname === '/v1/sessions') { - return Response.json({ id: proxyFrontDevice.id, state: 'settled' }); - } - return new Response(null, { status: 204 }); - }); + pendingCase.fetchMock.mockResolvedValueOnce( + Response.json({ id: proxyFrontDevice.id, state: 'settled' }), + ); const refused = await runCliCapture(['disconnect', '--session', 'cloud-qa', '--json'], { env: pendingCase.env, sendToDaemon: async (req) => @@ -934,43 +888,34 @@ test('connect cloud --force and unfinished disconnect keep an expired unbound pr }); test('forget recovers an orphan attachment with no identity source when cli-session.json is malformed or unreadable', async () => { - const malformedCase = await book('cloud-qa', 'api-key'); - removeRemoteConnectionState(malformedCase.location); - const recordFile = path.join(cloudConnectionDir(malformedCase.location), 'record.json'); - fs.writeFileSync(recordFile, '{'); - writeRawLogin(malformedCase.env.AGENT_DEVICE_STATE_DIR, '{'); - const forgotten = await runCliCapture( - ['disconnect', '--forget', '--session', 'cloud-qa', '--json'], - { env: { ...malformedCase.env, AGENT_DEVICE_CLOUD_API_KEY: undefined } }, - ); - expect(forgotten.code, forgotten.stdout).toBeNull(); - expect(JSON.parse(forgotten.stdout).data).toMatchObject({ forgotten: true }); - expect(fs.existsSync(recordFile)).toBe(false); - expect(fs.existsSync(cloudAttachmentPath(malformedCase.location))).toBe(false); - - if (process.platform === 'win32') return; - const unreadableCase = await book('cloud-qa', 'api-key'); - removeRemoteConnectionState(unreadableCase.location); - const unreadableRecord = path.join(cloudConnectionDir(unreadableCase.location), 'record.json'); - fs.writeFileSync(unreadableRecord, '{'); - const sessionFile = writeRawLogin(unreadableCase.env.AGENT_DEVICE_STATE_DIR, '{"version":2}'); - fs.chmodSync(sessionFile, 0o000); - try { - const recovered = await runCliCapture( - ['disconnect', '--forget', '--session', 'cloud-qa', '--json'], - { env: { ...unreadableCase.env, AGENT_DEVICE_CLOUD_API_KEY: undefined } }, + for (const unreadable of process.platform === 'win32' ? [false] : [false, true]) { + const { env, location } = await book('cloud-qa', 'api-key'); + removeRemoteConnectionState(location); + const recordFile = path.join(cloudConnectionDir(location), 'record.json'); + fs.writeFileSync(recordFile, '{'); + const sessionFile = writeRawLogin( + env.AGENT_DEVICE_STATE_DIR, + unreadable ? '{"version":2}' : '{', ); - expect(recovered.code, recovered.stdout).toBeNull(); - expect(JSON.parse(recovered.stdout).data).toMatchObject({ forgotten: true }); - expect(fs.existsSync(unreadableRecord)).toBe(false); - expect(fs.existsSync(cloudAttachmentPath(unreadableCase.location))).toBe(false); - } finally { - fs.chmodSync(sessionFile, 0o600); + if (unreadable) fs.chmodSync(sessionFile, 0o000); + try { + const forgotten = await runCliCapture( + ['disconnect', '--forget', '--session', 'cloud-qa', '--json'], + { env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined } }, + ); + expect(forgotten.code, forgotten.stdout).toBeNull(); + expect(JSON.parse(forgotten.stdout).data).toMatchObject({ forgotten: true }); + expect(fs.existsSync(recordFile)).toBe(false); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + } finally { + if (unreadable) fs.chmodSync(sessionFile, 0o600); + } } }); test('plain disconnect with a malformed cli-session.json keeps reporting cloud_api_key_required', async () => { const { env, fetchMock, location } = await book('cloud-qa', 'api-key'); + expire(location); writeRawLogin(env.AGENT_DEVICE_STATE_DIR, '{'); const refused = await runCliCapture(['disconnect', '--session', 'cloud-qa', '--json'], { @@ -980,4 +925,5 @@ test('plain disconnect with a malformed cli-session.json keeps reporting cloud_a expect(JSON.parse(refused.stdout).error.details.reason).toBe('cloud_api_key_required'); expect(brokerCalls(fetchMock)).toEqual([]); expect(readCloudConnection(location)?.id).toBe(hostedDevice.id); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(true); }); diff --git a/src/cli/commands/connection-hosted.ts b/src/cli/commands/connection-hosted.ts index 2937bf8959..249acd8e9d 100644 --- a/src/cli/commands/connection-hosted.ts +++ b/src/cli/commands/connection-hosted.ts @@ -392,7 +392,7 @@ async function cleanUncommittedGeneration( const record = readCloudConnectionQuietly(location); if (!record || record.phase === 'committed') return; const outcome = await timings.measure('cleanup', async () => { - const plan = await verifyUncommittedGenerationCleanup(location, record, access); + const plan = await verifyUncommittedGenerationCleanup(location, record, access, params.host); if (plan.kind === 'clear-reservation') return plan; return await closeWithin(params, location, access, plan.proven); }); diff --git a/src/cli/connection/active-connection.ts b/src/cli/connection/active-connection.ts index 31dd48446e..422dbe13a3 100644 --- a/src/cli/connection/active-connection.ts +++ b/src/cli/connection/active-connection.ts @@ -123,15 +123,10 @@ function admitsExpiredBooking( record: CloudConnectionRecord, teardownSession?: string, ): ExpiredBookingAdmission | null { - if ( - teardownSession && - record.session === teardownSession && - record.accountBinding === undefined - ) { - return null; - } try { - return admitHostedCaller({ stateDir, env, booking: record }, 'clear'); + const admission = admitHostedCaller({ stateDir, env, booking: record }, 'clear'); + if (record.session === teardownSession && !admission.mayUseSavedCredentials) return null; + return admission; } catch { return null; } diff --git a/src/cli/connection/cloud-access.ts b/src/cli/connection/cloud-access.ts index 51d9106fe1..c4bbe5f50c 100644 --- a/src/cli/connection/cloud-access.ts +++ b/src/cli/connection/cloud-access.ts @@ -135,9 +135,12 @@ export function admitHostedCaller( if (purpose === 'use' || presentsCloudCredential(stateDir, env)) throw credentialMismatch(); return { mayUseSavedCredentials: false }; } - const caller = readCloudCallerForPurpose(stateDir, env, booking.origin, purpose); - if (caller === 'unverified') return { mayUseSavedCredentials: false }; - if (caller) assertCloudConnectionCaller(booking, caller); + const hasApiKey = Boolean(env.AGENT_DEVICE_CLOUD_API_KEY?.trim()); + const login = hasApiKey ? null : readStoredLogin(stateDir); + if (login === 'unverified' && purpose === 'clear') return { mayUseSavedCredentials: false }; + if (hasApiKey || login) { + assertCloudConnectionCaller(booking, readCallerIdentity(env, booking.origin, login)); + } const verifiable = booking.accountBinding !== undefined; if (purpose === 'use' && !verifiable) throw credentialMismatch(); return { mayUseSavedCredentials: verifiable }; @@ -177,21 +180,6 @@ function credentialMismatch() { return cloudConnectionUnavailable(CLOUD_CONNECTION_REASONS.credentialMismatch.reason); } -function readCloudCallerForPurpose( - stateDir: string, - env: EnvMap, - savedOrigin: string, - purpose: HostedCallerPurpose, -): CloudCallerIdentity | 'unverified' | undefined { - const hasApiKey = Boolean(env.AGENT_DEVICE_CLOUD_API_KEY?.trim()); - const login = hasApiKey ? null : readStoredLogin(stateDir); - if (!hasApiKey) { - if (!login) return undefined; - if (login === 'unverified' && purpose === 'clear') return 'unverified'; - } - return readCallerIdentity(env, savedOrigin, login); -} - function readCallerIdentity( env: EnvMap, savedOrigin: string, diff --git a/src/cli/connection/cloud-connect.ts b/src/cli/connection/cloud-connect.ts index 009864b8c5..6562a37308 100644 --- a/src/cli/connection/cloud-connect.ts +++ b/src/cli/connection/cloud-connect.ts @@ -1,6 +1,7 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { AgentDeviceClient } from '@agent-device/command-surface'; import { + observeRemoteConnectionState, readRemoteConnectionState, removeRemoteConnectionState, writeRemoteConnectionState, @@ -189,18 +190,12 @@ export async function closeHostedGeneration( // The fence goes up before any cleanup step: no command uses the candidate state after this. writeGeneration(location, 'pending', 'close', { ...record, phase: 'closing', rollback: true }); } - const endBroker = () => - proven - ? proven.active - ? deleteCloudSession(access, proven.id) - : Promise.resolve() - : endBrokerSession(access, record); const [lease, broker] = await Promise.allSettled([ releaseLease(), // A confirmed end is saved at once, so a later absence of that booking counts as released. record.brokerReleased ? Promise.resolve() - : endBroker().then(() => { + : endBrokerSession(access, record, proven).then(() => { // The caller has left the lock: a late confirmation is logged below, never saved. if (abandoned.aborted) return; const current = readCloudConnectionQuietly(location); @@ -277,40 +272,52 @@ function hasAttachmentEntry(location: ConnectionLocation): boolean { } } -/** - * Verifies pairing and broker ownership before an unfinished generation reaches attachment - * teardown. An unbound booking proves its owner through the broker lookup first; a reservation - * with no allocation ID, lease ID, saved state, or attachment clears on canonical `not_found`. - */ +function isEmptyPendingReservation( + location: ConnectionLocation, + record: CloudConnectionRecord, + stateAbsent: boolean, + host: HostEnvironment, +): boolean { + return ( + record.phase === 'pending' && + record.id === undefined && + record.hostedLeaseId === undefined && + record.deadlineAt === undefined && + record.assignment === undefined && + record.attachmentRefresh === undefined && + record.target === undefined && + record.receipt === undefined && + record.rollback === undefined && + stateAbsent && + !hasAttachmentEntry(location) && + !hasHostedPluginDaemonRegistration(location, record.generation, host) + ); +} + +/** Verifies pairing and broker ownership before unfinished teardown; clears empty reservations on `not_found`. */ export async function verifyUncommittedGenerationCleanup( location: ConnectionLocation, record: CloudConnectionRecord, access: HostedCloudAccess, + host: HostEnvironment, ): Promise< { kind: 'close'; proven?: { id: string; active: boolean } } | { kind: 'clear-reservation' } > { assertUncommittedGenerationAccess(record, access); - const state = readRemoteConnectionState(location); + const observedState = observeRemoteConnectionState(location); + const state = observedState.kind === 'valid' ? observedState.state : null; cloudBindingForTeardown(location, state, record); if (record.accountBinding !== undefined || record.brokerReleased) return { kind: 'close' }; - let found: { id: string; active: boolean } | undefined; - try { - found = await lookupCloudSession(access, record.generation); - } catch { - throw cloudConnectionUnavailable(CLOUD_CONNECTION_REASONS.allocationUnconfirmed.reason); - } - if (!found) { - if ( - record.id === undefined && - record.hostedLeaseId === undefined && - state === null && - !hasAttachmentEntry(location) - ) { - return { kind: 'clear-reservation' }; - } + const found = await lookupCloudSession(access, record.generation).catch(() => { throw cloudConnectionUnavailable(CLOUD_CONNECTION_REASONS.allocationUnconfirmed.reason); + }); + if ( + !found && + isEmptyPendingReservation(location, record, observedState.kind === 'absent', host) + ) { + return { kind: 'clear-reservation' }; } - if (record.id !== undefined && record.id !== found.id) { + if (!found || (record.id !== undefined && record.id !== found.id)) { throw cloudConnectionUnavailable(CLOUD_CONNECTION_REASONS.allocationUnconfirmed.reason); } record.accountBinding = hostedCloudAccountBinding(access); @@ -337,8 +344,10 @@ export function forgetUncommittedGeneration( async function endBrokerSession( access: HostedCloudAccess, record: CloudConnectionRecord, + proven?: { id: string; active: boolean }, ): Promise { - const id = record.id ?? (await lookupCloudSession(access, record.generation))?.id; + if (proven && !proven.active) return; + const id = proven?.id ?? record.id ?? (await lookupCloudSession(access, record.generation))?.id; if (id) await deleteCloudSession(access, id); } @@ -767,9 +776,7 @@ export async function forgetCloudConnection(options: { : null; if (!hasFiles && !hostedState) return null; const [daemonStateDir] = await Promise.all([ - usesSavedCredentials - ? stopHostedDaemonForForget(location, binding, host) - : unstoppedHostedDaemonDir(location, binding, host), + stopHostedDaemonForForget(location, binding, record, host, usesSavedCredentials), binding?.transport === 'agent-device-daemon' && usesSavedCredentials ? settleWithin( () => releaseProxyFrontTeardownLease(client, location, hostedState), @@ -789,8 +796,21 @@ export async function forgetCloudConnection(options: { async function stopHostedDaemonForForget( location: ConnectionLocation, binding: CloudSessionBinding | undefined, + record: CloudConnectionRecord | null, host: HostEnvironment, + usesSavedCredentials: boolean, ): Promise { + if (!usesSavedCredentials) { + const candidate = + binding && binding.transport !== 'agent-device-daemon' + ? binding + : record + ? { generation: record.generation } + : undefined; + return candidate && hasHostedPluginDaemonRegistration(location, candidate.generation, host) + ? hostedPluginDaemonDir(location, candidate) + : undefined; + } if (!binding || binding.transport === 'agent-device-daemon') return undefined; const stopped = await settleWithin( () => stopHostedPluginDaemon(location, binding.generation, host), @@ -802,17 +822,6 @@ async function stopHostedDaemonForForget( if (!stopped) return hostedPluginDaemonDir(location, binding); } -function unstoppedHostedDaemonDir( - location: ConnectionLocation, - binding: CloudSessionBinding | undefined, - host: HostEnvironment, -): string | undefined { - if (!binding || binding.transport === 'agent-device-daemon') return undefined; - return hasHostedPluginDaemonRegistration(location, binding.generation, host) - ? hostedPluginDaemonDir(location, binding) - : undefined; -} - function removeCloudState( location: ConnectionLocation, state: RemoteConnectionState | null, diff --git a/src/cli/connection/cloud-connection-record.test.ts b/src/cli/connection/cloud-connection-record.test.ts index 312860cff3..2d34f44c44 100644 --- a/src/cli/connection/cloud-connection-record.test.ts +++ b/src/cli/connection/cloud-connection-record.test.ts @@ -124,59 +124,60 @@ test('an expired proxy front is released with its attachment before the attachme expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); }); -test('an expired proxy-front attachment is removed without releasing when saved credentials are not admitted', async () => { - const location = expiredProxyFrontLocation(); - const released: unknown[] = []; - await cleanExpiredCloudAttachments( - location.stateDir, - () => ({ mayUseSavedCredentials: false }), - async () => { - throw new Error('a limrun daemon is not retired for a proxy front'); - }, - async (_location, attachment) => { - released.push(attachment); - }, - ); - expect(released).toEqual([]); - expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); -}); +test.each(['proxy-front', 'plugin'] as const)( + 'an expired %s attachment is removed without provider callbacks when saved credentials are not admitted', + async (kind) => { + const location = expiredProxyFrontLocation(); + if (kind === 'plugin') { + fs.rmSync(cloudAttachmentPath(location)); + writeCloudAttachment( + location, + { + kind: 'plugin', + plugin: '@agent-device/limrun', + token: 'scoped-plugin-token', + expiresAt: new Date(Date.now() - 1000).toISOString(), + data: { kind: 'limrun-instance' }, + }, + 'generation-1', + ); + } + const callbacks: unknown[] = []; + await cleanExpiredCloudAttachments( + location.stateDir, + () => ({ mayUseSavedCredentials: false }), + async (_location, generation) => { + callbacks.push(generation); + }, + async (_location, attachment) => { + callbacks.push(attachment); + }, + ); + expect(callbacks).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + }, +); -test('an expired plugin attachment is removed directly without retiring its daemon when saved credentials are not admitted', async () => { - const stateDir = mkdtempForTestSync('cloud-record-plugin-expiry-'); - const location = { stateDir, session: 'plugin-expiry-qa' }; - writeCloudConnection(location, { - session: location.session, - generation: 'generation-1', - phase: 'committed', - origin: 'https://cloud.example', - fingerprint: 'fingerprint-1', - id: '00000000-0000-4000-8000-000000000001', - deadlineAt: new Date(Date.now() - 1000).toISOString(), - }); - writeCloudAttachment( - location, - { - kind: 'plugin', - plugin: '@agent-device/limrun', - token: 'scoped-plugin-token', - expiresAt: new Date(Date.now() - 1000).toISOString(), - data: { kind: 'limrun-instance' }, - }, - 'generation-1', +test('the sweep leaves an expired attachment untouched when an invalid legacy saved connection exists for the session', async () => { + const location = expiredProxyFrontLocation(); + const recordsDir = path.join(location.stateDir, 'remote-connections'); + fs.mkdirSync(recordsDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(recordsDir, `${location.session}.json`), + JSON.stringify({ + version: 1, + session: location.session, + cloudSession: { transport: 'limrun', generation: 'other-generation' }, + }), + { mode: 0o600 }, ); - const retired: string[] = []; await cleanExpiredCloudAttachments( location.stateDir, () => ({ mayUseSavedCredentials: false }), - async (_location, generation) => { - retired.push(generation); - }, - async () => { - throw new Error('a proxy front is not released for a plugin attachment'); - }, + async () => undefined, + async () => undefined, ); - expect(retired).toEqual([]); - expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(true); }); test('an expired proxy-front attachment is removed even when its release fails', async () => { diff --git a/src/cli/connection/cloud-connection-record.ts b/src/cli/connection/cloud-connection-record.ts index 18ecf190de..4065872223 100644 --- a/src/cli/connection/cloud-connection-record.ts +++ b/src/cli/connection/cloud-connection-record.ts @@ -13,6 +13,7 @@ import { import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; import { AppError, CLOUD_ATTACHMENT_REASONS, type ReasonTable } from '@agent-device/kernel/errors'; import { + observeRemoteConnectionState, readRemoteConnectionState, type CloudSessionBinding, type RemoteConnectionState, @@ -553,9 +554,7 @@ function isExpired(record: CloudConnectionRecord): boolean { return record.deadlineAt !== undefined && Date.parse(record.deadlineAt) <= Date.now(); } -export type ExpiredBookingAdmission = { - mayUseSavedCredentials: boolean; -}; +export type ExpiredBookingAdmission = { mayUseSavedCredentials: boolean }; /** * Clears what expired bookings left in the state directory. Only a booking that `admits` accepts @@ -593,23 +592,30 @@ export async function cleanExpiredCloudAttachments( if (!current || !isExpired(current)) return; admission = admits(current); if (!admission) return; - // Saved state of another booking is left for the explicit local recovery. - const state = readRemoteConnectionState(location); - if (state && !samePairedBooking(state.cloudSession, current)) return; + // Saved state of another or invalid booking is left for explicit local recovery. + const observedState = observeRemoteConnectionState(location); + if ( + observedState.kind === 'invalid' || + observedState.kind === 'unknown' || + (observedState.kind === 'valid' && + !samePairedBooking(observedState.state.cloudSession, current)) + ) { + return; + } kind = readExpiredAttachmentKind(location); proxyFront = kind === 'agent-device-daemon' ? readProxyFrontAttachment(location) : undefined; } catch { return; } - if (proxyFront && current.phase !== 'pending' && admission.mayUseSavedCredentials) { + if (!admission.mayUseSavedCredentials) { + removeCloudAttachment(location); + return; + } + if (proxyFront && current.phase !== 'pending') { await releaseExpiredProxyFront(location, proxyFront).catch(() => undefined); removeCloudAttachment(location); - } else if ( - current.phase === 'pending' || - kind === 'agent-device-daemon' || - !admission.mayUseSavedCredentials - ) { + } else if (current.phase === 'pending' || kind === 'agent-device-daemon') { removeCloudAttachment(location); } else { await retireExpiredDaemon(location, current.generation).then( @@ -624,7 +630,13 @@ export async function cleanExpiredCloudAttachments( function readExpiredAttachmentKind(location: ConnectionLocation): unknown { try { return asCloudRecord(readCloudCredentialJson(cloudAttachmentPath(location)))?.kind; - } catch { + } catch (error) { + if ( + error instanceof AppError && + error.details?.reason === CLOUD_CONNECTION_REASONS.credentialStoreUnsafe.reason + ) { + throw error; + } return undefined; } } From 3c7ac9368c00e1a5ceb909a348f830c291662436 Mon Sep 17 00:00:00 2001 From: Suneeth12 Date: Sun, 6 Dec 2026 16:58:14 +0530 Subject: [PATCH 6/6] fix(cli): clear empty closing rollback reservations on canonical not_found --- .../cli-cloud-record-recovery.test.ts | 21 ++++++++++++++++--- src/cli/connection/cloud-connect.ts | 6 ++++-- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/__tests__/cli-cloud-record-recovery.test.ts b/src/__tests__/cli-cloud-record-recovery.test.ts index 9a74cb78b4..a3a22b13a0 100644 --- a/src/__tests__/cli-cloud-record-recovery.test.ts +++ b/src/__tests__/cli-cloud-record-recovery.test.ts @@ -368,12 +368,22 @@ test('connect on an expired unbound unfinished proxy-front booking releases its expect(owned.broker.mock.calls.map(([, init]) => init.method)).not.toContain('DELETE'); }); -test.each([false, true])( - 'connect (force=%s) clears an ID-less legacy pending reservation on canonical not_found and continues', - async (force) => { +test.each<{ + label: string; + force: boolean; + overrides?: { phase: 'closing'; rollback: true }; +}>([ + { label: 'pending', force: false }, + { label: 'pending', force: true }, + { label: 'closing rollback', force: false, overrides: { phase: 'closing', rollback: true } }, + { label: 'closing rollback', force: true, overrides: { phase: 'closing', rollback: true } }, +])( + 'connect (force=$force) clears an ID-less legacy $label reservation on canonical not_found and continues', + async ({ force, overrides }) => { const env = cloudEnv(); const location = locationOf(env); const reservation = writeLegacyPending(env); + if (overrides) writeCloudConnection(location, { ...reservation, ...overrides }); const broker = stubCloudApi(); broker.mockResolvedValueOnce(Response.json({ error: 'not_found' }, { status: 404 })); @@ -396,6 +406,11 @@ test.each<{ label: 'non-canonical 404', response: () => Response.json({ error: 'other' }, { status: 404 }), }, + { + label: 'closing record without rollback', + setup: (location) => + writeCloudConnection(location, { ...readCloudConnection(location)!, phase: 'closing' }), + }, { label: 'record with allocation ID', setup: (location) => diff --git a/src/cli/connection/cloud-connect.ts b/src/cli/connection/cloud-connect.ts index 6562a37308..dae63a829e 100644 --- a/src/cli/connection/cloud-connect.ts +++ b/src/cli/connection/cloud-connect.ts @@ -278,8 +278,11 @@ function isEmptyPendingReservation( stateAbsent: boolean, host: HostEnvironment, ): boolean { + const uncommitted = + record.phase === 'pending' || (record.phase === 'closing' && record.rollback === true); return ( - record.phase === 'pending' && + uncommitted && + !record.brokerReleased && record.id === undefined && record.hostedLeaseId === undefined && record.deadlineAt === undefined && @@ -287,7 +290,6 @@ function isEmptyPendingReservation( record.attachmentRefresh === undefined && record.target === undefined && record.receipt === undefined && - record.rollback === undefined && stateAbsent && !hasAttachmentEntry(location) && !hasHostedPluginDaemonRegistration(location, record.generation, host)