Skip to content

Commit 5968975

Browse files
committed
fix(remote): verify the previous config file still speaks for its endpoint
Rule 1 reads the previous connection's own config file to recover a credential that provably belongs to the previous endpoint. It re-read `previous.remoteConfigPath` and trusted whatever token that file holds *now* — but a config path is routinely reused, so "connect to A from ./remote.json, re-point ./remote.json at B, connect --force" classified B's token as A's own and sent it to A during lease release. Same cross-endpoint leak the env-merge fix closed, arriving through the file instead of the environment. The file must now still vouch for the previous endpoint, by either of two independent facts: its bytes still hash to the `remoteConfigHash` recorded at connect time (so it is literally the declaration that stood up the previous connection), or — if it changed — it still declares the same daemon base URL. The second is what keeps an ordinary credential rotation releasing its lease instead of orphaning one; endpoint equality, not the fact of an edit, is what separates rotation from re-pointing. Endpoint comparison runs both sides through `buildRemoteConnectionDaemonState`, the same normalizer that produced the stored `daemon.baseUrl`. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017Rva4YGtSCAKJqH5PbpcCU
1 parent d79bf78 commit 5968975

2 files changed

Lines changed: 202 additions & 2 deletions

File tree

‎src/__tests__/remote-connection.test.ts‎

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2236,6 +2236,157 @@ test('connect --force does not misclassify an env-sourced new token as the previ
22362236
fs.rmSync(tempRoot, { recursive: true, force: true });
22372237
});
22382238

