Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions docs/agents/security.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
# Security boundaries

The CLI client trusts its caller to choose local destinations.
The client trusts a remote daemon for data and validated identifiers.
Scripts and remote record stop reject daemon paths (#4518). Trace and perf take them.
The daemon admits its state directory. Nobody trusts the network or other local users.
The caller chooses local destinations.
Scripts and remote record stop reject daemon paths (#4518).
Pathless trace and perf stops require a matching capture ID to reuse start paths.
When the capture is foreign, specify a stop path.
The daemon admits its state directory; network and other users are untrusted.
Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems.
ADR 0041 owns credential transport.

Expand All @@ -15,6 +16,6 @@ Remote script delivery caps in-memory bytes and error answers.

## Proposed in #4669

#4669 proposes private writes for credentials, client state, and daemon state (#4649): create each under a verified state root, and never write through a link at the final name.
#4669 proposes private writes for credentials, client state, and daemon state (#4649) under a verified state root, without final-name links.
Do not apply these before #4669 is approved.
Do not apply the ADR 0016 walk to other outputs. Screenshot `--out`, contact sheets, JUnit, traces, recordings keep a plain write to the path the caller names.
Do not apply the ADR 0016 walk to other outputs. Screenshot `--out`, contact sheets, JUnit, traces, and recordings use plain writes to caller paths.
6 changes: 6 additions & 0 deletions packages/contracts/src/daemon-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,12 @@ export function isTenantOwnedSessionName(tenant: string, sessionName: string): b
return sessionName.startsWith(`${tenant}:`);
}

/** The canonical address of a session under tenant isolation. */
export function tenantScopedSessionName(tenant: string, sessionName: string | undefined): string {
const requested = sessionName || 'default';
return isTenantOwnedSessionName(tenant, requested) ? requested : `${tenant}:${requested}`;
}

export function buildDaemonHttpTenantHeaders(tenantId: string | undefined): Record<string, string> {
const normalizedTenantId = tenantId?.trim();
if (!normalizedTenantId) return {};
Expand Down
3 changes: 3 additions & 0 deletions packages/contracts/src/recording.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,12 @@ export type TraceCommandResult =
| {
trace: 'started';
outPath: string;
clientCaptureId?: string;
captureStartOrder?: number;
}
| {
trace: 'stopped';
outPath: string;
artifacts: DaemonArtifact[];
clientCaptureId?: string;
};
14 changes: 11 additions & 3 deletions packages/daemon-client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { resolveCommandTimeoutPolicy } from '@agent-device/command-registry/regi
import { resolveCommandRequestTimeoutMs } from '@agent-device/command-registry/timeout-policy';
import {
prepareRemoteRequestArtifacts,
sendRemoteCapture,
sendRemoteScriptOpen,
type PreparedRemoteRequest,
} from '@agent-device/remote/daemon-artifacts';
Expand Down Expand Up @@ -186,9 +187,16 @@ async function sendToDaemonOnHost(
...(options.leaseCheckedByAdmission ? { leaseCheckedByAdmission: true } : {}),
},
);
if (!info.baseUrl || !request.meta?.clientArtifactPaths?.savedScript)
return await send(request);
return await sendRemoteScriptOpen(info, request, settings.paths.baseDir, send);
if (!info.baseUrl) return await send(request);
if (request.meta?.clientArtifactPaths?.savedScript)
return await sendRemoteScriptOpen(info, request, settings.paths.baseDir, send);
return await sendRemoteCapture(
info.baseUrl,
request,
settings.paths.baseDir,
send,
options.signal,
);
},
{ requestId, command: req.command },
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { buildSessionLeaseFromRequest } from '../../core/lease-context.ts';
import { LeaseRegistry } from '../../resources/lease-registry.ts';
import { createRequestHandler } from '../../server/request-router.ts';
import { providerCredentialsFixture } from './provider-credentials-fixture.ts';
import { tenantScopedSessionName } from '../../core/session-tenant-scope.ts';
import { tenantScopedSessionName } from '@agent-device/contracts/daemon-http';
import { lifecycleDeviceRuntimeGateway } from './test-device-runtime-gateway.ts';
import { HUMAN_CONTROL_LEASE_REQUEST, humanControlRequest } from './human-control-fixtures.ts';
import { fakeCreateCommandSurface } from './command-surface-fake.ts';
Expand Down
40 changes: 40 additions & 0 deletions packages/daemon/src/core/capture-identity-refusal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { errorResponse, type DaemonResponse } from '@agent-device/kernel/contracts';
import { CAPTURE_IDENTITY_REASONS } from '@agent-device/kernel/errors';

