Skip to content
Merged
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
85 changes: 85 additions & 0 deletions src/daemon/__tests__/artifact-archive.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { test } from 'vitest';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { extractTarInstallableArtifact } from '../artifact-archive.ts';
import { runCmdSync } from '@agent-device/host-kit/command';
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';

const TAR_ENV = { ...process.env, COPYFILE_DISABLE: '1' };

/**
* Builds a tar from the named top-level roots created under a fresh temp source
* dir, then extracts it with no `expectedRootName`, so the archive's own layout
* must decide the installable root (`inferArchiveRootName`).
*/
async function extractWithoutExpectedRoot(
rootNames: string[],
entries: Record<string, string>,
platform: 'ios' | 'android',
): Promise<string> {
const tempRoot = mkdtempForTestSync('agent-device-artifact-archive-');
const sourceRoot = path.join(tempRoot, 'src');
fs.mkdirSync(sourceRoot, { recursive: true });
for (const [name, contents] of Object.entries(entries)) {
const filePath = path.join(sourceRoot, name);
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, contents);
}
const archivePath = path.join(tempRoot, 'artifact.tar');
runCmdSync('tar', ['cf', archivePath, '-C', sourceRoot, ...rootNames], { env: TAR_ENV });
const extractDir = path.join(tempRoot, 'out');
fs.mkdirSync(extractDir);
return await extractTarInstallableArtifact({ archivePath, tempDir: extractDir, platform });
}

test('an iOS tar infers the single top-level .app directory as the installable root', async () => {
const artifactPath = await extractWithoutExpectedRoot(
['Sample.app'],
{ 'Sample.app/payload.txt': 'payload' },
'ios',
);
assert.equal(path.basename(artifactPath), 'Sample.app');
assert.equal(fs.readFileSync(path.join(artifactPath, 'payload.txt'), 'utf8'), 'payload');
});

test('an iOS tar with no top-level .app directory is refused, not installed under a wrong root', async () => {
await assert.rejects(
async () =>
await extractWithoutExpectedRoot(['payload'], { 'payload/data.txt': 'data' }, 'ios'),
/must contain a single top-level \.app directory/i,
);
});

test('an iOS tar with two top-level .app directories refuses and names both candidates', async () => {
await assert.rejects(
async () =>
await extractWithoutExpectedRoot(
['A.app', 'B.app'],
{ 'A.app/x': '1', 'B.app/y': '2' },
'ios',
),
/exactly one top-level \.app directory, found: A\.app, B\.app/i,
);
});

test('an Android tar installs its single top-level bundle whatever it is named', async () => {
const artifactPath = await extractWithoutExpectedRoot(
['bundle'],
{ 'bundle/base.apk': 'apk' },
'android',
);
assert.equal(path.basename(artifactPath), 'bundle');
});

test('an Android tar with two top-level bundles is refused and names them', async () => {
await assert.rejects(
async () =>
await extractWithoutExpectedRoot(
['bundle-a', 'bundle-b'],
{ 'bundle-a/x': '1', 'bundle-b/y': '2' },
'android',
),
/must contain a single top-level bundle, found: bundle-a, bundle-b/i,
);
});
110 changes: 110 additions & 0 deletions src/daemon/__tests__/request-lock-policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,116 @@ test('rejects mismatching serial selectors for existing android sessions', () =>
);
});

// Fresh-session target ↔ lock-platform matrix (`targetSelectorsConflict`). A fresh session under a
// platform lock binds its first device from that platform, so a target that cannot exist on it must
// fail loudly instead of binding the wrong device class (or none). Each family keeps its native
// target: mobile-family locks bind `mobile`, vega binds `tv`, desktop-family locks bind `desktop`.
test('a mobile-family lock accepts its native mobile target on a fresh session', () => {
for (const lockPlatform of ['android', 'harmonyos', 'ios'] as const) {
const req = applyRequestLockPolicy({
token: 'token',
session: 'qa-fresh',
command: 'snapshot',
positionals: [],
flags: { target: 'mobile' },
meta: { lockPolicy: 'reject', lockPlatform },
});
assert.equal(req.flags?.target, 'mobile');
assert.equal(req.flags?.platform, lockPlatform);
}
});

test('rejects a desktop target under a mobile-family lock platform on a fresh session', () => {
for (const lockPlatform of ['android', 'harmonyos', 'ios'] as const) {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
assert.throws(
() =>
applyRequestLockPolicy({
token: 'token',
session: 'qa-fresh',
command: 'snapshot',
positionals: [],
flags: { target: 'desktop' },
meta: { lockPolicy: 'reject', lockPlatform },
}),
/but this request selected --target=desktop/i,
`${lockPlatform} locks cannot host a desktop target`,
);
}
});

