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
2 changes: 1 addition & 1 deletion packages/command-surface/src/cli-grammar/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export type SelectionOptions = {
export type CliInput = Record<string, unknown>;
export type CliReader = (positionals: string[], flags: CliFlags) => CliInput;
/** Builds the daemon request for one command. Most writers are pure projections of their input. */
export type DaemonWriter = (input: CommandInput) => DaemonCommandRequest;
export type DaemonWriter = (input: CommandInput, host?: HostEnvironment) => DaemonCommandRequest;

/**
* A writer that has caller-side work to do before the request exists: reading the replay script
Expand Down
2 changes: 1 addition & 1 deletion packages/command-surface/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ async function prepareBatchDaemonCommandRequest(
throw new AppError(
'INVALID_ARGS',
`Batch step ${stepNumber} ${command} input is invalid: ${message}`,
undefined,
error instanceof AppError ? error.details : undefined,
error,
);
}
Expand Down
10 changes: 10 additions & 0 deletions packages/command-surface/src/replay/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,16 @@ describe('replay command interface', () => {
}
});

test('prepares a large suite for daemon admission', async () => {
const root = mkdtempForTestSync('agent-device-replay-count-');
for (let index = 0; index < 257; index += 1) {
fs.writeFileSync(path.join(root, `${index}.ad`), '');
}
const host = { env: {}, cwd: root };
const request = await testDaemonWriter({ paths: ['.'] }, host);
expect(request.options.replayScriptSources).toHaveLength(257);
});

test('validates -e keys with the grammar of the resolved replay format', async () => {
fs.writeFileSync(path.join(SCRIPT_ROOT, 'flow.yaml'), 'appId: demo.app\n---\n- back\n');
const host = { env: {}, cwd: SCRIPT_ROOT };
Expand Down
55 changes: 29 additions & 26 deletions packages/command-surface/src/replay/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,16 @@ export const replayDaemonWriter: AsyncDaemonWriter = async (input, host) => {
const inputPath = requiredDaemonString(input.path, 'replay requires path');
const replayBackend = readReplayBackend(input);
const replayShellEnv = collectReplayClientShellEnv(host.env);
const replayScriptSource = await loadReplayScriptSourceBundle({
inputPath,
cwd: readReplayClientCwd(input, host.cwd),
replayBackend,
env: readReplayScriptSourceEnv(
input,
replayShellEnv,
resolveReplayFormat(inputPath, replayBackend),
),
});
return request(REPLAY_COMMAND_NAME, [inputPath], {
...input,
replayUpdate: input.update,
Expand All @@ -258,16 +268,7 @@ export const replayDaemonWriter: AsyncDaemonWriter = async (input, host) => {
// #1802: the caller owns the flow files, so it reads them here — the same
// client-collects-local-input move `replayShellEnv` already makes — and
// the daemon executes only what arrives in this bundle.
replayScriptSource: await loadReplayScriptSourceBundle({
inputPath,
cwd: readReplayClientCwd(input, host.cwd),
replayBackend,
env: readReplayScriptSourceEnv(
input,
replayShellEnv,
resolveReplayFormat(inputPath, replayBackend),
),
}),
replayScriptSource,
replayFrom: input.resumeFrom,
replayPlanDigest: input.resumePlanDigest,
replayKeepSession: input.keepSession,
Expand All @@ -280,6 +281,22 @@ export const testDaemonWriter: AsyncDaemonWriter = async (input, host) => {
const replayBackend = readReplayBackend(input);
const cwd = readReplayClientCwd(input, host.cwd);
const replayShellEnv = collectReplayClientShellEnv(host.env);
const paths = discoverReplaySourcePaths({ inputs, cwd, replayBackend });
const sources = await Promise.all(
paths.map(
async (inputPath) =>
await loadReplayScriptSourceBundle({
inputPath,
cwd,
replayBackend,
env: readReplayScriptSourceEnv(
input,
replayShellEnv,
resolveReplayFormat(inputPath, replayBackend),
),
}),
),
);
return request(TEST_COMMAND_NAME, inputs, {
...stripReplayTestPresentationInput(input),
replayUpdate: input.update,
Expand All @@ -289,21 +306,7 @@ export const testDaemonWriter: AsyncDaemonWriter = async (input, host) => {
// #1802: `test` inputs are paths, directories, and globs on the CALLER's
// filesystem. Expanding them here keeps discovery order identical for a
// local and a remote daemon and ships each discovered source's text.
replayScriptSources: await Promise.all(
discoverReplaySourcePaths({ inputs, cwd, replayBackend }).map(
async (inputPath) =>
await loadReplayScriptSourceBundle({
inputPath,
cwd,
replayBackend,
env: readReplayScriptSourceEnv(
input,
replayShellEnv,
resolveReplayFormat(inputPath, replayBackend),
),
}),
),
),
replayScriptSources: sources,
});
};

Expand All @@ -330,7 +333,7 @@ export const testCommandFacet = defineCommandFacet({
summary: 'Run replay test suites',
searchHint: 'tests ad',
cliDetail:
"Relative globs are expanded on the caller from its working directory, whose name is treated literally. Quote glob inputs to defer expansion to test. Copied diagnostic artifacts receive numbered filenames when needed to preserve other artifacts, replay sources, timing traces, and attempt manifests. JUnit reports (--reporter junit:<path>) replace characters forbidden by XML 1.0 with U+FFFD and preserve legal Unicode and whitespace. JSON and other reporters retain the original suite values. Custom reporter getExitCode hooks must return an integer from 0 to 255 or undefined; the highest valid code wins and cannot lower a failing suite's exit code. A nested test stops after a bounded resource refusal even with --retries; other failures keep their configured retries.",
"Relative globs are expanded on the caller from its working directory, whose name is treated literally. Quote glob inputs to defer expansion to test. A public-network remote daemon accepts at most 2 MiB of source text, 256 source bundles, and 2,048 files per request; split a larger suite into smaller invocations. These count limits do not apply to a local daemon. Copied diagnostic artifacts receive numbered filenames when needed to preserve other artifacts, replay sources, timing traces, and attempt manifests. JUnit reports (--reporter junit:<path>) replace characters forbidden by XML 1.0 with U+FFFD and preserve legal Unicode and whitespace. JSON and other reporters retain the original suite values. Custom reporter getExitCode hooks must return an integer from 0 to 255 or undefined; the highest valid code wins and cannot lower a failing suite's exit code. A nested test stops after a bounded resource refusal even with --retries; other failures keep their configured retries.",
},
metadata: testCommandMetadata,
run: (client, input) => client.replay.test(withCommandRuntimeHints(input)),
Expand Down
9 changes: 9 additions & 0 deletions packages/contracts/src/facades/remote.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { ReasonTable } from '@agent-device/kernel/errors';

export type { CompanionTunnelScope, MetroBridgeScope } from '../companion-tunnel-scope.ts';
export type {
MetroBridgeResult,
Expand All @@ -22,6 +24,13 @@ export {
PROVIDER_PROFILE_FIELD_FLAG_ALIASES,
PROVIDER_PROFILE_FIELD_FLAGS,
} from '../remote-config-fields.ts';

/** Why a provider response was rejected before its body was accepted. */
export const PROVIDER_RESPONSE_REASONS = {
// A provider answered with more bytes than the response budget allows.
tooLarge: { reason: 'provider_response_too_large' },
} as const satisfies ReasonTable<'provider response'>;

export type {
CloudProviderProfileFields,
DaemonRpcMode,
Expand Down
2 changes: 2 additions & 0 deletions packages/contracts/src/platform-providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export type PlatformProviderRequestContext = Readonly<{
requestId?: string;
/** Daemon policy says that the root may construct its managed Web provider for this request. */
useDefaultWebProvider?: boolean;
/** The daemon's trusted remote-tenant policy for this request. */
publicNetworkOnly?: true;
}>;

/** The only request-scoped platform value currently consumed by daemon handlers.
Expand Down
10 changes: 8 additions & 2 deletions packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ test('requireTenantOwnedEntry returns entries readable by the tenant', () => {
['owned', { tenantId: 'tenant-a' }],
]);
assert.equal(requireTenantOwnedEntry(map, 'shared', undefined, RESOURCE), map.get('shared'));
assert.equal(requireTenantOwnedEntry(map, 'shared', 'tenant-b', RESOURCE), map.get('shared'));
assert.equal(requireTenantOwnedEntry(map, 'owned', 'tenant-a', RESOURCE), map.get('owned'));
});

Expand All @@ -43,12 +42,19 @@ test('missing entries surface as expired resources with a recovery hint', () =>
});

test('tenant mismatch stays UNAUTHORIZED and honors plural labels', () => {
const map = new Map([['owned', { tenantId: 'tenant-a' }]]);
const map = new Map([
['owned', { tenantId: 'tenant-a' }],
['shared', {}],
]);
const singular = captureAppError(() =>
requireTenantOwnedEntry(map, 'owned', 'tenant-b', RESOURCE),
);
assert.equal(singular.code, 'UNAUTHORIZED');
assert.equal(singular.message, 'Artifact belongs to a different tenant');
assert.equal(
captureAppError(() => requireTenantOwnedEntry(map, 'shared', 'tenant-b', RESOURCE)).code,
'UNAUTHORIZED',
);

const plural = captureAppError(() =>
requireTenantOwnedEntry(map, 'owned', undefined, {
Expand Down
6 changes: 4 additions & 2 deletions packages/daemon/src/core/tenant-owned-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,12 @@ export function requireTenantOwnedEntry<T extends TenantOwnedEntry>(
if (!entry) {
throw expiredTenantOwnedEntryError(kind, id);
}
if (entry.tenantId && entry.tenantId !== tenantId) {
if (entry.tenantId !== tenantId) {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
throw new AppError(
'UNAUTHORIZED',
`${kind.label} ${kind.plural ? 'belong' : 'belongs'} to a different tenant`,
entry.tenantId
? `${kind.label} ${kind.plural ? 'belong' : 'belongs'} to a different tenant`
: `${kind.label} ${kind.plural ? 'are' : 'is'} not owned by a tenant`,
Comment thread
thymikee marked this conversation as resolved.
Resolved
);
}
return entry;
Expand Down
2 changes: 1 addition & 1 deletion packages/daemon/src/resources/artifact-tracking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ function archiveFilename(fileName: string): string {
}

function canReadArtifact(entry: ArtifactEntry, tenantId: string | undefined): boolean {
return !entry.cleanupRequested && (!entry.tenantId || entry.tenantId === tenantId);
return !entry.cleanupRequested && entry.tenantId === tenantId;
}

function safeArtifactFilename(fileName: string | undefined, fallback: string): string {
Expand Down
8 changes: 8 additions & 0 deletions packages/daemon/src/resources/lease-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,14 @@ export class LeaseRegistry {
assertLeaseScopeMatch(this.getActiveLease(scope.leaseId), scope);
}

/** Admit a scoped read without filling an omitted backend with an allocation default. */
assertLeaseReadAdmission(request: HeartbeatLeaseRequest): void {
this.cleanupExpiredLeases();
const lease = this.getActiveLease(normalizeRequiredLeaseId(request.leaseId));
assertLeaseOwnerScope(lease, request);
assertLeaseScopeMatch(lease, request);
}

/** Whether this daemon ever allocated `tenantId` a `macos-app` lease, released or not. */
hasHeldMacOsAppLease(tenantId: string): boolean {
return this.macOsAppTenantIds.has(tenantId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,22 @@ test('a /rpc COMMAND_FAILED without the expiry reason stays a 500', async (t) =>
await closeLoopbackServer(server);
}
});

test('upload capacity failures answer 503 with a typed reason', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const { port, server } = await startRpcServer(TOKEN, async () => ({
ok: false,
error: {
code: 'COMMAND_FAILED',
message: 'Too many active resumable uploads',
details: { reason: 'UPLOAD_CAPACITY_EXCEEDED', retriable: true },
},
}));
try {
const answer = await postRpcCommand(port, TOKEN, 'req-upload-capacity');
assert.equal(answer.status, 503);
assert.equal(answer.body.error?.data?.details?.reason, 'UPLOAD_CAPACITY_EXCEEDED');
} finally {
await closeLoopbackServer(server);
}
});
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,13 @@ test('downloadable artifact inventory is filtered by tenant', async () => {
(await listDownloadableArtifacts('tenant-a', process.env)).map(
(artifact) => artifact.filename,
),
['public.txt', 'tenant-a.txt'],
['tenant-a.txt'],
);
assert.deepEqual(
(await listDownloadableArtifacts('tenant-b', process.env)).map(
(artifact) => artifact.filename,
),
['public.txt', 'tenant-b.txt'],
['tenant-b.txt'],
);
} finally {
for (const artifactId of artifactIds) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { DaemonResponse } from '@agent-device/kernel/contracts';
import { test } from 'vitest';
import { test, vi } from 'vitest';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import type { DaemonRequest } from '../../core/daemon-request.ts';
import {
Expand Down Expand Up @@ -96,6 +97,62 @@ test('the rpc admission registers the tracking id before consulting the auth hoo
}
});

test('a disconnected rpc caller cancels a nonresolving auth hook and releases request state', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const state = globalThis as typeof globalThis & {
__rpcAuthHookSignal?: AbortSignal;
};
const previousHook = process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;
let dispatches = 0;
const { port, server } = await startWithAuthHook(
`let first = true;
export default ({ signal }) => {
if (!first) return { tenantId: 'tenant-admitted' };
first = false;
globalThis.__rpcAuthHookSignal = signal;
return new Promise(() => {});
};`,
async () => {
dispatches++;
return { ok: true, data: {} };
},
);
try {
const request = http.request({
host: '127.0.0.1',
port,
method: 'POST',
path: '/rpc',
headers: { authorization: `Bearer ${DAEMON_TOKEN}`, 'content-type': 'application/json' },
});
request.on('error', () => {});
request.end(
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'agent_device.command',
params: {
command: 'devices',
session: 'default',
meta: { requestId: 'stalled-auth-hook' },
},
}),
);
await vi.waitFor(() => assert.ok(state.__rpcAuthHookSignal), { timeout: 1_000 });
const signal = state.__rpcAuthHookSignal;
assert.ok(signal);
request.destroy();
await vi.waitFor(() => assert.equal(signal.aborted, true), { timeout: 1_000 });
const next = await postRpcCommand(port, DAEMON_TOKEN, 'stalled-auth-hook');
assert.equal(next.status, 200);
assert.equal(dispatches, 1);
} finally {
delete state.__rpcAuthHookSignal;
restoreEnv('AGENT_DEVICE_HTTP_AUTH_HOOK', previousHook);
await closeLoopbackServer(server);
}
});