type CaptureKind = 'trace' | 'native perf';
type CaptureRefusal = 'already-active' | 'mismatch';

const messages = {
trace: {
'already-active': 'trace already in progress',
mismatch: 'trace capture identity changed',
},
'native perf': {
'already-active': 'native perf capture already in progress',
mismatch: 'native perf capture identity changed',
},
} as const;

export function captureIdentityRefusal(
kind: CaptureKind,
refusal: CaptureRefusal,
clientCaptureId?: string,
): DaemonResponse {
return errorResponse('INVALID_ARGS', messages[kind][refusal], {
reason:
refusal === 'already-active'
? CAPTURE_IDENTITY_REASONS.alreadyActive.reason
: CAPTURE_IDENTITY_REASONS.mismatch.reason,
...(refusal === 'already-active' ? { clientCaptureId } : {}),
});
}

let lastCaptureStartOrder = 0;

/** Orders successful capture starts even when their HTTP replies arrive out of order. */
export function captureStartReceipt(clientCaptureId: string | undefined) {
if (!clientCaptureId) return {};
const now = Math.floor((performance.timeOrigin + performance.now()) * 1_000);
lastCaptureStartOrder = Math.max(lastCaptureStartOrder + 1, now);
return { clientCaptureId, captureStartOrder: lastCaptureStartOrder };
}
4 changes: 2 additions & 2 deletions packages/daemon/src/core/session-capture-binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ export function bindSessionAudioProbe(sessionStore: SessionStore, ref: SessionRe
export function bindSessionPerfCapture(
sessionStore: SessionStore,
ref: SessionRef,
clientOutPath?: string,
captureIdentity?: { clientCaptureId: string; clientOutPath?: string },
) {
return bindSessionCapture(sessionStore, ref, {
read: (session) => session.perfCapture,
write: (perfCapture) => {
sessionStore.update(ref, {
perfCapture: perfCapture ? { ...perfCapture, clientOutPath } : undefined,
perfCapture: perfCapture ? { ...perfCapture, captureIdentity } : undefined,
});
},
});
Expand Down
3 changes: 2 additions & 1 deletion packages/daemon/src/core/session-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,14 +224,15 @@ export type SessionState = {
snapshotDiagnostics?: SnapshotDiagnosticsState;
trace?: {
outPath: string;
clientCaptureId?: string;
Comment thread
thymikee marked this conversation as resolved.
Resolved
clientOutPath?: string;
remoteCaptureOutputPath?: string;
remoteCaptureTenantId?: string;
startedAt: number;
};
/** Native profiling mechanics stay behind one exact-owner durable handle. */
perfCapture?: {
clientOutPath?: string;
captureIdentity?: { clientCaptureId: string; clientOutPath?: string };
handle: PerfNativeCaptureLiveHandle;
envelope: DurableResourceEnvelope<'perf-capture'>;
};
Expand Down
4 changes: 0 additions & 4 deletions packages/daemon/src/core/session-tenant-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,6 @@ export type TenantSessionNamespace = {
partitioned: boolean;
};

export function tenantScopedSessionName(tenant: string, session: string): string {
return isTenantOwnedSessionName(tenant, session) ? session : `${tenant}:${session}`;
}

/** The tenant-relative name that addresses this session under tenant scoping. */
export function tenantPublicSessionName(tenant: string, session: string): string {
return isTenantOwnedSessionName(tenant, session) ? session.slice(tenant.length + 1) : session;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { createDaemonHttpServer } from './http-server.ts';
import { createRequestHandler } from '../../__tests__/support/test-device-runtime-gateway.ts';
import { screenshotCommandSurface } from '../../__tests__/support/screenshot-command-surface-fake.ts';
import { makeRecordRuntimeHarness } from '../../sessions/handlers/__tests__/record-runtime.fixtures.ts';
import { tenantScopedSessionName } from '../../core/session-tenant-scope.ts';
import { tenantScopedSessionName } from '@agent-device/contracts/daemon-http';
import { LeaseRegistry } from '../../resources/lease-registry.ts';
import {
listDownloadableArtifacts,
Expand Down
18 changes: 12 additions & 6 deletions packages/daemon/src/server/http/http-server-remote-output.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -785,9 +785,13 @@ test('remote perf memory output reaches the runtime only as a session artifact a
});
});

test.each(['./capture.log', undefined])(
'remote trace start/stop retains only a client destination (%s)',
async (destination) => {
test.each([
{ destination: './capture.log', stopId: 'capture-a' },
{ destination: './capture.log', stopId: undefined },
{ destination: undefined, stopId: 'capture-a' },
])(
'remote trace start/stop retains a client destination $destination only with ID $stopId',
async ({ destination, stopId }) => {
const root = mkdtempForTestSync('remote-trace-client-');
const clientRoot = path.join(root, 'client');
const sessionStore = makeSessionStore('remote-trace-session-');
Expand All @@ -814,6 +818,7 @@ test.each(['./capture.log', undefined])(
...req,
meta: {
...req.meta,
captureId: 'capture-a',
...(clientPath ? { clientArtifactPaths: { outPath: clientPath } } : {}),
},
});
Expand All @@ -825,13 +830,14 @@ test.each(['./capture.log', undefined])(
command: 'trace',
session: 'capture',
positionals: ['stop'],
meta: { cwd: clientRoot },
meta: { cwd: clientRoot, captureId: stopId },
};
const stopped = await post(stopRequest);
expect(stopped.result?.ok, JSON.stringify(stopped)).toBe(true);
const artifact = stopped.result?.data?.artifacts?.[0];
expect(artifact?.localPath).toBe(clientPath);
expect(artifact?.fileName).toBe(path.basename(clientPath ?? output));
const expectedPath = stopId ? clientPath : undefined;
expect(artifact?.localPath).toBe(expectedPath);
expect(artifact?.fileName).toBe(path.basename(expectedPath ?? output));
const download = await fetch(`${baseUrl}/artifacts/${artifact?.artifactId}`, {
headers: { authorization: 'Bearer test-token' },
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,21 @@ function fixture() {
return { root, session, sessionStore };
}

function request(positionals: string[], clientOutPath?: string): DaemonRequest {
function request(positionals: string[], clientOutPath?: string, captureId?: string): DaemonRequest {
return {
token: 'token',
session: 'trace-session',
command: 'trace',
positionals,
flags: {},
...(clientOutPath ? { meta: { clientArtifactPaths: { outPath: clientOutPath } } } : {}),
...(clientOutPath || captureId
? {
meta: {
...(clientOutPath ? { clientArtifactPaths: { outPath: clientOutPath } } : {}),
...(captureId ? { captureId } : {}),
},
}
: {}),
};
}

Expand All @@ -69,6 +76,75 @@ test('starts and stops one trace through the session-owned trace slot', () => {
expect(session.trace).toBeUndefined();
});

test('a stale client capture identity cannot stop a reopened trace', () => {
const { session, sessionStore } = fixture();
const host = createTestHostEnvironment();
for (const action of ['start', 'stop']) {
expect(
handleTraceCommand({
host,
req: request([action], undefined, 'capture-a'),
sessionName: session.name,
sessionStore,
}),
).toMatchObject({ ok: true, data: { clientCaptureId: 'capture-a' } });
}
const started = handleTraceCommand({
host,
req: request(['start'], undefined, 'capture-b'),
sessionName: session.name,
sessionStore,
});
expect(started).toMatchObject({
ok: true,
data: { clientCaptureId: 'capture-b', captureStartOrder: expect.any(Number) },
});
const stale = handleTraceCommand({
host,
req: request(['stop'], undefined, 'capture-a'),
sessionName: session.name,
sessionStore,
});
expect(stale).toMatchObject({
ok: false,
error: { details: { reason: 'capture-identity-mismatch' } },
});
expect(session.trace).toBeDefined();
const stopped = handleTraceCommand({
host,
req: request(['stop'], undefined, 'capture-b'),
sessionName: session.name,
sessionStore,
});
expect(stopped).toMatchObject({ ok: true, data: { clientCaptureId: 'capture-b' } });
});
Comment thread
thymikee marked this conversation as resolved.
Resolved

test('a pathless stop without a capture ID omits the prior client destination', () => {
const { root, session, sessionStore } = fixture();
const host = createTestHostEnvironment();
const clientPath = path.join(root, 'client.trace');
const daemonPath = path.join(root, 'daemon.trace');
handleTraceCommand({
host,
req: request(['start', daemonPath], clientPath, 'capture-a'),
sessionName: session.name,
sessionStore,
});
const stopped = handleTraceCommand({
host,
req: request(['stop']),
sessionName: session.name,
sessionStore,
});
expect(stopped).toMatchObject({
ok: true,
data: {
clientCaptureId: 'capture-a',
artifacts: [{ localPath: daemonPath }],
},
});
});

test('relocates trace output and projects the client artifact path', () => {
const { root, session, sessionStore } = fixture();
const original = path.join(root, 'original.trace');
Expand Down
23 changes: 19 additions & 4 deletions packages/daemon/src/sessions/handlers/trace-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import type { SessionRef } from '../../core/session-state.ts';
import { recordSessionAction } from '../../core/session-action-recorder.ts';
import { errorResponse } from '@agent-device/kernel/contracts';
import { withCaptureOutputOwnership } from '../../core/capture-output-ownership.ts';
import {
captureIdentityRefusal,
captureStartReceipt,
} from '../../core/capture-identity-refusal.ts';

export function handleTraceCommand(params: {
host: HostEnvironment;
Expand All @@ -38,7 +42,8 @@ function startTrace(
ref: SessionRef,
): DaemonResponse {
const session = sessionStore.requireCurrent(ref);
if (session.trace) return errorResponse('INVALID_ARGS', 'trace already in progress');
if (session.trace)
return captureIdentityRefusal('trace', 'already-active', session.trace.clientCaptureId);
const outPath = expandSessionPath(
req.positionals?.[1] ?? sessionStore.defaultTracePath(session),
requestCwd(req, host),
Expand All @@ -47,15 +52,20 @@ function startTrace(
fs.appendFileSync(outPath, '');
session.trace = {
outPath,
clientCaptureId: req.meta?.captureId,
startedAt: Date.now(),
clientOutPath: req.meta?.clientArtifactPaths?.outPath,
clientOutPath: req.meta?.captureId ? req.meta.clientArtifactPaths?.outPath : undefined,
...(req.internal?.publicNetworkOnly ? { remoteCaptureOutputPath: outPath } : {}),
remoteCaptureTenantId: session.lease?.tenantId ?? req.meta?.tenantId,
};
Comment on lines 52 to 60

@apex-sentinel-staging apex-sentinel-staging Bot Dec 1, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No longer raised on 1adba76.

🟡 Minor · Old client's pathless trace stop now receives the daemon's own path as its destination

A released client (no meta.captureId) sends trace start ./saved.adtrace then a pathless trace stop; the stop response returns the daemon's own outPath as artifacts[].localPath instead of the client's destination. clientOutPath is stored only when meta.captureId is present, so for old clients it is never recorded and the fallback falls through to the daemon's path.

Suggested change
fs.appendFileSync(outPath, '');
session.trace = {
outPath,
clientCaptureId: req.meta?.captureId,
startedAt: Date.now(),
clientOutPath: req.meta?.clientArtifactPaths?.outPath,
clientOutPath: req.meta?.captureId ? req.meta.clientArtifactPaths?.outPath : undefined,
...(req.internal?.publicNetworkOnly ? { remoteCaptureOutputPath: outPath } : {}),
remoteCaptureTenantId: session.lease?.tenantId ?? req.meta?.tenantId,
};
session.trace = {
outPath,
clientCaptureId: req.meta?.captureId,
startedAt: Date.now(),
clientOutPath: req.meta?.clientArtifactPaths?.outPath,
...(req.internal?.publicNetworkOnly ? { remoteCaptureOutputPath: outPath } : {}),
remoteCaptureTenantId: session.lease?.tenantId ?? req.meta?.tenantId,
};

Suggested change

Record clientOutPath unconditionally on start and gate only its reuse on capture identity, or add a released-client fallback so a pathless stop still receives its start destination rather than a daemon-host path.

Details

persona: senior-developer, maintainability, javascript

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if it is wrong — I will re-check the cited code.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked at 1adba76871 against released v0.21.46. Both advertise RPC protocol 3. The released trace and native perf stop handlers reused the named start destination on a pathless stop. At this head a legacy start lacks the capture ID, so a pathless stop still completes but drops the saved destination. On the public HTTP trace route localPath is omitted, with a filename available for fallback. The destination change remains observable even though the path field is optional. Saving the old path alone would not restore the behavior under the new identity check. Leaving this thread open for a maintainer decision on a typed protocol-3 refusal before finalizing a named capture or a protocol version bump.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

55c76abacb fixes start settlement when daemon execution order differs from client reservation order. The protocol-3 case still drops the saved destination for released clients. I left this thread open for the maintainer’s choice between a typed pre-finalization refusal and a protocol bump.

recordSessionAction(sessionStore, ref, req, req.command, { action: 'start', outPath });
return {
ok: true,
data: { trace: 'started', outPath } satisfies TraceCommandResult,
data: {
trace: 'started',
outPath,
...captureStartReceipt(req.meta?.captureId),
} satisfies TraceCommandResult,
};
}

Expand All @@ -67,6 +77,10 @@ function stopTrace(
): DaemonResponse {
const session = sessionStore.requireCurrent(ref);
if (!session.trace) return errorResponse('INVALID_ARGS', 'no active trace');
const requestedCaptureId = req.meta?.captureId;
const clientCaptureId = session.trace.clientCaptureId;
if (requestedCaptureId && requestedCaptureId !== clientCaptureId)
return captureIdentityRefusal('trace', 'mismatch');
const outPath = relocateTraceOutput(
requestCwd(req, host),
session.trace.outPath,
Expand All @@ -76,7 +90,7 @@ function stopTrace(
const tenantId = session.trace.remoteCaptureTenantId;
const clientOutPath =
req.meta?.clientArtifactPaths?.outPath ??
session.trace.clientOutPath ??
(requestedCaptureId ? session.trace.clientOutPath : undefined) ??
(req.internal?.publicNetworkOnly ? undefined : outPath);
session.trace = undefined;
recordSessionAction(sessionStore, ref, req, req.command, { action: 'stop', outPath });
Expand All @@ -86,6 +100,7 @@ function stopTrace(
{
trace: 'stopped',
outPath,
...(clientCaptureId ? { clientCaptureId } : {}),
artifacts: [
{
field: 'outPath',
Expand Down
Loading
Loading