2239+
test('connect --force does not treat a re-pointed config path’s token as the previous endpoint’s own', async () => {
2240+
const tempRoot = mkdtempForTestSync('agent-device-connect-force-repointed-path-');
2241+
const stateDir = path.join(tempRoot, '.state');
2242+
// ONE path, reused. The previous connection was made against old.example
2243+
// through this file; the file is then edited in place to describe a
2244+
// different endpoint with a different credential. Distinct old/new paths
2245+
// cannot express this: the leak is that `remoteConfigPath` still resolves,
2246+
// and still parses, while no longer describing the connection it is being
2247+
// consulted about.
2248+
const remoteConfigPath = path.join(tempRoot, 'remote.json');
2249+
fs.writeFileSync(
2250+
remoteConfigPath,
2251+
JSON.stringify({
2252+
daemonBaseUrl: 'https://old.example',
2253+
daemonAuthToken: 'test-old-not-a-real-token',
2254+
}),
2255+
);
2256+
writeRemoteConnectionState({
2257+
stateDir,
2258+
state: {
2259+
version: 1,
2260+
session: 'adc-android',
2261+
remoteConfigPath,
2262+
// Recorded while the file still described old.example — the fact that
2263+
// makes the later edit detectable.
2264+
remoteConfigHash: hashRemoteConfigFile(remoteConfigPath),
2265+
tenant: 'acme',
2266+
runId: 'run-old',
2267+
leaseId: 'lease-old',
2268+
leaseBackend: 'android-instance',
2269+
daemon: { baseUrl: 'https://old.example' },
2270+
connectedAt: new Date().toISOString(),
2271+
updatedAt: new Date().toISOString(),
2272+
},
2273+
});
2274+
// The edit: same path, now endpoint B with token B.
2275+
fs.writeFileSync(
2276+
remoteConfigPath,
2277+
JSON.stringify({
2278+
daemonBaseUrl: 'https://new.example',
2279+
daemonAuthToken: 'test-new-not-a-real-token',
2280+
}),
2281+
);
2282+
let releaseRequest: Parameters<AgentDeviceClient['leases']['release']>[0] | undefined;
2283+
2284+
const stdout = await captureStdout(async () => {
2285+
await connectCommand({
2286+
positionals: [],
2287+
flags: {
2288+
json: false,
2289+
help: false,
2290+
version: false,
2291+
force: true,
2292+
stateDir,
2293+
remoteConfig: remoteConfigPath,
2294+
daemonBaseUrl: 'https://new.example',
2295+
tenant: 'acme',
2296+
runId: 'run-new',
2297+
session: 'adc-android',
2298+
platform: 'android',
2299+
},
2300+
client: createTestClient({
2301+
release: async (request) => {
2302+
releaseRequest = request;
2303+
return { released: true };
2304+
},
2305+
}),
2306+
});
2307+
});
2308+
2309+
// No request at all — not merely a request carrying a different token.
2310+
assert.equal(releaseRequest, undefined);
2311+
assert.match(stdout, /Could not release the previous lease lease-old/);
2312+
assert.match(stdout, /old\.example/);
2313+
assert.equal(readRemoteConnectionState({ stateDir, session: 'adc-android' })?.runId, 'run-new');
2314+
fs.rmSync(tempRoot, { recursive: true, force: true });
2315+
});
2316+
2317+
test('connect --force still releases with a rotated credential when the config keeps the same endpoint', async () => {
2318+
const tempRoot = mkdtempForTestSync('agent-device-connect-force-rotated-token-');
2319+
const stateDir = path.join(tempRoot, '.state');
2320+
const remoteConfigPath = path.join(tempRoot, 'remote.json');
2321+
const newRemoteConfigPath = path.join(tempRoot, 'new-remote.json');
2322+
fs.writeFileSync(
2323+
remoteConfigPath,
2324+
JSON.stringify({
2325+
daemonBaseUrl: 'https://old.example',
2326+
daemonAuthToken: 'test-old-not-a-real-token',
2327+
}),
2328+
);
2329+
fs.writeFileSync(newRemoteConfigPath, JSON.stringify({ daemonBaseUrl: 'https://new.example' }));
2330+
writeRemoteConnectionState({
2331+
stateDir,
2332+
state: {
2333+
version: 1,
2334+
session: 'adc-android',
2335+
remoteConfigPath,
2336+
remoteConfigHash: hashRemoteConfigFile(remoteConfigPath),
2337+
tenant: 'acme',
2338+
runId: 'run-old',
2339+
leaseId: 'lease-old',
2340+
leaseBackend: 'android-instance',
2341+
daemon: { baseUrl: 'https://old.example' },
2342+
connectedAt: new Date().toISOString(),
2343+
updatedAt: new Date().toISOString(),
2344+
},
2345+
});
2346+
// The file changed — so the hash no longer matches — but it still describes
2347+
// old.example, so the rotated token is still that endpoint's own credential
2348+
// and must still release its lease. This is the case an edit-detecting rule
2349+
// must not break: refusing here would orphan leases on every key rotation.
2350+
fs.writeFileSync(
2351+
remoteConfigPath,
2352+
JSON.stringify({
2353+
daemonBaseUrl: 'https://old.example',
2354+
daemonAuthToken: 'test-rotated-not-a-real-token',
2355+
}),
2356+
);
2357+
let releaseRequest: Parameters<AgentDeviceClient['leases']['release']>[0] | undefined;
2358+
2359+
await captureStdout(async () => {
2360+
await connectCommand({
2361+
positionals: [],
2362+
flags: {
2363+
json: true,
2364+
help: false,
2365+
version: false,
2366+
force: true,
2367+
stateDir,
2368+
remoteConfig: newRemoteConfigPath,
2369+
daemonBaseUrl: 'https://new.example',
2370+
tenant: 'acme',
2371+
runId: 'run-new',
2372+
session: 'adc-android',
2373+
platform: 'android',
2374+
},
2375+
client: createTestClient({
2376+
release: async (request) => {
2377+
releaseRequest = request;
2378+
return { released: true };
2379+
},
2380+
}),
2381+
});
2382+
});
2383+
2384+
assert.equal(releaseRequest?.leaseId, 'lease-old');
2385+
assert.equal(releaseRequest?.daemonBaseUrl, 'https://old.example');
2386+
assert.equal(releaseRequest?.daemonAuthToken, 'test-rotated-not-a-real-token');
2387+
fs.rmSync(tempRoot, { recursive: true, force: true });
2388+
});
2389+
22392390
test('connect --force reuses the ambient token to release the previous lease when the endpoint is unchanged', async () => {
22402391
const tempRoot = mkdtempForTestSync('agent-device-connect-force-same-endpoint-');
22412392
const stateDir = path.join(tempRoot, '.state');

‎src/cli/commands/connection-runtime.ts‎

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -545,18 +545,67 @@ function resolvePreviousOwnDaemonAuthToken(
545545
// masquerade as a credential that provably belongs to the *previous*
546546
// endpoint. Only a token the previous config file itself declares counts
547547
// here; the env fallback is rule 2's job, gated on matching endpoints.
548-
return readRemoteConfigFile({
548+
const { profile } = readRemoteConfigFile({
549549
configPath: previous.remoteConfigPath,
550550
cwd,
551551
env,
552-
}).profile.daemonAuthToken;
552+
});
553+
if (!profile.daemonAuthToken) return undefined;
554+
// The path alone is not provenance. `remoteConfigPath` names a file *now*,
555+
// while the claim being made is about what that file declared when the
556+
// previous connection was established — and a config path is routinely
557+
// reused (edited in place, re-pointed at a second environment) between the
558+
// two. Without this check, "connect to A from ./remote.json, re-point
559+
// ./remote.json at B, connect --force" reads B's token as A's own and
560+
// sends it to A during lease release: the same cross-endpoint leak the
561+
// env-merge fix closed, arriving through the file instead.
562+
return previousConfigStillSpeaksForPreviousEndpoint(previous, profile.daemonBaseUrl)
563+
? profile.daemonAuthToken
564+
: undefined;
553565
} catch {
554566
// A missing/unparseable previous config is the "cannot authenticate"
555567
// case handled by the caller, not an error to propagate here.
556568
return undefined;
557569
}
558570
}
559571

572+
/**
573+
* Whether the previous connection's config file can still vouch for a token as
574+
* belonging to the previous connection's endpoint.
575+
*
576+
* Two independent ways to establish that, in order:
577+
*
578+
* 1. **The file has not changed since connect time.** `remoteConfigHash` is a
579+
* hash of the file's bytes taken when the connection was recorded, so an
580+
* exact match means this is literally the declaration that stood up the
581+
* previous connection. Nothing further to verify.
582+
* 2. **The file changed, but still declares the same endpoint.** The common
583+
* benign case is a rotated credential in an otherwise unchanged profile,
584+
* which is still the previous endpoint's own credential and should still
585+
* release its lease. Endpoint equality is what separates that from the
586+
* re-pointed-file case, so it — not the mere fact of an edit — is the test.
587+
*
588+
* The endpoint comparison runs both sides through
589+
* `buildRemoteConnectionDaemonState`, the same normalizer that produced the
590+
* stored `daemon.baseUrl`, so it compares like with like rather than raw
591+
* strings that differ only by a trailing slash.
592+
*
593+
* A file that changed and no longer declares an endpoint at all cannot vouch
594+
* for anything: the caller then falls back to rule 2 (matching endpoints) or
595+
* reports the lease as unreleasable, which is a warning and an orphaned lease
596+
* — the correct price for not sending a credential somewhere it may not belong.
597+
*/
598+
function previousConfigStillSpeaksForPreviousEndpoint(
599+
previous: RemoteConnectionState,
600+
declaredDaemonBaseUrl: string | undefined,
601+
): boolean {
602+
if (hashRemoteConfigFile(previous.remoteConfigPath) === previous.remoteConfigHash) return true;
603+
const declared = buildRemoteConnectionDaemonState({
604+
daemonBaseUrl: declaredDaemonBaseUrl,
605+
})?.baseUrl;
606+
return declared !== undefined && declared === previous.daemon?.baseUrl;
607+
}
608+
560609
export async function releasePreviousLease(
561610
client: AgentDeviceClient,
562611
previous: RemoteConnectionState,

0 commit comments

Comments
 (0)