function hookCalls(): number {
return Number(process.env[HOOK_CALLS_ENV] ?? 0);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
trackUploadedArtifact,
} from '../../resources/artifact-tracking.ts';
import { resolveInstallSource } from '../../sessions/install-source-resolution.ts';
import { REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES } from '@agent-device/replay-port/script-source';
import {
closeLoopbackServer,
listenOnLoopback,
Expand Down Expand Up @@ -270,7 +271,11 @@ test('remote HTTP accepts an uploaded path artifact without resolving the client
const root = mkdtempForTestSync('agent-device-http-uploaded-path-');
const artifactPath = path.join(root, 'uploaded.apk');
fs.writeFileSync(artifactPath, 'uploaded');
const uploadedArtifactId = trackUploadedArtifact({ artifactPath, tempDir: root });
const uploadedArtifactId = trackUploadedArtifact({
artifactPath,
tempDir: root,
tenantId: 'tenant-test',
});
const hookPath = writeAllowingAuthHook(root);
const received: DaemonRequest[] = [];
const server = await createDaemonHttpServer({
Expand Down Expand Up @@ -309,6 +314,39 @@ test('remote HTTP accepts an uploaded path artifact without resolving the client
}
});

test('remote replay rejects an oversized raw source before dispatch', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const root = mkdtempForTestSync('agent-device-http-replay-source-limit-');
const hookPath = writeAllowingAuthHook(root);
let handlerCalls = 0;
const server = await createDaemonHttpServer({
env: remoteHttpEnvironment(hookPath),
handleRequest: async (): Promise<DaemonResponse> => {
handlerCalls += 1;
return { ok: true, data: {} };
},
cwd: process.cwd(),
});
try {
const port = await listenOnLoopback(server);
const source = 'x'.repeat(REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES + 1);
const response = await postCommandRpc(port, {
command: 'replay',
positionals: ['flow.ad'],
flags: { replayScriptSource: { entry: 'flow.ad', files: { 'flow.ad': source } } },
});
assert.equal(response.status, 400);
assert.equal(response.body.error?.data?.code, 'INVALID_ARGS');
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
assert.deepEqual(response.body.error?.data?.details, {
limitBytes: REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES,
totalBytes: REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES + 1,
});
assert.equal(handlerCalls, 0);
} finally {
await closeLoopbackServer(server);
}
});

test('local command RPC keeps host paths unrestricted', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const received: DaemonRequest[] = [];
Expand Down
Loading
Loading