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
Original file line number Diff line number Diff line change
Expand Up @@ -403,8 +403,8 @@ test('a sensitive value never reaches the instrumentation detail or the log wher
assertPrivate(log);
}

// The failure message and `stderr` detail are unchanged from before this diagnostic existed, so
// for stderr only the new `instrumentation` detail and its request-log entry are asserted.
// Helper stderr reaches the client only as the bounded, snapshot-content-free diagnostic (#4026),
// so every surface of the error and the request log is asserted, not just `instrumentation`.
const onStderr = [
`ret" text="${SECRET}" bounds="[0,0][1,1]" />`,
`ret" role-description="${SECRET}" />`,
Expand All @@ -416,8 +416,8 @@ test('a sensitive value never reaches the instrumentation detail or the log wher
for (const stderr of onStderr) {
const run = { exitCode: 1, stdout: '', stderr: `${stderr}\nam: Killed` };
const error = await captureError(run);
assertPrivate(JSON.stringify(normalizeError(error)));
const instrumentation = exitResultOf(normalizeError(error).details ?? {});
assertPrivate(JSON.stringify(instrumentation));
assert.equal(instrumentation.failed, undefined);

const { log } = await withLog(async (logPath) => {
Expand All @@ -430,12 +430,71 @@ test('a sensitive value never reaches the instrumentation detail or the log wher
);
});
});
assertPrivate(
JSON.stringify(diagnosticData(log, 'android_snapshot_helper_failed').instrumentation),
);
assertPrivate(log);
}
});

test('helper stderr kept for the client is bounded and keeps the cause line visible', async () => {
// A provider must still see why the run died; a line carrying snapshot content must not be what
// it sees, wherever the error or the request log carries stderr.
const run = {
exitCode: 1,
stdout: '',
stderr: `ret" text="${SECRET}" bounds="[0,0][1,1]" />\nuiautomator unavailable\nam: Killed`,
};
const error = await captureError(run);
const wire = normalizeError(error);
assert.ok(!JSON.stringify(wire).includes(SECRET), JSON.stringify(wire).slice(-800));
assert.equal(wire.details?.stderr, 'uiautomator unavailable\nam: Killed');
assert.equal(wire.details?.stderrWithheldLines, 1);

const { log } = await withLog(async (logPath) => {
await inScope(logPath, async () => {
await assert.rejects(
snapshotAndroid(emulator, {
helperAdb: helperFailingWith(run),
helperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT,
}),
);
});
});
assertPrivate(log);
// The kept cause line is what the client error and the request-log reason carry.
await assert.rejects(
snapshotAndroid(emulator, {
helperAdb: helperFailingWith(run),
helperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT,
}),
/uiautomator unavailable/,
);
assert.match(
JSON.stringify(diagnosticData(log, 'android_snapshot_helper_failed')),
/uiautomator unavailable/,
);
});

test('helper stderr beyond the kept budget is withheld whole, and so is a stream with only content', async () => {
const overBudget = await captureError({
exitCode: 1,
stdout: '',
stderr: `${'a'.repeat(3_000)}\n`,
});
const overBudgetWire = normalizeError(overBudget);
assert.ok(!JSON.stringify(overBudgetWire).includes(`${'a'.repeat(100)}`));
assert.equal(overBudgetWire.details?.stderr, undefined);
assert.equal(overBudgetWire.details?.stderrWithheldLines, 1);

const allContent = await captureError({
exitCode: 1,
stdout: '',
stderr: `ret" text="${SECRET}" />\n`,
});
const allContentWire = normalizeError(allContent);
assertPrivate(JSON.stringify(allContentWire));
assert.equal(allContentWire.details?.stderr, undefined);
assert.equal(allContentWire.details?.stderrWithheldLines, 1);
});