test('a vega lock accepts only a tv target on a fresh session', () => {
const req = applyRequestLockPolicy({
token: 'token',
session: 'qa-fresh',
command: 'snapshot',
positionals: [],
flags: { target: 'tv' },
meta: { lockPolicy: 'reject', lockPlatform: 'vega' },
});
assert.equal(req.flags?.target, 'tv');
assert.equal(req.flags?.platform, 'vega');

for (const target of ['mobile', 'desktop'] as const) {
assert.throws(
() =>
applyRequestLockPolicy({
token: 'token',
session: 'qa-fresh',
command: 'snapshot',
positionals: [],
flags: { target },
meta: { lockPolicy: 'reject', lockPlatform: 'vega' },
}),
new RegExp(`--target=${target}`, 'i'),
'a vega lock cannot bind a non-tv target',
);
}
});

test('desktop-family locks (macos/linux/web) accept only a desktop target on a fresh session', () => {
for (const lockPlatform of ['macos', 'linux', 'web'] as const) {
const req = applyRequestLockPolicy({
token: 'token',
session: 'qa-fresh',
command: 'snapshot',
positionals: [],
flags: { target: 'desktop' },
meta: { lockPolicy: 'reject', lockPlatform },
});
assert.equal(req.flags?.target, 'desktop');

for (const target of ['mobile', 'tv'] as const) {
assert.throws(
() =>
applyRequestLockPolicy({
token: 'token',
session: 'qa-fresh',
command: 'snapshot',
positionals: [],
flags: { target },
meta: { lockPolicy: 'reject', lockPlatform },
}),
new RegExp(`--target=${target}`, 'i'),
`${lockPlatform} locks cannot host a ${target} target`,
);
}
}
});

test('an Apple lock accepts every target because Apple spans mobile, tv, and desktop', () => {
for (const target of ['mobile', 'tv', 'desktop'] as const) {
const req = applyRequestLockPolicy({
token: 'token',
session: 'qa-fresh',
command: 'snapshot',
positionals: [],
flags: { target },
meta: { lockPolicy: 'reject', lockPlatform: 'apple' },
});
assert.equal(req.flags?.target, target);
}
});

