Skip to content

Commit edff907

Browse files
committed
fix(daemon): scope the fingerprint bypass to two installed trees
An installed client declined the code comparison on the strength of its own tree alone, which left whatever is already running unverified: a source checkout that shares an explicit --state-dir can publish any code it likes under a published version string, and the installed client would have run it (#2458 review). A daemon now records which tree it started from beside its signature, and the bypass is pairwise — it holds only where both sides say they are installs of that version. A checkout still judges a checkout by signature; a pair whose trees cannot match at all restarts the daemon rather than run code it cannot identify, which is also the rule a daemon too old to report an origin is judged by. Closes #2458
1 parent 5fef822 commit edff907

10 files changed

Lines changed: 262 additions & 67 deletions

File tree

‎packages/host-kit/src/code-signature.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import crypto from 'node:crypto';
22
import fs from 'node:fs';
33
import path from 'node:path';
4-
import { findProjectRoot } from './version.ts';
4+
import { findProjectRoot, isSourceCheckoutProjectRoot } from './version.ts';
55

66
// Any quoted, relative-path-shaped string literal is treated as a module
77
// specifier, rather than matching the `import`/`export`/`from` grammar
@@ -61,6 +61,23 @@ export function resolveDaemonCodeSignature(): string {
6161
return computeDaemonCodeSignature(entryPath);
6262
}
6363

64+
/**
65+
* Which tree a daemon's code came from, and so what could have changed it since the
66+
* version it reports.
67+
*
68+
* A signature only means something against a tree that can be re-read, so this answers
69+
* first: two installed trees of one version hold the same artifact and have nothing to
70+
* compare (#2458), while a checkout's code moves under a version that does not move
71+
* with it. A running daemon publishes its own answer beside its signature
72+
* (`src/daemon/server/server-lifecycle.ts`) because the question is about the code that
73+
* is RUNNING, not only about the client asking it.
74+
*/
75+
export type DaemonCodeOrigin = 'installed' | 'checkout';
76+
77+
export function resolveDaemonCodeOrigin(root: string = findProjectRoot()): DaemonCodeOrigin {
78+
return isSourceCheckoutProjectRoot(root) ? 'checkout' : 'installed';
79+
}
80+
6481
export function computeDaemonCodeSignature(
6582
entryPath: string,
6683
root: string = findProjectRoot(),
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import assert from 'node:assert/strict';
2+
import fs from 'node:fs';
3+
import path from 'node:path';
4+
import { test } from 'vitest';
5+
import type { DaemonCodeOrigin } from '@agent-device/host-kit/code-signature';
6+
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
7+
import { writeInfo } from '../../daemon/server/server-lifecycle.ts';
8+
import { readDaemonInfo } from '../daemon-client-metadata.ts';
9+
10+
// The reuse decision is only as good as the identity that survives the round trip
11+
// through `daemon.json`: a client cannot compare what the file lost (#2458).
12+
13+
function scratchStateDir(): [stateDir: string, infoPath: string] {
14+
const stateDir = mkdtempForTestSync('agent-device-daemon-identity-');
15+
return [stateDir, path.join(stateDir, 'daemon.json')];
16+
}
17+
18+
function publishInfo(codeOrigin: DaemonCodeOrigin): string {
19+
const [stateDir, infoPath] = scratchStateDir();
20+
writeInfo(stateDir, infoPath, path.join(stateDir, 'daemon.log'), {
21+
httpPort: 41_234,
22+
token: 'local-secret',
23+
version: '0.0.0-test',
24+
codeOrigin,
25+
codeSignature: 'graph:1:abc',
26+
processStartTime: 'start',
27+
});
28+
return infoPath;
29+
}
30+
31+
test('a daemon publishes the code origin its client reads back', () => {
32+
for (const codeOrigin of ['installed', 'checkout'] as const) {
33+
assert.equal(readDaemonInfo(publishInfo(codeOrigin))?.codeOrigin, codeOrigin);
34+
}
35+
});
36+
37+
test('a registration this version did not write reads back unreported', () => {
38+
// Shaped like a daemon published before the field existed, and like a value no
39+
// version of this writer produces.
40+
for (const contents of [
41+
{ httpPort: 41_234, token: 'local-secret', pid: 7 },
42+
{ httpPort: 41_234, token: 'local-secret', pid: 7, codeOrigin: 'something-else' },
43+
]) {
44+
const [, infoPath] = scratchStateDir();
45+
fs.writeFileSync(infoPath, JSON.stringify(contents));
46+
47+
assert.equal(readDaemonInfo(infoPath)?.codeOrigin, undefined);
48+
}
49+
});

‎src/daemon-client/__tests__/daemon-launch-spec.test.ts‎

Lines changed: 99 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { computeDaemonCodeSignature } from '@agent-device/host-kit/code-signatur
66
import {
77
resolveDaemonLaunchSpec,
88
resolveDaemonTakeoverReason,
9-
resolveLocalDaemonCodeSignature,
9+
resolveLocalDaemonCodeIdentity,
1010
} from '../daemon-launch-spec.ts';
1111
import { isSourceCheckoutProjectRoot, readVersion } from '@agent-device/host-kit/version';
1212
import { resetAllProcessMemosForTests } from '@agent-device/kernel/ttl-memo';
@@ -26,10 +26,17 @@ afterEach(() => {
2626
vi.mocked(isSourceCheckoutProjectRoot).mockReset();
2727
});
2828

29+
/** This tree's fingerprint, or `undefined` when the tree is an installed package. */
30+
function ownCheckoutCodeSignature(): Promise<string | undefined> {
31+
return resolveLocalDaemonCodeIdentity().then((identity) =>
32+
identity.origin === 'checkout' ? identity.codeSignature : undefined,
33+
);
34+
}
35+
2936
// A source checkout re-reads the launch entry and its code signature on every
3037
// command. The entry is fixed for the process; the signature is not, so it stays
31-
// live and leans on the stat-validated cache instead. An installed package has no
32-
// signature to re-read: its version pins its bytes (`#2458`).
38+
// live and leans on the stat-validated cache instead. An installed package reports
39+
// an origin and no signature at all: its version pins its bytes (`#2458`).
3340

3441
test('resolveDaemonLaunchSpec probes the entry candidates once per process', () => {
3542
resetAllProcessMemosForTests();
@@ -44,12 +51,13 @@ test('resolveDaemonLaunchSpec probes the entry candidates once per process', ()
4451
assert.equal(existsSpy.mock.calls.length, probeCalls);
4552
});
4653

47-
test('resolveLocalDaemonCodeSignature re-reads the filesystem on every call', async () => {
54+
test('the local code identity re-reads the filesystem on every call', async () => {
4855
resetAllProcessMemosForTests();
4956

50-
const first = await resolveLocalDaemonCodeSignature();
57+
const first = await ownCheckoutCodeSignature();
58+
assert.ok(first);
5159
const statSpy = vi.spyOn(fs, 'statSync');
52-
const second = await resolveLocalDaemonCodeSignature();
60+
const second = await ownCheckoutCodeSignature();
5361

5462
assert.equal(second, first);
5563
// Not memoized in either mode: a long-lived client (the MCP server) has to
@@ -58,15 +66,12 @@ test('resolveLocalDaemonCodeSignature re-reads the filesystem on every call', as
5866
assert.ok(statSpy.mock.calls.length > 0);
5967
});
6068

61-
test('resolveLocalDaemonCodeSignature agrees with the uncached walk over the launch entry', async () => {
69+
test('the local signature agrees with the uncached walk over the launch entry', async () => {
6270
resetAllProcessMemosForTests();
6371
const spec = resolveDaemonLaunchSpec();
6472
const entryPath = spec.useSrc ? spec.srcPath : spec.distPath;
6573

66-
assert.equal(
67-
await resolveLocalDaemonCodeSignature(),
68-
computeDaemonCodeSignature(entryPath, spec.root),
69-
);
74+
assert.equal(await ownCheckoutCodeSignature(), computeDaemonCodeSignature(entryPath, spec.root));
7075
});
7176

7277
test('a source client fingerprints the source entry through the stat-validated cache', async () => {
@@ -80,10 +85,10 @@ test('a source client fingerprints the source entry through the stat-validated c
8085
const spec = resolveDaemonLaunchSpec();
8186
assert.equal(spec.useSrc, true);
8287
const expected = computeDaemonCodeSignature(spec.srcPath, spec.root);
83-
assert.equal(await resolveLocalDaemonCodeSignature(), expected);
88+
assert.equal(await ownCheckoutCodeSignature(), expected);
8489

8590
const readSpy = vi.spyOn(fs, 'readFileSync');
86-
assert.equal(await resolveLocalDaemonCodeSignature(), expected);
91+
assert.equal(await ownCheckoutCodeSignature(), expected);
8792
const sourceReads = readSpy.mock.calls
8893
.map(([target]) => target)
8994
.filter((target): target is string => typeof target === 'string')
@@ -98,67 +103,123 @@ test('a source client fingerprints the source entry through the stat-validated c
98103
/**
99104
* Which daemon a command keeps. `daemon-client-lifecycle.test.ts` pins the same
100105
* decision end to end from a source checkout, which is what this test process runs
101-
* in; these cases flip the one input that separates a checkout from an installed
102-
* package of a published version (#2458).
106+
* in; these cases flip the two inputs that separate the trees — which tree this client
107+
* runs from, and which tree the running daemon says it was started from (#2458).
103108
*/
104109
function useClientTree(sourceCheckout: boolean): void {
105110
vi.mocked(isSourceCheckoutProjectRoot).mockReturnValue(sourceCheckout);
106111
}
107112

108-
function runningDaemon(info: { version?: string; codeSignature?: string }) {
113+
function runningDaemon(info: {
114+
version?: string;
115+
codeOrigin?: 'installed' | 'checkout';
116+
codeSignature?: string;
117+
}) {
109118
return {
110119
token: 'local-secret',
111120
pid: 999_999,
112121
httpPort: 41_234,
113122
transport: 'http' as const,
114123
version: info.version ?? readVersion(),
124+
codeOrigin: info.codeOrigin,
115125
codeSignature: info.codeSignature,
116126
};
117127
}
118128

119-
test('an installed client fingerprints nothing, because its version pins its bytes (#2458)', async () => {
129+
test('an installed client reports an origin and no signature, because its version pins its bytes (#2458)', async () => {
120130
// Two installs of one published version stamp identical bytes with different
121131
// mtimes, so a signature can only ever say "different" about the same code.
122132
resetAllProcessMemosForTests();
123133
useClientTree(false);
124134
const statSpy = vi.spyOn(fs, 'statSync');
125135

126-
assert.equal(await resolveLocalDaemonCodeSignature(), undefined);
136+
assert.deepEqual(await resolveLocalDaemonCodeIdentity(), { origin: 'installed' });
127137
assert.equal(statSpy.mock.calls.length, 0);
128138
});
129139

130-
test('an installed client keeps a reachable daemon whose code signature differs from its own (#2458)', async () => {
140+
test('an installed client keeps an installed daemon whose code signature differs (#2458)', async () => {
141+
// Both sides are installs of the version they report, so that version is the
142+
// whole of the identity either can offer, and the session on the daemon stands.
131143
useClientTree(false);
132144

133145
assert.equal(
134-
await resolveDaemonTakeoverReason(runningDaemon({ codeSignature: 'some-other-install' }), true),
146+
await resolveDaemonTakeoverReason(
147+
runningDaemon({ codeOrigin: 'installed', codeSignature: 'some-other-install' }),
148+
true,
149+
),
135150
undefined,
136151
);
137152
});
138153

139-
test('a source checkout keeps a reachable daemon whose code signature matches its own', async () => {
154+
test('an installed client replaces a daemon that reports a source checkout (#2458)', async () => {
155+
// The bypass is pairwise. A checkout beside a shared `--state-dir` can publish any
156+
// code it likes under the published version string, and an installed client has no
157+
// fingerprint of its own to notice.
158+
useClientTree(false);
159+
160+
assert.equal(
161+
await resolveDaemonTakeoverReason(
162+
runningDaemon({ codeOrigin: 'checkout', codeSignature: 'edited-checkout' }),
163+
true,
164+
),
165+
'code origin mismatch (daemon checkout, client installed)',
166+
);
167+
});
168+
169+
test('an installed client replaces a daemon that predates the code origin field (#2458)', async () => {
170+
useClientTree(false);
171+
172+
assert.equal(
173+
await resolveDaemonTakeoverReason(runningDaemon({ codeSignature: 'any' }), true),
174+
'code origin mismatch (daemon unreported, client installed)',
175+
);
176+
});
177+
178+
test('a source checkout keeps a daemon that reports the same code signature', async () => {
140179
useClientTree(true);
141-
const ownCodeSignature = await resolveLocalDaemonCodeSignature();
180+
const ownCodeSignature = await ownCheckoutCodeSignature();
142181
assert.ok(ownCodeSignature);
143182

144183
assert.equal(
145-
await resolveDaemonTakeoverReason(runningDaemon({ codeSignature: ownCodeSignature }), true),
184+
await resolveDaemonTakeoverReason(
185+
runningDaemon({ codeOrigin: 'checkout', codeSignature: ownCodeSignature }),
186+
true,
187+
),
146188
undefined,
147189
);
148190
});
149191

150-
test('a source checkout replaces a reachable daemon whose code signature differs', async () => {
192+
test('a source checkout replaces a daemon whose code signature differs', async () => {
151193
// A rebuild leaves the version alone, so the signature is the only thing that can
152194
// notice a daemon serving code its client no longer has.
153195
useClientTree(true);
154196

155197
assert.equal(
156-
await resolveDaemonTakeoverReason(runningDaemon({ codeSignature: 'an-older-build' }), true),
198+
await resolveDaemonTakeoverReason(
199+
runningDaemon({ codeOrigin: 'checkout', codeSignature: 'an-older-build' }),
200+
true,
201+
),
157202
'code-signature mismatch',
158203
);
159204
});
160205

161-
test('a source checkout replaces a daemon that reported no code signature at all', async () => {
206+
test('a source checkout replaces a daemon that reports an installed package', async () => {
207+
// The pair #2458 lets through is two installs; a checkout can still neither prove
208+
// nor disprove what an install holds, and must not run it on faith.
209+
useClientTree(true);
210+
211+
assert.equal(
212+
await resolveDaemonTakeoverReason(
213+
runningDaemon({ codeOrigin: 'installed', codeSignature: 'the-published-artifact' }),
214+
true,
215+
),
216+
'code origin mismatch (daemon installed, client checkout)',
217+
);
218+
});
219+
220+
test('a source checkout judges a daemon that predates the code origin field by its signature', async () => {
221+
// Every daemon published before the field answered with a signature, which is the
222+
// comparison they were reused under until now.
162223
useClientTree(true);
163224

164225
assert.equal(
@@ -174,27 +235,33 @@ test('a mismatched version replaces the daemon whichever tree the client runs fr
174235

175236
assert.equal(
176237
await resolveDaemonTakeoverReason(
177-
runningDaemon({ version: '0.0.0-mismatch', codeSignature: 'any' }),
238+
runningDaemon({ version: '0.0.0-mismatch', codeOrigin: 'installed', codeSignature: 'any' }),
178239
true,
179240
),
180241
expected,
181242
);
182243
}
183244
});
184245

185-
test('a reachable daemon of a matching version survives, an unreachable one does not', async () => {
246+
test('a reachable daemon of a matching identity survives, an unreachable one does not', async () => {
186247
useClientTree(false);
187248

188-
assert.equal(await resolveDaemonTakeoverReason(runningDaemon({}), true), undefined);
189-
assert.equal(await resolveDaemonTakeoverReason(runningDaemon({}), false), 'unreachable');
249+
assert.equal(
250+
await resolveDaemonTakeoverReason(runningDaemon({ codeOrigin: 'installed' }), true),
251+
undefined,
252+
);
253+
assert.equal(
254+
await resolveDaemonTakeoverReason(runningDaemon({ codeOrigin: 'installed' }), false),
255+
'unreachable',
256+
);
190257
});
191258

192259
test('the tree shape is asked per call, not memoized with the signature', async () => {
193260
// A long-lived client (the MCP server) must notice a daemon rebuilt underneath it,
194261
// so nothing about this answer is cached — including which tree it came from.
195262
useClientTree(false);
196-
assert.equal(await resolveLocalDaemonCodeSignature(), undefined);
263+
assert.deepEqual(await resolveLocalDaemonCodeIdentity(), { origin: 'installed' });
197264

198265
useClientTree(true);
199-
assert.ok(await resolveLocalDaemonCodeSignature());
266+
assert.ok(await ownCheckoutCodeSignature());
200267
});

‎src/daemon-client/daemon-client-metadata.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { shellQuote } from '@agent-device/host-kit/command';
33
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
44
import { isAgentDeviceDaemonProcess, stopProcessForTakeover } from '../daemon/daemon-process.ts';
55

6+
import type { DaemonCodeOrigin } from '@agent-device/host-kit/code-signature';
7+
68
import { resolveDaemonPaths, type DaemonPaths, type DaemonServerMode } from '../daemon/config.ts';
79

810
export type DaemonInfo = {
@@ -12,6 +14,7 @@ export type DaemonInfo = {
1214
token: string;
1315
pid: number;
1416
version?: string;
17+
codeOrigin?: DaemonCodeOrigin;
1518
codeSignature?: string;
1619
processStartTime?: string;
1720
baseUrl?: string;
@@ -58,6 +61,7 @@ export function readDaemonInfo(infoPath: string): DaemonInfo | null {
5861
transport: readDaemonInfoTransport(parsed.transport),
5962
pid: readPositiveInteger(parsed.pid) ?? 0,
6063
version: readOptionalString(parsed.version),
64+
codeOrigin: readDaemonInfoCodeOrigin(parsed.codeOrigin),
6165
codeSignature: readOptionalString(parsed.codeSignature),
6266
processStartTime: readOptionalString(parsed.processStartTime),
6367
};
@@ -76,6 +80,10 @@ function readDaemonInfoPorts(
7680
return { port, httpPort };
7781
}
7882

83+
function readDaemonInfoCodeOrigin(value: unknown): DaemonInfo['codeOrigin'] {
84+
return value === 'installed' || value === 'checkout' ? value : undefined;
85+
}
86+
7987
function readDaemonInfoTransport(value: unknown): DaemonInfo['transport'] {
8088
return value === 'socket' || value === 'http' || value === 'dual' ? value : undefined;
8189
}

0 commit comments

Comments
 (0)