test('a session exit never leaks a sensitive value split across chunks', async () => {
const { exit, log } = await sessionExit(async (process) => {
// The payload and the sensitive key arrive in pieces, with stderr interleaved.
Expand Down Expand Up @@ -532,7 +591,9 @@ test('a nonzero exit after parseable helper output keeps no raw stream in its de

assertPrivate(JSON.stringify(normalizeError(error)));
assert.equal(error.details?.stdout, '');
// A stderr that carries no snapshot content is kept as it is, with no withheld count.
assert.equal(error.details?.stderr, 'am: Killed');
assert.equal(error.details?.stderrWithheldLines, undefined);
assert.equal(error.details?.exitCode, 1);
});

Expand Down Expand Up @@ -878,9 +939,11 @@ test('a helper that prints chunks and then times out in the executor leaks no st

assert.ok(caught instanceof AppError);
const wire = normalizeError(caught);
assertPrivate(JSON.stringify({ ...wire.details, stderr: undefined }));
// The raw stderr line held snapshot content, so it is withheld whole (#4026).
assertPrivate(JSON.stringify(wire.details));
assert.equal(caught.details?.stderr, undefined);
assert.equal(caught.details?.stderrWithheldLines, 1);
assert.equal('stdout' in (caught.details ?? {}), false);
assert.ok(typeof caught.details?.stderr === 'string');
assert.equal(caught.details?.timeoutMs, 600);
assert.equal(exitResultOf(caught.details ?? {}).statusCode, 1);
});
Expand Down
39 changes: 39 additions & 0 deletions packages/platform-android/src/instrumentation-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,45 @@ function appendLine(value: string | undefined, line: string): string | undefined
return next.length > MESSAGE_FIELD_MAX_CHARS ? value : next;
}

/**
* The helper's stderr as far as it is safe to show a caller (#4026). The run's stderr can carry
* snapshot text: `am instrument` interleaves the device process's output, and a tagless hierarchy
* fragment reads as `ret" text="…" />`. A line holding such content — an attribute-like assignment,
* markup, an entity, or a payload record — is withheld whole, as is one the budget cannot hold,
* since a cut line cannot be proven clean. What is kept stays inside `STDERR_DIAGNOSTIC_MAX_CHARS`,
* so the cause line a provider reads (`uiautomator unavailable`, `am: Killed`) survives and screen
* text does not. `withheldLines` counts every withheld line so the omission stays on the record.
*/
export function readAndroidHelperStderrDiagnostic(
stderr: unknown,
): Readonly<{ stderr?: string; withheldLines: number }> | undefined {
if (typeof stderr !== 'string') return undefined;
const kept: string[] = [];
let withheld = 0;
let keptLength = 0;
for (const line of stderr.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed) continue;
if (
keptLength + trimmed.length + 1 > STDERR_DIAGNOSTIC_MAX_CHARS ||
holdsSnapshotMarker(trimmed)
) {
withheld += 1;
continue;
}
kept.push(trimmed);
keptLength += trimmed.length + 1;
}
if (kept.length === 0) {
return withheld > 0 ? { withheldLines: withheld } : undefined;
}
return { stderr: kept.join('\n'), withheldLines: withheld };
}

// Matches the cap the parsed instrumentation fields are held to, so one budget covers every
// helper-output field an error can carry.
const STDERR_DIAGNOSTIC_MAX_CHARS = MESSAGE_FIELD_MAX_CHARS;

/**
* Whether a finished run is a start the system refused, and nothing else. All of these hold:
* - `am instrument` reported `INSTRUMENTATION_FAILED`;
Expand Down
42 changes: 33 additions & 9 deletions packages/platform-android/src/snapshot-helper-capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
import { execFailureDetails } from '@agent-device/host-kit/command';
import {
parseInstrumentationRecords,
readAndroidHelperStderrDiagnostic,
readInstrumentationResultBoolean,
readInstrumentationResultIntegerList,
readInstrumentationResultNumber,
Expand Down Expand Up @@ -116,14 +117,33 @@ export async function captureAndroidSnapshotWithHelper(
'COMMAND_FAILED',
'Android snapshot helper failed',
execFailureDetails(
{ stdout: '', stderr: result.stderr, exitCode: result.exitCode },
{ helper: output.metadata, instrumentation },
{ stdout: '', stderr: '', exitCode: result.exitCode },
{
helper: output.metadata,
instrumentation,
...androidHelperStderrDetails(result.stderr),
},
),
);
}
return output;
}

/**
* The stderr fields a helper failure publishes on its details (#4026). The run's raw stderr can
* carry snapshot text, so only the bounded, snapshot-content-free diagnostic crosses the boundary;
* `stderrWithheldLines` records what was kept out.
*/
function androidHelperStderrDetails(stderr: string): Record<string, unknown> {
const diagnostic = readAndroidHelperStderrDiagnostic(stderr);
if (!diagnostic) return {};
const { stderr: kept, withheldLines } = diagnostic;
return {
...(kept !== undefined ? { stderr: kept } : {}),
...(withheldLines > 0 ? { stderrWithheldLines: withheldLines } : {}),
};
}