test('strips only conflicting scope selectors for existing sessions, keeping matching identity', () => {
const req = applyRequestLockPolicy(
{
Expand Down
58 changes: 58 additions & 0 deletions src/daemon/__tests__/session-script-writer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,64 @@ test('write() publishes atomically: no stray temp file survives a successful rep
// lifecycle alone decides that — a session handed to the writer still recording
// is refused on the strength of its terminal status ---

// A recorded longpress whose action.result carries no durationMs must recover the duration from the
// recorded positionals (last entry) when rewriting the ref to its selector chain — and must NOT
// promote a trailing junk positional into a duration, which would silently change the hold time.
test('a resolved longpress keeps its recorded duration when rewriting the selector', () => {
const root = mkdtempForTestSync('agent-device-script-writer-longpress-duration-');
const writer = new SessionScriptWriter(path.join(root, 'sessions'));
const session = makeAuthoringSession('default', {
actions: [
action({
command: 'longpress',
positionals: ['@e4', '800'],
result: { selectorChain: ['id="row"'] },
}),
],
});

const { parsed } = writeAndParse(writer, session);
expect(parsed.actions).toHaveLength(1);
expect(parsed.actions[0]?.command).toBe('longpress');
expect(parsed.actions[0]?.positionals).toEqual(['id="row"', '800']);
});

test('a resolved longpress without a duration positional writes the selector alone', () => {
const root = mkdtempForTestSync('agent-device-script-writer-longpress-noduration-');
const writer = new SessionScriptWriter(path.join(root, 'sessions'));
const session = makeAuthoringSession('default', {
actions: [
action({
command: 'longpress',
positionals: ['@e4'],
result: { selectorChain: ['id="row"'] },
}),
],
});

const { parsed } = writeAndParse(writer, session);
expect(parsed.actions[0]?.positionals).toEqual(['id="row"']);
});

test('a resolved longpress drops a blank or non-numeric trailing positional instead of writing it as a duration', () => {
for (const junk of [' ', 'abc']) {
const root = mkdtempForTestSync('agent-device-script-writer-longpress-junk-');
const writer = new SessionScriptWriter(path.join(root, 'sessions'));
const session = makeAuthoringSession('default', {
actions: [
action({
command: 'longpress',
positionals: ['@e4', junk],
result: { selectorChain: ['id="row"'] },
}),
],
});

const { parsed } = writeAndParse(writer, session);
expect(parsed.actions[0]?.positionals).toEqual(['id="row"']);
}
});

test('#1533: write() publishes nothing for an aborted authoring lifecycle that is still recording', () => {
const root = mkdtempForTestSync('agent-device-script-writer-authoring-aborted-');
const sessionsDir = path.join(root, 'sessions');
Expand Down
105 changes: 105 additions & 0 deletions src/daemon/server/http-authorization.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { test } from 'vitest';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { createDaemonHttpServer } from './http-server.ts';
import type { DaemonResponse } from '../daemon-request.ts';
import {
closeLoopbackServer,
listenOnLoopback,
skipWhenLoopbackUnavailable,
} from '../../__tests__/test-utils/loopback.ts';
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
import { restoreEnv } from '../../__tests__/test-utils/env.ts';

const DAEMON_TOKEN = 'daemon-secret';

function writeAuthHook(root: string, source: string): string {
const hookPath = path.join(root, 'auth-hook.mjs');
fs.writeFileSync(hookPath, source);
return hookPath;
}

/**
* Drives an auxiliary route (request diagnostics) through the shared
* token/auth-hook gate with a hook whose source is `hookSource`. The record
* never has to exist: a rejection answers before the record is resolved.
*/
async function withAuxRouteAndHook(
hookSource: string,
run: (ctx: { baseUrl: string }) => Promise<void>,
): Promise<void> {
const root = mkdtempForTestSync('agent-device-http-auth-rejection-');
const previousHook = process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;
process.env.AGENT_DEVICE_HTTP_AUTH_HOOK = writeAuthHook(root, hookSource);
const server = await createDaemonHttpServer({
token: DAEMON_TOKEN,
handleRequest: async (): Promise<DaemonResponse> => ({ ok: true, data: {} }),
resolveRequestDiagnosticsPath: () => path.join(root, 'unused-request-log.json'),
});
try {
const port = await listenOnLoopback(server);
await run({ baseUrl: `http://127.0.0.1:${port}` });
} finally {
await closeLoopbackServer(server);
restoreEnv('AGENT_DEVICE_HTTP_AUTH_HOOK', previousHook);
fs.rmSync(root, { recursive: true, force: true });
}
}

async function fetchDiagnostics(baseUrl: string): Promise<Response> {
return await fetch(`${baseUrl}/sessions/default/requests/abc123/diagnostics`, {
headers: { authorization: `Bearer ${DAEMON_TOKEN}` },
});
}

// An auth hook's own rejection on an auxiliary route must reach the caller as the flat REST error
// shape those routes answer with (`{ ok: false, error }` at the hook's status code), not as a
// JSON-RPC envelope or a generic 401 that drops the hook's message.

test('aux route: a hook returning bare false answers 401 with the default rejection message', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
await withAuxRouteAndHook(
'export default function authHook() { return false; }\n',
async ({ baseUrl }) => {
const response = await fetchDiagnostics(baseUrl);
assert.equal(response.status, 401);
assert.equal(response.headers.get('content-type'), 'application/json');
const body = (await response.json()) as { ok?: boolean; error?: string };
assert.equal(body.ok, false);
assert.equal(body.error, 'Request rejected by auth hook');
},
);
});

test('aux route: a hook returning a structured rejection keeps its message and 401 status', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
await withAuxRouteAndHook(
"export default function authHook() { return { ok: false, code: 'FORBIDDEN', message: 'denied by policy' }; }\n",
async ({ baseUrl }) => {
const response = await fetchDiagnostics(baseUrl);
assert.equal(response.status, 401);
const body = (await response.json()) as { ok?: boolean; error?: string };
assert.equal(
body.error,
'denied by policy',
"the hook's own message must survive the REST rendering",
);
},
);
});

test('aux route: a hook returning an invalid tenantId answers 500, not a 401 caller-retry trap', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
await withAuxRouteAndHook(
"export default function authHook() { return { tenantId: 'not a valid tenant!!' }; }\n",
async ({ baseUrl }) => {
const response = await fetchDiagnostics(baseUrl);
// The hook itself is broken (its attestation failed validation); that is a server fault, so
// the status must not masquerade as a client auth failure a retry could fix.
assert.equal(response.status, 500);
const body = (await response.json()) as { ok?: boolean; error?: string };
assert.match(body.error ?? '', /invalid tenantId/i);
},
);
});
Loading