diff --git a/packages/remote/src/remote-connection-state-session-identity.test.ts b/packages/remote/src/remote-connection-state-session-identity.test.ts new file mode 100644 index 0000000000..30efaefd3b --- /dev/null +++ b/packages/remote/src/remote-connection-state-session-identity.test.ts @@ -0,0 +1,392 @@ +import { describe, test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { AppError } from '@agent-device/kernel/errors'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { + hashRemoteConfigFile, + readActiveConnectionState, + readRemoteConnectionState, + removeRemoteConnectionState, + resolveRemoteConnectionDefaults, + writeRemoteConnectionState, + type RemoteConnectionState, +} from './remote-connection-state.ts'; + +// A saved connection is stored in a file named after its session. Sanitizing a name that cannot be a +// filename, instead of hashing it, let two names that differ only in case open the same file on a +// case-insensitive filesystem, so one session read and then overwrote another session's record. + +const RECORDS_DIR = 'remote-connections'; +const ACTIVE_SESSION_FILE = '.active-session.json'; + +function recordFor(session: string): RemoteConnectionState { + const now = new Date().toISOString(); + return { + version: 1, + session, + remoteConfigPath: '/profiles/remote.json', + remoteConfigHash: 'hash', + tenant: 'acme', + runId: `run-${session}`, + connectedAt: now, + updatedAt: now, + }; +} + +/** Writes `contents` straight to `fileName`, as a previous build or another session would have left it. */ +function writeRecordFile( + stateDir: string, + fileName: string, + contents: string | Record, +): string { + const recordsDir = path.join(stateDir, RECORDS_DIR); + fs.mkdirSync(recordsDir, { recursive: true }); + const statePath = path.join(recordsDir, fileName); + const text = typeof contents === 'string' ? contents : `${JSON.stringify(contents, null, 2)}\n`; + fs.writeFileSync(statePath, text, 'utf8'); + return statePath; +} + +/** Where a session whose name cannot be a filename is stored: under the hash of its UTF-16 code units. */ +function hashedFileName(session: string): string { + const identity = crypto + .createHash('sha256') + .update(Buffer.from(session, 'utf16le')) + .digest('hex'); + return `~${identity}.json`; +} + +/** The file name a build that sanitized names wrote for `session`. */ +function sanitizedFileName(session: string): string { + const safe = session.replaceAll(/[^a-zA-Z0-9._-]/g, '_'); + if (safe === session) return `${safe}.json`; + return `${safe}-${crypto.createHash('sha256').update(session).digest('hex').slice(0, 8)}.json`; +} + +function recordsIn(stateDir: string): string[] { + return fs.readdirSync(path.join(stateDir, RECORDS_DIR)).sort(); +} + +/** + * Leaves one legacy file reachable under the names of both `session` and its lower-case variant, which + * is what a case-insensitive filesystem does by itself. On a case-sensitive one, a hard link stands in + * for that fold so both names open the same bytes. + */ +function plantFileSharedByCaseVariants( + stateDir: string, + session: string, + contents: string | Record = recordFor(session), +): string { + const written = writeRecordFile(stateDir, `${session}.json`, contents); + const aliased = path.join(path.dirname(written), `${session.toLowerCase()}.json`); + try { + fs.linkSync(written, aliased); + } catch (error) { + // EEXIST: the volume folds the two names onto the file that is already there. + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; + } + return written; +} + +function captureRefusal(run: () => unknown): AppError { + try { + run(); + } catch (error) { + assert.ok(error instanceof AppError, `expected an AppError, got ${String(error)}`); + return error; + } + return assert.fail('expected a refusal'); +} + +const runsAsRoot = process.getuid?.() === 0; + +describe.each([ + { first: 'Demo', second: 'demo', files: ['demo.json', hashedFileName('Demo')] }, + { + first: '\uD800', + second: '\uD801', + files: [hashedFileName('\uD800'), hashedFileName('\uD801')], + }, +])('sessions named $first and $second', ({ first, second, files }) => { + test('keep separate records, and removing one leaves the other', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pair-'); + writeRemoteConnectionState({ stateDir, state: recordFor(first) }); + writeRemoteConnectionState({ stateDir, state: recordFor(second) }); + + assert.equal(readRemoteConnectionState({ stateDir, session: first })?.runId, `run-${first}`); + assert.equal(readRemoteConnectionState({ stateDir, session: second })?.runId, `run-${second}`); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, ...files].sort()); + + removeRemoteConnectionState({ stateDir, session: first }); + assert.equal(readRemoteConnectionState({ stateDir, session: first }), null); + assert.equal(readRemoteConnectionState({ stateDir, session: second })?.runId, `run-${second}`); + }); +}); + +test('a record at the sanitized path that names this session is read in place and moves on save', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-legacy-match-'); + const session = 'team/dev#1'; + writeRecordFile(stateDir, sanitizedFileName(session), recordFor(session)); + + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); + assert.deepEqual(recordsIn(stateDir), [sanitizedFileName(session)], 'a read moved no file'); + + writeRemoteConnectionState({ stateDir, state: { ...recordFor(session), runId: 'run-saved' } }); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, hashedFileName(session)].sort()); + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, 'run-saved'); +}); + +test('a record at the sanitized path that names another session is left in place', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-legacy-alias-'); + const session = 'team/dev#1'; + // An older build wrote two sessions to the same name, so the file name proves nothing. + const legacyPath = writeRecordFile(stateDir, sanitizedFileName(session), recordFor('team:dev#1')); + + assert.equal(readRemoteConnectionState({ stateDir, session }), null); + writeRemoteConnectionState({ stateDir, state: recordFor(session) }); + + assert.equal(JSON.parse(fs.readFileSync(legacyPath, 'utf8')).session, 'team:dev#1'); + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); +}); + +test('a sanitized record whose hashed path is already taken is kept and refused', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-legacy-occupied-'); + const session = 'team/dev#1'; + const legacyPath = writeRecordFile(stateDir, sanitizedFileName(session), recordFor(session)); + writeRecordFile(stateDir, hashedFileName(session), recordFor(session)); + + const refusal = captureRefusal(() => removeRemoteConnectionState({ stateDir, session })); + + assert.equal(refusal.details?.reason, 'connection_session_mismatch'); + assert.equal(refusal.details?.recordPath, legacyPath); + assert.deepEqual( + recordsIn(stateDir), + [hashedFileName(session), sanitizedFileName(session)].sort(), + 'neither record is lost when both claim the same session', + ); +}); + +test('a record an older build shared with a case-variant session moves to its owner on save', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-upgrade-'); + plantFileSharedByCaseVariants(stateDir, 'Demo'); + + assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' }), null); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); + + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); + // On a case-sensitive volume the fixture's hard link leaves `Demo.json` as a second name of the + // moved record. Only the Demo session retires that name, so ignore it here. + assert.deepEqual( + recordsIn(stateDir).filter((name) => name !== 'Demo.json'), + [ACTIVE_SESSION_FILE, 'demo.json', hashedFileName('Demo')].sort(), + ); + + removeRemoteConnectionState({ stateDir, session: 'demo' }); + assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' }), null); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); +}); + +describe.each([ + { damage: 'unreadable', skip: runsAsRoot }, + { damage: 'unparseable', skip: false }, +])('an $damage record an older build shared with a case-variant session', ({ damage, skip }) => { + test.skipIf(skip)('is never removed and serves no session', () => { + const stateDir = mkdtempForTestSync(`agent-device-remote-identity-${damage}-`); + const sharedPath = + damage === 'unreadable' + ? plantFileSharedByCaseVariants(stateDir, 'Demo') + : plantFileSharedByCaseVariants(stateDir, 'Demo', '{"session": "Demo",'); + if (damage === 'unreadable') fs.chmodSync(sharedPath, 0o000); + const planted = recordsIn(stateDir); + try { + const refusal = captureRefusal(() => + readRemoteConnectionState({ stateDir, session: 'demo' }), + ); + assert.equal(refusal.details?.reason, 'connection_record_owner_unknown'); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' }), null); + captureRefusal(() => writeRemoteConnectionState({ stateDir, state: recordFor('demo') })); + captureRefusal(() => removeRemoteConnectionState({ stateDir, session: 'demo' })); + assert.deepEqual(recordsIn(stateDir), planted, 'no command removed the shared file'); + } finally { + fs.chmodSync(sharedPath, 0o600); + } + }); +}); + +test('an invalid record of another session at a session path refuses read, save and removal', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-mismatch-'); + // Ownership is settled before shape: a record that fails validation is still another session's. + const statePath = writeRecordFile(stateDir, 'demo.json', { + ...recordFor('other'), + updatedAt: null, + }); + + const read = captureRefusal(() => readRemoteConnectionState({ stateDir, session: 'demo' })); + assert.equal(read.code, 'COMMAND_FAILED'); + assert.equal(read.details?.reason, 'connection_session_mismatch'); + assert.equal(read.details?.session, 'demo'); + assert.equal(read.details?.recordPath, statePath); + assert.ok(String(read.details?.hint).includes(statePath), 'the recovery names the file'); + + for (const run of [ + () => writeRemoteConnectionState({ stateDir, state: recordFor('demo') }), + () => removeRemoteConnectionState({ stateDir, session: 'demo' }), + ]) { + assert.equal(captureRefusal(run).details?.reason, 'connection_session_mismatch'); + } + assert.equal(JSON.parse(fs.readFileSync(statePath, 'utf8')).session, 'other'); +}); + +test('a read reports an invalid record of its session as no connection and keeps it', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-observe-invalid-'); + writeRecordFile(stateDir, 'demo.json', { ...recordFor('demo'), updatedAt: null }); + writeRecordFile(stateDir, 'Team.json', { ...recordFor('Team'), updatedAt: null }); + writeRecordFile(stateDir, ACTIVE_SESSION_FILE, { session: 'demo' }); + + assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' }), null); + assert.equal(readActiveConnectionState({ stateDir }), null); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Team' }), null); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, 'Team.json', 'demo.json'].sort()); +}); + +test('remote command defaults resolve from an older Demo.json without moving it', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-defaults-'); + const remoteConfigPath = path.join(stateDir, 'remote.json'); + fs.writeFileSync(remoteConfigPath, '{}'); + writeRecordFile(stateDir, 'Demo.json', { + ...recordFor('Demo'), + remoteConfigPath, + remoteConfigHash: hashRemoteConfigFile(remoteConfigPath), + }); + + const defaults = resolveRemoteConnectionDefaults({ + stateDir, + session: 'Demo', + cwd: stateDir, + env: {}, + }); + + assert.equal(defaults?.flags.session, 'Demo'); + assert.equal(defaults?.flags.remoteConfig, remoteConfigPath); + assert.deepEqual(recordsIn(stateDir), ['Demo.json']); +}); + +test('the empty session owns the default.json an older build wrote for it, and default does not', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-empty-'); + writeRecordFile(stateDir, 'default.json', recordFor('')); + + assert.equal(readRemoteConnectionState({ stateDir, session: '' })?.runId, 'run-'); + assert.equal(readRemoteConnectionState({ stateDir, session: 'default' }), null); + assert.deepEqual(recordsIn(stateDir), ['default.json'], 'a read moved no file'); + + writeRemoteConnectionState({ stateDir, state: { ...recordFor(''), runId: 'run-saved' } }); + assert.equal(readRemoteConnectionState({ stateDir, session: '' })?.runId, 'run-saved'); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, hashedFileName('')].sort()); +}); + +test('an EPERM hard-link failure never deletes default.json', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-eperm-'); + // The empty session's older record, which fails validation, at the literal `default` session path. + const legacyPath = writeRecordFile(stateDir, 'default.json', { + ...recordFor(''), + updatedAt: null, + }); + const link = vi.spyOn(fs, 'linkSync').mockImplementation(() => { + throw Object.assign(new Error('EPERM: operation not permitted, link'), { code: 'EPERM' }); + }); + try { + assert.throws(() => removeRemoteConnectionState({ stateDir, session: '' }), { + code: 'EPERM', + }); + assert.throws(() => writeRemoteConnectionState({ stateDir, state: recordFor('') }), { + code: 'EPERM', + }); + } finally { + link.mockRestore(); + } + assert.equal(fs.existsSync(legacyPath), true); +}); + +test('an empty-session pointer resolves for an unnamed read', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-empty-pointer-'); + writeRecordFile(stateDir, hashedFileName(''), recordFor('')); + writeRecordFile(stateDir, ACTIVE_SESSION_FILE, { session: '' }); + + assert.equal(readActiveConnectionState({ stateDir })?.runId, 'run-'); +}); + +test('the record an older build wrote for .active-session at the pointer path is read, then moved before the pointer write', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-'); + // A build that sanitized names wrote the session `.active-session` to exactly the pointer path. + const session = '.active-session'; + writeRecordFile(stateDir, ACTIVE_SESSION_FILE, recordFor(session)); + + assert.equal(readActiveConnectionState({ stateDir })?.runId, `run-${session}`); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE], 'the active lookup moved no file'); + + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); + + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); + assert.equal(readActiveConnectionState({ stateDir })?.runId, 'run-demo'); + assert.deepEqual( + recordsIn(stateDir), + [ACTIVE_SESSION_FILE, 'demo.json', hashedFileName(session)].sort(), + ); +}); + +test('a record of unproven owner on the pointer path refuses the pointer write', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-foreign-'); + const pointerPath = writeRecordFile(stateDir, ACTIVE_SESSION_FILE, recordFor('team')); + + const refusal = captureRefusal(() => + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }), + ); + + assert.equal(refusal.details?.reason, 'connection_session_mismatch'); + assert.equal(JSON.parse(fs.readFileSync(pointerPath, 'utf8')).session, 'team'); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE], 'nothing else was written'); +}); + +describe.each([ + { owner: 'demo', ownSessionRecord: 'demo.json', activeRunId: undefined }, + // `.ACTIVE-SESSION.json` is the older name of `.ACTIVE-SESSION`, so the record looks like that + // session's. Only the checked move may remove it, and the move refuses the occupied hashed path. + { + owner: '.ACTIVE-SESSION', + ownSessionRecord: hashedFileName('.ACTIVE-SESSION'), + activeRunId: 'run-.ACTIVE-SESSION', + }, +])( + 'a full record at the pointer path that names $owner', + ({ owner, ownSessionRecord, activeRunId }) => { + test('is not deleted by removal of that session', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-record-'); + writeRecordFile(stateDir, ownSessionRecord, recordFor(owner)); + const pointerPath = writeRecordFile(stateDir, ACTIVE_SESSION_FILE, { + ...recordFor(owner), + runId: 'run-at-pointer', + }); + assert.equal(readActiveConnectionState({ stateDir })?.runId, activeRunId); + // On a case-insensitive volume `.ACTIVE-SESSION.json` opens the pointer file. A case-sensitive + // volume keeps the names apart, so the removal reaches the pointer without the checked move. + const readFileSync = fs.readFileSync; + const read = vi.spyOn(fs, 'readFileSync').mockImplementation(((file, ...rest) => { + if (path.basename(String(file)) === '.ACTIVE-SESSION.json') { + throw Object.assign(new Error('ENOENT: no such file'), { code: 'ENOENT' }); + } + return readFileSync(file, ...rest); + }) as typeof fs.readFileSync); + try { + removeRemoteConnectionState({ stateDir, session: owner }); + } finally { + read.mockRestore(); + } + + assert.equal(JSON.parse(fs.readFileSync(pointerPath, 'utf8')).runId, 'run-at-pointer'); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE]); + }); + }, +); diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index 59426dfda5..2ca43e968b 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -220,26 +220,155 @@ type RemoteConnectionDefaults = { flags: Partial; runtime?: SessionRuntimeHints; connection?: RemoteConnectionRequestMetadata; + /** Set only by {@link claimRemoteConnectionDefaults}: the record it claimed, or `null` for none. */ + claimed?: RemoteConnectionState | null; }; +const REMOTE_CONNECTION_STATE_REASONS = { + // A saved connection file cannot be used for the session a command named: it names another session, + // a record from an older build cannot move to its session file because that file already exists, or + // the active-session pointer path holds a record whose owner is unproven. The refused file is kept, + // and so is the occupied session file. + sessionMismatch: { reason: 'connection_session_mismatch' }, + // The session's own saved connection file, or the active-session pointer, could not be read or + // parsed, so no session is known to own it. It was neither replaced nor removed. + ownerUnknown: { reason: 'connection_record_owner_unknown' }, +} as const satisfies ReasonTable<'remote connections'>; + +/** + * The saved connection `session` owns, read without a change to any file. + * + * A record an older build wrote for exactly this session is reported where it is. A record that names + * the session but fails validation is reported as no connection and is kept. Only + * {@link writeRemoteConnectionState}, {@link claimRemoteConnectionState} and + * {@link removeRemoteConnectionState} move or remove files. + */ export function readRemoteConnectionState(options: { stateDir: string; session: string; }): RemoteConnectionState | null { - const statePath = remoteConnectionStatePath(options); - if (!fs.existsSync(statePath)) return null; - let parsed: unknown; - try { - parsed = JSON.parse(fs.readFileSync(statePath, 'utf8')); - } catch (error) { - removeInvalidRemoteConnectionState(options, error); - return null; + const recordsDir = path.join(options.stateDir, 'remote-connections'); + const canonical = canonicalRemoteConnectionStatePath(recordsDir, options.session); + const file = readRecordFile(canonical); + if (file.kind === 'unknown') { + throw recordOwnerUnknownError(options.session, canonical, file.cause); + } + // A record that another session's older build left at this path moves away on the next save. + if (file.kind === 'owned' && !isMovableLegacyRecord(recordsDir, canonical, file)) { + if (file.session !== options.session) { + throw sessionMismatchError( + options.session, + canonical, + 'The saved connection belongs to a different session.', + ); + } + return observedRemoteConnectionState(options.session, canonical, file.record); + } + const legacyPath = path.join(recordsDir, legacyRemoteConnectionFileName(options.session)); + const legacy = readRecordFile(legacyPath); + return legacy.kind === 'owned' && + legacy.session === options.session && + isMovableLegacyRecord(recordsDir, legacyPath, legacy) + ? observedRemoteConnectionState(options.session, legacyPath, legacy.record) + : null; +} + +/** + * The first step of a removal: the saved connection `session` owns, moved to its session's own path. + * + * A caller runs this before any remote teardown, so a record it cannot remove is refused before a lease + * ends, and finishes with {@link removeRemoteConnectionState}. `session` is `undefined` when the caller + * named none: the `default` session comes first, then the active-session pointer. A record that names + * its session but fails validation is removed on the way, and the next candidate is tried. A missing + * record returns `null`. + */ +export function claimRemoteConnectionState(options: { + stateDir: string; + session: string | undefined; +}): RemoteConnectionState | null { + const { stateDir, session } = options; + if (session !== undefined) return claimSessionRecord({ stateDir, session }).state; + const claimed = claimSessionRecord({ stateDir, session: 'default' }).state; + if (claimed) return claimed; + const activeSession = activeRecordOwner(stateDir); + return activeSession === undefined + ? null + : claimSessionRecord({ stateDir, session: activeSession }).state; +} + +/** + * The session's own path and its valid record there, if any. Records an older build wrote for the + * session move there first, and a record there that names the session but fails validation is removed. + * A file there that no session is proven to own, or that another session owns, refuses the claim. + */ +function claimSessionRecord(options: { stateDir: string; session: string }): { + statePath: string; + state: RemoteConnectionState | null; +} { + const recordsDir = path.join(options.stateDir, 'remote-connections'); + const statePath = canonicalRemoteConnectionStatePath(recordsDir, options.session); + // A record at the name an older build wrote for this session moves to its owner's own path first. + // That name can also open another session's record: it can be this session's own path, or a case + // alias of the other session's older name. A hashed path is never a name an older build wrote. + migrateLegacyRemoteConnectionState({ + recordsDir, + source: path.join(recordsDir, legacyRemoteConnectionFileName(options.session)), + session: options.session, + }); + const file = readRecordFile(statePath); + if (file.kind === 'absent') return { statePath, state: null }; + if (file.kind === 'unknown') { + throw recordOwnerUnknownError(options.session, statePath, file.cause); } - if (!isRemoteConnectionState(parsed)) { - removeInvalidRemoteConnectionState(options); - return null; + // Ownership is settled before shape: a record another session owns is never removed as invalid. + if (file.session !== options.session) { + throw sessionMismatchError( + options.session, + statePath, + 'The saved connection belongs to a different session.', + ); } - return parsed; + if (isRemoteConnectionState(file.record)) return { statePath, state: file.record }; + warnInvalidRecord(options.session, statePath); + removeRemoteConnectionStateFile(options, statePath); + return { statePath, state: null }; +} + +function observedRemoteConnectionState( + session: string, + recordPath: string, + record: Record, +): RemoteConnectionState | null { + if (isRemoteConnectionState(record)) return record; + warnInvalidRecord(session, recordPath); + return null; +} + +function warnInvalidRecord(session: string, recordPath: string): void { + emitDiagnostic({ + level: 'warn', + phase: 'remote_connection_state_invalid', + data: { session, recordPath }, + }); +} + +function sessionMismatchError(session: string, recordPath: string, message: string): AppError { + return new AppError('COMMAND_FAILED', message, { + reason: REMOTE_CONNECTION_STATE_REASONS.sessionMismatch.reason, + session, + recordPath, + hint: `Remove ${recordPath} only if no session needs the connection it holds.`, + }); +} + +function recordOwnerUnknownError(session: string, recordPath: string, cause: unknown): AppError { + return new AppError('COMMAND_FAILED', 'The saved connection file could not be read.', { + reason: REMOTE_CONNECTION_STATE_REASONS.ownerUnknown.reason, + session, + recordPath, + cause: cause instanceof Error ? cause.message : String(cause), + hint: `Make ${recordPath} readable, or remove it if no session needs it.`, + }); } export function writeRemoteConnectionState(options: { @@ -252,7 +381,8 @@ export function writeRemoteConnectionState(options: { */ onSessionRecordCommitted?: () => void; }): void { - const statePath = remoteConnectionStatePath({ + retireRecordAtActivePointer(options.stateDir, options.state.session); + const { statePath } = claimSessionRecord({ stateDir: options.stateDir, session: options.state.session, }); @@ -276,10 +406,23 @@ export function buildRemoteConnectionDaemonState( } export function removeRemoteConnectionState(options: { stateDir: string; session: string }): void { - fs.rmSync(remoteConnectionStatePath(options), { force: true }); + removeRemoteConnectionStateFile(options, claimSessionRecord(options).statePath); +} + +function removeRemoteConnectionStateFile( + options: { stateDir: string; session: string }, + statePath: string, +): void { + fs.rmSync(statePath, { force: true }); + // Only a pointer is removed here. A full record an older build wrote at the pointer path leaves only + // through the checked move in migrateLegacyRemoteConnectionState. const activePath = activeConnectionStatePath(options.stateDir); - const activeSession = readActiveConnectionSession(options.stateDir); - if (activeSession === options.session) { + const active = readRecordFile(activePath); + if ( + active.kind === 'owned' && + active.session === options.session && + isActiveSessionPointer(active.record) + ) { fs.rmSync(activePath, { force: true }); } } @@ -340,8 +483,42 @@ export function resolveRemoteConnectionDefaults(options: { env: Record; validateRemoteConfigHash?: boolean; }): RemoteConnectionDefaults | null { + return remoteConnectionDefaults(selectRemoteConnectionState(options), options); +} + +/** + * The defaults for `disconnect`, taken from the record {@link claimRemoteConnectionState} claims. + * + * The returned `claimed` record also drives the teardown, so the record is resolved once. A leased + * record is refused when the caller named no session. The defaults are empty when no record is + * claimed or the record connects through another `remoteConfig` than the one requested. + */ +export function claimRemoteConnectionDefaults(options: { + stateDir: string; + session: string | undefined; + remoteConfig?: string; + cwd: string; + env: Record; +}): RemoteConnectionDefaults { + const claimed = claimRemoteConnectionState(options); + if (claimed) requireLeasedConnectionSession(claimed, options.session); + const selected = claimed && matchesRequestedRemoteConfig(claimed, options) ? claimed : null; + const defaults = remoteConnectionDefaults(selected, { + ...options, + validateRemoteConfigHash: false, + }); + return { flags: {}, ...defaults, claimed }; +} + +function remoteConnectionDefaults( + state: RemoteConnectionState | null, + options: { + cwd: string; + env: Record; + validateRemoteConfigHash?: boolean; + }, +): RemoteConnectionDefaults | null { const validateRemoteConfigHash = options.validateRemoteConfigHash ?? true; - const state = selectRemoteConnectionState(options); if (!state) return null; if ( validateRemoteConfigHash && @@ -514,39 +691,182 @@ export function hashRemoteConfigFile(configPath: string): string { } } -function remoteConnectionStatePath(options: { stateDir: string; session: string }): string { - return path.join( - options.stateDir, - 'remote-connections', - `${safeStateName(options.session)}.json`, +/** The pointer to the machine-wide active session. It is not a session record and never names one. */ +const ACTIVE_SESSION_FILE_NAME = '.active-session.json'; + +/** A session name that is a file name on its own. It cannot start with `.`, so it never names the pointer. */ +const PLAIN_SESSION_NAME = /^[a-z0-9_-][a-z0-9._-]*$/; + +/** + * Where a session's saved connection lives. The name alone decides it, and no two sessions share it. + * + * A plain name is stored under itself. Any other name is stored under the SHA-256 of its UTF-16 code + * units, so names that differ only in case, or in lone surrogates, get different files. Neither form + * can be a case alias of another session's file or of the active-session pointer. + */ +function canonicalRemoteConnectionStatePath(recordsDir: string, session: string): string { + if (PLAIN_SESSION_NAME.test(session)) return path.join(recordsDir, `${session}.json`); + const identity = crypto + .createHash('sha256') + .update(Buffer.from(session, 'utf16le')) + .digest('hex'); + return path.join(recordsDir, `~${identity}.json`); +} + +/** + * The file name a build that sanitized session names wrote for `session`. On a case-insensitive + * filesystem it also opens the file of any session whose name differs only in case. + */ +function legacyRemoteConnectionFileName(session: string): string { + if (session === '') return 'default.json'; + const safe = session.replaceAll(/[^a-zA-Z0-9._-]/g, '_'); + if (safe === session) return `${safe}.json`; + const suffix = crypto.createHash('sha256').update(session).digest('hex').slice(0, 8); + return `${safe}-${suffix}.json`; +} + +type RecordFile = + | { kind: 'absent' } + /** The file exists but could not be read or parsed, or names no session: its owner is unknown. */ + | { kind: 'unknown'; cause: unknown } + | OwnedRecordFile; + +type OwnedRecordFile = { kind: 'owned'; session: string; record: Record }; + +/** What the file at `filePath` holds. Only `ENOENT` means absent. */ +function readRecordFile(filePath: string): RecordFile { + let text: string; + try { + text = fs.readFileSync(filePath, 'utf8'); + } catch (error) { + return isMissingPathError(error) ? { kind: 'absent' } : { kind: 'unknown', cause: error }; + } + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch (error) { + return { kind: 'unknown', cause: error }; + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return { kind: 'unknown', cause: 'The file holds no JSON object.' }; + } + const record = parsed as Record; + return typeof record.session === 'string' + ? { kind: 'owned', session: record.session, record } + : { kind: 'unknown', cause: 'The file names no session.' }; +} + +/** Whether a parsed file is an active-session pointer, which holds only the session it points at. */ +function isActiveSessionPointer(record: Record): boolean { + return Object.keys(record).every((key) => key === 'session'); +} + +/** + * Moves a record an older build left at `source` to its owner's own path, then removes `source`. + * + * The owner is the session the record names, and only when `source` is a name an older build wrote + * for that session, compared case-insensitively. A file whose owner is unknown or unproven is left + * in place. When the owner's own path is already taken by a different file, `source` is kept and the + * command is refused: one of the two records would otherwise be lost. + */ +function migrateLegacyRemoteConnectionState(options: { + recordsDir: string; + source: string; + session: string; +}): boolean { + const file = readRecordFile(options.source); + if (file.kind !== 'owned' || !isMovableLegacyRecord(options.recordsDir, options.source, file)) { + return false; + } + const target = canonicalRemoteConnectionStatePath(options.recordsDir, file.session); + try { + fs.linkSync(options.source, target); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; + if (!isSameFile(options.source, target)) { + throw sessionMismatchError( + options.session, + options.source, + 'An older saved connection cannot move to its session file, because that file already exists.', + ); + } + } + fs.rmSync(options.source, { force: true }); + return true; +} + +/** + * Whether `file` is a record an older build left at `source` for the session it names: `source` is a + * name an older build wrote for that session, compared case-insensitively, and not its own path. A + * pointer at the active-session pointer path, or at a case alias of it, is no record. + */ +function isMovableLegacyRecord(recordsDir: string, source: string, file: OwnedRecordFile): boolean { + const sourceName = path.basename(source).toLowerCase(); + if (sourceName === ACTIVE_SESSION_FILE_NAME && isActiveSessionPointer(file.record)) return false; + // Canonical names hold no upper-case letters, so a name that folds onto the target IS the target. + if (path.basename(canonicalRemoteConnectionStatePath(recordsDir, file.session)) === sourceName) { + return false; + } + return legacyRemoteConnectionFileName(file.session).toLowerCase() === sourceName; +} + +function isSameFile(left: string, right: string): boolean { + const a = fs.statSync(left); + const b = fs.statSync(right); + return a.dev === b.dev && a.ino === b.ino; +} + +/** + * Keeps a full record an older build wrote at the active-session pointer path, or at a case alias of + * it, from being replaced by the next pointer write. A record whose owner is proven moves to that + * owner's own path first. A file whose owner is unknown refuses the write. + */ +function retireRecordAtActivePointer(stateDir: string, session: string): void { + const recordsDir = path.join(stateDir, 'remote-connections'); + const activePath = activeConnectionStatePath(stateDir); + const file = readRecordFile(activePath); + if (file.kind === 'absent') return; + if (file.kind === 'unknown') throw recordOwnerUnknownError(session, activePath, file.cause); + if (isActiveSessionPointer(file.record)) return; + if (migrateLegacyRemoteConnectionState({ recordsDir, source: activePath, session })) return; + throw sessionMismatchError( + session, + activePath, + 'The active-session pointer path holds a saved connection whose owner is unproven.', ); } function activeConnectionStatePath(stateDir: string): string { - return path.join(stateDir, 'remote-connections', '.active-session.json'); + return path.join(stateDir, 'remote-connections', ACTIVE_SESSION_FILE_NAME); } +/** + * The connection the active-session pointer names, read without a change to any file. + * + * A full record an older build wrote at the pointer path counts only when that path is the older name + * of the session the record names. + */ export function readActiveConnectionState(options: { stateDir: string; }): RemoteConnectionState | null { - const session = readActiveConnectionSession(options.stateDir); - return session - ? readRemoteConnectionState({ - stateDir: options.stateDir, - session, - }) - : null; + const session = activeRecordOwner(options.stateDir); + return session === undefined + ? null + : readRemoteConnectionState({ stateDir: options.stateDir, session }); } -function readActiveConnectionSession(stateDir: string): string | undefined { +/** + * The session the active-session pointer names, or the owner of a full record an older build wrote at + * the pointer path when that path is the older name of the session the record names. + */ +function activeRecordOwner(stateDir: string): string | undefined { const activePath = activeConnectionStatePath(stateDir); - if (!fs.existsSync(activePath)) return undefined; - try { - const parsed = JSON.parse(fs.readFileSync(activePath, 'utf8')) as Record; - return typeof parsed.session === 'string' ? parsed.session : undefined; - } catch { - return undefined; - } + const file = readRecordFile(activePath); + if (file.kind !== 'owned') return undefined; + const isPointer = isActiveSessionPointer(file.record); + return isPointer || isMovableLegacyRecord(path.dirname(activePath), activePath, file) + ? file.session + : undefined; } export function fingerprint(value: string | undefined): string | undefined { @@ -598,29 +918,6 @@ function sanitizeDaemonBaseUrl(value: string | undefined): string | undefined { return url.toString().replace(/\/+$/, ''); } -function removeInvalidRemoteConnectionState( - options: { stateDir: string; session: string }, - error?: unknown, -): void { - emitDiagnostic({ - level: 'warn', - phase: 'remote_connection_state_invalid', - data: { - session: options.session, - cause: error instanceof Error ? error.message : error ? String(error) : undefined, - }, - }); - removeRemoteConnectionState(options); -} - -function safeStateName(value: string): string { - const safe = value.replaceAll(/[^a-zA-Z0-9._-]/g, '_'); - if (!safe) return 'default'; - if (safe === value) return safe; - const suffix = crypto.createHash('sha256').update(value).digest('hex').slice(0, 8); - return `${safe}-${suffix}`; -} - function isRemoteConnectionState(value: unknown): value is RemoteConnectionState { if (!value || typeof value !== 'object' || Array.isArray(value)) return false; const record = value as Record; diff --git a/src/__tests__/cli-config.test.ts b/src/__tests__/cli-config.test.ts index 28d81e1fb6..3339adfc68 100644 --- a/src/__tests__/cli-config.test.ts +++ b/src/__tests__/cli-config.test.ts @@ -1138,7 +1138,7 @@ test('disconnect cleans connection state when remote config file is gone', async fs.rmSync(root, { recursive: true, force: true }); }); -test('disconnect removes malformed connection state', async () => { +test('disconnect refuses and keeps a connection state file that does not parse', async () => { const { root, home, project } = makeTempWorkspace(); const stateDir = path.join(root, 'state'); const connectionsDir = path.join(stateDir, 'remote-connections'); @@ -1153,10 +1153,12 @@ test('disconnect removes malformed connection state', async () => { env: { HOME: home }, }); - assert.equal(disconnected.code, null); + // No session can be shown to own an unparseable file, so it is never removed. + assert.equal(disconnected.code, 1); assert.equal(disconnected.calls.length, 0); - assert.equal(fs.existsSync(statePath), false); - assert.equal(fs.existsSync(activePath), false); + assert.match(disconnected.stdout, /connection_record_owner_unknown/); + assert.equal(fs.readFileSync(statePath, 'utf8'), '{not json'); + assert.equal(fs.existsSync(activePath), true); fs.rmSync(root, { recursive: true, force: true }); }); diff --git a/src/__tests__/cli-disconnect-invalid-default.test.ts b/src/__tests__/cli-disconnect-invalid-default.test.ts new file mode 100644 index 0000000000..d9d65ccd57 --- /dev/null +++ b/src/__tests__/cli-disconnect-invalid-default.test.ts @@ -0,0 +1,107 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { makeTempWorkspace } from '@agent-device/test-kit'; +import { + hashRemoteConfigFile, + readRemoteConnectionState, +} from '@agent-device/remote/remote-connection-state'; +import { runCliCapture } from './cli-capture.ts'; + +test('an unnamed disconnect removes an invalid default record before it disconnects the active session', async () => { + const { root, home, project } = makeTempWorkspace(); + const stateDir = path.join(root, 'state'); + const connectionsDir = path.join(stateDir, 'remote-connections'); + fs.mkdirSync(connectionsDir, { recursive: true }); + const remoteConfig = path.join(project, 'agent-device.remote.json'); + fs.writeFileSync( + remoteConfig, + JSON.stringify({ daemonBaseUrl: 'http://remote-mac.example.test:9124/agent-device' }), + 'utf8', + ); + const record = (session: string) => ({ + version: 1, + session, + remoteConfigPath: remoteConfig, + remoteConfigHash: hashRemoteConfigFile(remoteConfig), + tenant: 'acme', + runId: `run-${session}`, + connectedAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }); + const defaultPath = path.join(connectionsDir, 'default.json'); + const teamPath = path.join(connectionsDir, 'team.json'); + const activePath = path.join(connectionsDir, '.active-session.json'); + fs.writeFileSync(defaultPath, JSON.stringify({ ...record('default'), updatedAt: null }), 'utf8'); + fs.writeFileSync(teamPath, JSON.stringify(record('team')), 'utf8'); + fs.writeFileSync(activePath, JSON.stringify({ session: 'team' }), 'utf8'); + + const disconnected = await runCliCapture(['disconnect', '--state-dir', stateDir, '--json'], { + cwd: project, + env: { HOME: home }, + }); + + assert.equal(disconnected.code, null); + assert.equal(JSON.parse(disconnected.stdout).data.session, 'team'); + assert.equal(fs.existsSync(defaultPath), false); + assert.equal(fs.existsSync(teamPath), false); + assert.equal(fs.existsSync(activePath), false); + + fs.rmSync(root, { recursive: true, force: true }); +}); + +// A build that sanitized session names wrote the session `.active-session` to exactly the pointer +// path. The unnamed disconnect claims it there, and that claim drives the client and the teardown. +test.each([ + { leaseProvider: undefined, refusal: undefined }, + { leaseProvider: 'proxy', refusal: 'REMOTE_SESSION_REQUIRED' }, +])( + 'an unnamed disconnect of the older .active-session record at the pointer path (leaseProvider $leaseProvider)', + async ({ leaseProvider, refusal }) => { + const { root, home, project } = makeTempWorkspace(); + const stateDir = path.join(root, 'state'); + const connectionsDir = path.join(stateDir, 'remote-connections'); + fs.mkdirSync(connectionsDir, { recursive: true }); + const remoteConfig = path.join(project, 'agent-device.remote.json'); + fs.writeFileSync( + remoteConfig, + JSON.stringify({ daemonBaseUrl: 'http://remote-mac.example.test:9124/agent-device' }), + 'utf8', + ); + const session = '.active-session'; + fs.writeFileSync( + path.join(connectionsDir, '.active-session.json'), + JSON.stringify({ + version: 1, + session, + remoteConfigPath: remoteConfig, + remoteConfigHash: hashRemoteConfigFile(remoteConfig), + tenant: 'acme', + runId: 'run-legacy', + ...(leaseProvider ? { leaseProvider } : {}), + connectedAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }), + 'utf8', + ); + + const disconnected = await runCliCapture(['disconnect', '--state-dir', stateDir, '--json'], { + cwd: project, + env: { HOME: home }, + }); + + if (refusal) { + assert.equal(disconnected.code, 1); + assert.equal(JSON.parse(disconnected.stdout).error.details.reason, refusal); + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, 'run-legacy'); + } else { + assert.equal(disconnected.code, null); + assert.equal(JSON.parse(disconnected.stdout).data.session, session); + assert.equal(readRemoteConnectionState({ stateDir, session }), null); + assert.deepEqual(fs.readdirSync(connectionsDir), []); + } + + fs.rmSync(root, { recursive: true, force: true }); + }, +); diff --git a/src/cli.ts b/src/cli.ts index 86fb9c4715..a9ad962982 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -56,6 +56,7 @@ import { import { resolveCliOptions } from './cli/resolve-cli-options.ts'; import { maybeRunUpgradeNotifier } from './cli/update-check.ts'; import { + claimRemoteConnectionDefaults, remoteSessionRequiredError, resolveRemoteConnectionDefaults, type RemoteConnectionRequestMetadata, @@ -654,6 +655,7 @@ async function dispatchCliCommand( replayTestReporterRuntime, commandProgress, leaseDevice: ctx.leaseDevice, + claimedConnection: ctx.connectionDefaults?.claimed, }) ) { return; @@ -778,11 +780,7 @@ function resolveActiveConnectionDefaults(options: { stateDir: string; session: string | undefined; remoteConfig?: string; -}): { - flags: Partial; - runtime?: SessionRuntimeHints; - connection?: RemoteConnectionRequestMetadata; -} | null { +}) { if ( options.command === 'connect' || options.command === 'connection' || @@ -790,15 +788,16 @@ function resolveActiveConnectionDefaults(options: { ) { return null; } - const defaults = resolveRemoteConnectionDefaults({ + const request = { stateDir: options.stateDir, session: options.session, remoteConfig: options.remoteConfig, cwd: options.host.cwd, env: options.host.env, - validateRemoteConfigHash: options.command !== 'disconnect', - }); - return defaults; + }; + return options.command === 'disconnect' + ? claimRemoteConnectionDefaults(request) + : resolveRemoteConnectionDefaults(request); } // A command that cannot take a session runs on no remote connection. Reading, authenticating or diff --git a/src/cli/commands/connection-disconnect.test.ts b/src/cli/commands/connection-disconnect.test.ts index f122000ffc..8d1e3acdab 100644 --- a/src/cli/commands/connection-disconnect.test.ts +++ b/src/cli/commands/connection-disconnect.test.ts @@ -174,3 +174,157 @@ test('disconnect treats an already-inactive lease as released without a failure assert.equal(text.trim(), 'Disconnected remote session "adc-release-inactive".'); fs.rmSync(tempRoot, { recursive: true, force: true }); }); + +test('disconnect refuses a record it cannot remove before it closes the session or releases the lease', async () => { + const { tempRoot, stateDir } = seedReleasableConnection( + 'agent-device-disconnect-occupied-session-path-', + 'Demo', + ); + const recordsDir = path.join(stateDir, 'remote-connections'); + const [hashedName] = fs.readdirSync(recordsDir).filter((name) => name.startsWith('~')); + assert.ok(hashedName, 'the new build saves Demo at its hashed path'); + const hashedPath = path.join(recordsDir, hashedName); + // An older build connected Demo under a run of its own and saved it at the name it wrote. + const legacyPath = path.join(recordsDir, 'Demo.json'); + const legacy = JSON.parse(fs.readFileSync(hashedPath, 'utf8')); + fs.writeFileSync( + legacyPath, + JSON.stringify({ ...legacy, runId: 'run-legacy', leaseId: 'lease-legacy' }), + ); + let closed = 0; + let released = 0; + + await assert.rejects( + disconnectCommand({ + positionals: [], + flags: { json: true, help: false, version: false, stateDir, session: 'Demo' }, + client: createTestClient({ + closeSession: async () => { + closed += 1; + return { session: 'Demo', identifiers: { session: 'Demo' } }; + }, + release: async () => { + released += 1; + return { released: true }; + }, + }), + }), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'connection_session_mismatch', + ); + + assert.equal(closed, 0); + assert.equal(released, 0); + assert.equal(JSON.parse(fs.readFileSync(hashedPath, 'utf8')).leaseId, 'lease-1'); + assert.equal(JSON.parse(fs.readFileSync(legacyPath, 'utf8')).leaseId, 'lease-legacy'); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + +test('an unnamed disconnect removes an invalid default record and disconnects the active session', async () => { + const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( + 'agent-device-disconnect-invalid-default-', + ); + fs.writeFileSync(remoteConfigPath, '{}'); + seedConnectionState({ + stateDir, + state: { + session: 'demo', + remoteConfigPath, + tenant: 'acme', + runId: 'run-demo', + runtime: { platform: 'android', metroPort: 8081 }, + }, + }); + const recordsDir = path.join(stateDir, 'remote-connections'); + const defaultPath = path.join(recordsDir, 'default.json'); + const demoPath = path.join(recordsDir, 'demo.json'); + const activePath = path.join(recordsDir, '.active-session.json'); + const valid = JSON.parse(fs.readFileSync(demoPath, 'utf8')); + fs.writeFileSync(defaultPath, JSON.stringify({ ...valid, session: 'default', updatedAt: null })); + const closed: string[] = []; + + const text = await withCapturedStdoutAsync(async () => { + await disconnectCommand({ + positionals: [], + flags: { json: false, help: false, version: false, stateDir }, + client: createTestClient({ + closeSession: async (request) => { + closed.push(request?.session ?? ''); + return { session: 'demo', identifiers: { session: 'demo' } }; + }, + }), + }); + }); + + assert.equal(text.trim(), 'Disconnected remote session "demo".'); + assert.deepEqual(closed, ['demo']); + assert.equal(fs.existsSync(defaultPath), false); + assert.equal(fs.existsSync(demoPath), false); + assert.equal(fs.existsSync(activePath), false); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + +test.each([ + { + name: 'its own file', + session: 'demo', + fileName: 'demo.json', + record: { session: 'demo', version: 1, runId: 'run-demo', updatedAt: null }, + }, + // An older build saved Demo at the name it wrote, and the record holds only its session. + { + name: 'its older pointer-shaped file', + session: 'Demo', + fileName: 'Demo.json', + record: { session: 'Demo' }, + }, +])( + 'disconnect removes a record at $name that names its session but fails validation', + async ({ session, fileName, record }) => { + const { tempRoot, stateDir } = connectionWorkspace('agent-device-disconnect-invalid-record-'); + const recordsDir = path.join(stateDir, 'remote-connections'); + fs.mkdirSync(recordsDir, { recursive: true }); + fs.writeFileSync(path.join(recordsDir, fileName), JSON.stringify(record)); + fs.writeFileSync(path.join(recordsDir, '.active-session.json'), JSON.stringify({ session })); + + const text = await withCapturedStdoutAsync(async () => { + await disconnectCommand({ + positionals: [], + flags: { json: false, help: false, version: false, stateDir, session }, + client: createTestClient(), + }); + }); + + assert.equal(text.trim(), `No remote connection for "${session}".`); + assert.deepEqual(fs.readdirSync(recordsDir), []); + fs.rmSync(tempRoot, { recursive: true, force: true }); + }, +); + +// `--session=` names the empty session. Read as an omitted session, it followed the active-session +// pointer and removed the connection the pointer named for another session. +test('disconnect --session= with no empty-session record keeps the record the pointer names', async () => { + const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( + 'agent-device-connection-empty-session-', + ); + fs.writeFileSync(remoteConfigPath, '{}'); + seedConnectionState({ + stateDir, + state: { session: 'Demo', remoteConfigPath, tenant: 'acme', runId: 'run-Demo' }, + }); + + const stdout = await withCapturedStdoutAsync(async () => { + // Every call this client answers throws: the command may not reach the daemon. + await disconnectCommand({ + positionals: [], + flags: { json: true, help: false, version: false, stateDir, session: '' }, + client: createTestClient(), + }); + }); + + const payload = JSON.parse(stdout).data; + assert.equal(payload.connected, false); + assert.equal(payload.session, ''); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); diff --git a/src/cli/commands/connection-status-read-only.test.ts b/src/cli/commands/connection-status-read-only.test.ts new file mode 100644 index 0000000000..1b05ee5166 --- /dev/null +++ b/src/cli/commands/connection-status-read-only.test.ts @@ -0,0 +1,52 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { withCapturedStdoutAsync } from '@agent-device/test-kit'; +import { hashRemoteConfigFile } from '@agent-device/remote/remote-connection-state'; +import { + connectionWorkspace, + createTestClient, +} from '../../__tests__/remote-connection.fixtures.ts'; +import { connectionCommand } from '../../__tests__/test-utils/host-bound-commands.ts'; + +// `connection status` only reports the saved connection. A status read that moved an older build's +// record to its session's own file failed where the records directory could not be written. + +test('connection status --session Demo over an older Demo.json leaves the records directory unchanged', async () => { + const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( + 'agent-device-connection-status-read-only-', + ); + fs.writeFileSync(remoteConfigPath, '{}'); + const recordsDir = path.join(stateDir, 'remote-connections'); + fs.mkdirSync(recordsDir, { recursive: true }); + const now = new Date().toISOString(); + fs.writeFileSync( + path.join(recordsDir, 'Demo.json'), + `${JSON.stringify({ + version: 1, + session: 'Demo', + remoteConfigPath, + remoteConfigHash: hashRemoteConfigFile(remoteConfigPath), + tenant: 'acme', + runId: 'run-Demo', + connectedAt: now, + updatedAt: now, + })}\n`, + ); + + const stdout = await withCapturedStdoutAsync(async () => { + // Every call this client answers throws: status may not reach the daemon. + await connectionCommand({ + positionals: ['status'], + flags: { json: true, help: false, version: false, stateDir, session: 'Demo' }, + client: createTestClient(), + }); + }); + + const payload = JSON.parse(stdout).data; + assert.equal(payload.session, 'Demo'); + assert.equal(payload.runId, 'run-Demo'); + assert.deepEqual(fs.readdirSync(recordsDir), ['Demo.json'], 'status moved no file'); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 9ebcafac2a..1dc4c60a47 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -3,6 +3,7 @@ import type { CloudProviderSessionResult } from '@agent-device/contracts/observa import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import { resolveRemoteConfigProfile } from '@agent-device/remote/remote-config'; import { + claimRemoteConnectionState, readActiveConnectionState, requireLeasedConnectionSession, sessionLeaseScope, @@ -335,12 +336,33 @@ function scopeConnectProfile( }; } -export const disconnectCommand: ClientCommandHandler = async ({ flags, client, host }) => { - const { session, stateDir, state } = readRequestedConnectionState(flags, host); +/** + * The record moves to its session's own path before any teardown, so a record this command cannot + * remove is refused before its session closes or its lease ends. The CLI claims it before it builds + * the client, and that claim is the one torn down. + */ +function claimDisconnectTarget( + claimedConnection: RemoteConnectionState | null | undefined, + stateDir: string, + session: string | undefined, +): RemoteConnectionState | null { + if (claimedConnection !== undefined) return claimedConnection; + return claimRemoteConnectionState({ stateDir, session }); +} + +export const disconnectCommand: ClientCommandHandler = async ({ + flags, + client, + host, + claimedConnection, +}) => { + const stateDir = resolveConnectionStateDir(flags, host); + const state = claimDisconnectTarget(claimedConnection, stateDir, flags.session); if (!state) { - await writeNoRemoteConnectionOutput(flags, session); + await writeNoRemoteConnectionOutput(flags, flags.session ?? 'default'); return true; } + requireLeasedConnectionSession(state, flags.session); const connectedSession = state.session; let providerData: CloudProviderSessionResult | undefined; @@ -475,19 +497,21 @@ function readRequestedConnectionState( host: HostEnvironment, ): { session: string; - stateDir: string; state: RemoteConnectionState | null; } { const session = flags.session ?? 'default'; - const stateDir = resolveDaemonPaths(flags.stateDir, { - cwd: host.cwd, - env: host.env, - }).baseDir; + const stateDir = resolveConnectionStateDir(flags, host); + // Only a caller that named no session follows the active-session pointer. `--session=` names the + // empty session. const state = readRemoteConnectionState({ stateDir, session }) ?? - (flags.session ? null : readActiveConnectionState({ stateDir })); + (flags.session === undefined ? readActiveConnectionState({ stateDir }) : null); if (state) requireLeasedConnectionSession(state, flags.session); - return { session, stateDir, state }; + return { session, state }; +} + +function resolveConnectionStateDir(flags: CliFlags, host: HostEnvironment): string { + return resolveDaemonPaths(flags.stateDir, { cwd: host.cwd, env: host.env }).baseDir; } async function writeNoRemoteConnectionOutput(flags: CliFlags, session: string): Promise { diff --git a/src/cli/commands/router-types.ts b/src/cli/commands/router-types.ts index 83ba4611ac..a76992ba08 100644 --- a/src/cli/commands/router-types.ts +++ b/src/cli/commands/router-types.ts @@ -1,6 +1,7 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { CliFlags } from '@agent-device/contracts/command'; import type { LeaseDevice } from '@agent-device/contracts/client'; +import type { RemoteConnectionState } from '@agent-device/remote/remote-connection-state'; import type { AgentDeviceClient } from '@agent-device/command-surface'; import type { CliCommandName } from '@agent-device/command-registry/catalog'; import type { CommandProgressState } from '@agent-device/command-output'; @@ -18,6 +19,8 @@ export type ClientCommandParams = { commandProgress?: CommandProgressState; /** The device a proxy backend granted for the lease's device spec; `open` reports it. */ leaseDevice?: LeaseDevice; + /** The record `disconnect` claimed before its client was built, or `null` when it claimed none. */ + claimedConnection?: RemoteConnectionState | null; }; /** diff --git a/src/cli/commands/router.ts b/src/cli/commands/router.ts index 6b1468e8e7..57b98afa0f 100644 --- a/src/cli/commands/router.ts +++ b/src/cli/commands/router.ts @@ -35,6 +35,7 @@ export async function tryRunClientBackedCommand(params: { replayTestReporterRuntime?: ClientCommandParams['replayTestReporterRuntime']; commandProgress?: ClientCommandParams['commandProgress']; leaseDevice?: ClientCommandParams['leaseDevice']; + claimedConnection?: ClientCommandParams['claimedConnection']; }): Promise { const flags = { ...params.flags }; const loadDedicatedHandler = diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 7a99b1b7dd..384c0d51d8 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2600,6 +2600,8 @@ Exact behavior: `agent-device help disconnect`. +If agent-device cannot read or parse a session's own saved connection file or the active-session pointer, it cannot establish which session owns that file. It keeps the file and refuses with `connection_record_owner_unknown`. A session's own saved connection file that cannot be read refuses every command that uses that session's saved connection. An unreadable active-session pointer refuses `connect` and any command that rewrites the saved connection. The error names the file. Make it readable, or remove it if no session needs it. A file from an older build whose owner cannot be proven is left in place and is not used. A command that only reads the saved connection, such as `connection status`, changes no file. It uses an older build's file for the session where that file is, and it treats a file that fails validation as no connection. Only a command that saves or removes the saved connection moves an older file to its session's own file, or removes a file that fails validation. If an older file cannot move because its session's own file already exists, that command refuses with `connection_session_mismatch`. The refused file is kept, and so is the occupied session file. This is also true when both files name the same session, and when the occupied file cannot be read. + Manage cloud login state. diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 9091c1f074..cbd756a016 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -726,6 +726,13 @@ These reasons can come from more than one command. | `CONNECTION_DEVICE_CONFLICT` | The connection is bound to another device, or its lease was allocated by another device spec; `details.keys` names the disagreeing keys, and is present only for a device-spec mismatch. | | `CONNECTION_PLATFORM_CONFLICT` | The connection is bound to another platform, or the request names one its lease backend does not rent. | +### Remote connections + +| Reason | Meaning | +| --- | --- | +| `connection_session_mismatch` | A saved connection file cannot be used for the session a command named: it names another session, a record from an older build cannot move to its session file because that file already exists, or the active-session pointer path holds a record whose owner is unproven. The refused file is kept, and so is the occupied session file. | +| `connection_record_owner_unknown` | The session's own saved connection file, or the active-session pointer, could not be read or parsed, so no session is known to own it. It was neither replaced nor removed. | + ### Remote daemon | Reason | Meaning |