/**
* The one-shot run exited on its own after the system refused to start the helper (see
* `isRefusedInstrumentationStart`), so no helper code ran on the device.
Expand All @@ -134,20 +154,22 @@ export function isAndroidSnapshotHelperStartFailure(error: unknown): boolean {

/**
* An executor failure (a deadline, a spawn error) carries the helper's raw stdout, which can hold the
* snapshot it was printing. It is replaced by the parsed instrumentation result; `stderr` and the
* typed failure metadata stay.
* snapshot it was printing. It is replaced by the parsed instrumentation result, and the raw stderr
* is replaced by the bounded, snapshot-content-free diagnostic (#4026); the typed failure metadata
* stays.
*/
function withoutRawStreams(error: unknown): unknown {
if (!(error instanceof AppError) || error.details?.stdout === undefined) return error;
const { stdout, ...details } = error.details;
const { stdout, stderr, ...details } = error.details;
return new AppError(
error.code,
error.message,
{
...details,
...androidHelperStderrDetails(typeof stderr === 'string' ? stderr : ''),
instrumentation: readInstrumentationExitResult({
stdout: typeof stdout === 'string' ? stdout : '',
stderr: typeof details.stderr === 'string' ? details.stderr : '',
stderr: typeof stderr === 'string' ? stderr : '',
exitCode: typeof details.exitCode === 'number' ? details.exitCode : null,
}),
},
Expand Down Expand Up @@ -278,19 +300,21 @@ function readAndroidSnapshotHelperOutput(
);
}
// exec-guard-allow: reachable at exit 0 (helper output unparseable); the
// message already branches on the exit code.
// message already branches on the exit code, and the raw stderr trio is not
// spread because stderr crosses only as the filtered diagnostic below.
// Stdout is not copied into the details: it can hold the snapshot the helper was printing.
// The new `instrumentation` detail is parsed fields only; `stderr` stays as it always was.
// The new `instrumentation` detail is parsed fields only; stderr is published only as the
// bounded, snapshot-content-free diagnostic (#4026).
const instrumentation = readInstrumentationExitResult(result);
throw new AppError(
'COMMAND_FAILED',
result.exitCode === 0
? 'Android snapshot helper output could not be parsed'
: 'Android snapshot helper failed before returning parseable output',
{
stderr: result.stderr,
exitCode: result.exitCode,
instrumentation,
...androidHelperStderrDetails(result.stderr),
// Read only here, where adb returned the run's own exit: a deadline or a host failure throws
// before this point, so it can never read as a refused start.
...(isRefusedInstrumentationStart(result)
Expand Down
8 changes: 5 additions & 3 deletions packages/platform-android/src/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { buildAndroidSnapshotClickabilityEvidence } from './snapshot-clickabilit
import { resolveAndroidAdbProvider, type AndroidAdbProvider } from './adb-executor.ts';
import { sleep } from './adb.ts';
import { buildAndroidSnapshotHelperCaptureOptions } from './snapshot-helper-capture.ts';
import { readAndroidHelperStderrDiagnostic } from './instrumentation-helper.ts';
import {
ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS,
ANDROID_SNAPSHOT_HELPER_COMMAND_TIMEOUT_MS,
Expand Down Expand Up @@ -738,9 +739,10 @@ function formatAndroidSnapshotHelperFailureReason(error: unknown): string {
return `${normalized.message}: ${helperMessage}`;
}
if (helperMessage) return helperMessage;
const stderr =
typeof normalized.details?.stderr === 'string' ? normalized.details.stderr.trim() : '';
const firstLine = stderr.split(/\r?\n/).find((line) => line.trim());
// The cause line comes from the same diagnostic the details carry: a helper stream can hold
// snapshot text, so an unfiltered line must not become the reason (#4026).
const stderr = readAndroidHelperStderrDiagnostic(normalized.details?.stderr)?.stderr;
const firstLine = stderr?.split('\n').find((line) => line !== '');
return firstLine ? `${normalized.message}: ${firstLine}` : normalized.message;
}

Expand Down
Loading