Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
61e7178
fix(android-helper): defensive bounded session protocol over an admit…
thymikee Nov 19, 2026
811e7a1
fix(android): preflight helper framing and preserve SDK compatibility
thymikee Nov 19, 2026
4ee65e1
fix(android): buffer session reads and require authenticated readiness
thymikee Nov 19, 2026
55bc5ee
fix(android): separate helper request reads from response writes
thymikee Nov 19, 2026
00236cd
fix(android): preserve snapshot connection timeout and test session r…
thymikee Nov 19, 2026
f5f830b
fix(android-helper): separate command read and capture deadlines
thymikee Nov 19, 2026
1925572
fix(android-helper): remember unsupported session transports by helpe…
thymikee Nov 19, 2026
178a45b
fix(android-helper): diagnose verified unsupported builds and check t…
thymikee Nov 19, 2026
3efebd6
fix(android-helper): consolidate capture option type imports
thymikee Nov 19, 2026
799e636
test(android-helper): keep the real command byte cap in the session l…
thymikee Nov 19, 2026
834b0be
refactor(android-helper): remember verified unsupported builds in the…
thymikee Nov 19, 2026
dc2dd72
fix(android-helper): key the unsupported-build decision by helper build
thymikee Nov 19, 2026
c7b6e8f
test(android-helper): cover the five session transport defects before…
thymikee Nov 19, 2026
dbaba3d
fix(android-helper): close incomplete session reads and write each re…
thymikee Nov 19, 2026
6085510
fix(android): keep remembered installs out of the unsupported-build d…
thymikee Nov 19, 2026
ffc943d
docs(android-helper): note how LocalSocket reports a read timeout
thymikee Nov 19, 2026
f6c662f
fix(android): record the declined over-limit session frame
thymikee Nov 19, 2026
3ed1de1
test(android-helper): cover repeated unverified starts and a slow max…
thymikee Nov 19, 2026
dd49ec6
fix(android-helper): extend the read deadline per received byte and e…
thymikee Nov 19, 2026
b2ee5c5
fix(android): mark an unsupported session transport by helper build u…
thymikee Nov 19, 2026
ccf41b6
test(android): cover interleaved readiness output and an unverified u…
thymikee Nov 19, 2026
30632ac
fix(android-helper): bound each response by one deadline and keep enc…
thymikee Nov 19, 2026
e7e71cc
fix(android): classify session readiness from one complete stdout record
thymikee Nov 19, 2026
8953878
refactor(android-helper): share one capture step between one-shot and…
thymikee Nov 19, 2026
9821674
fix(android-helper): wait for send room only as long as the frame dea…
thymikee Nov 19, 2026
7e8be5e
fix(android): never mark a helper build unsupported for good
thymikee Nov 19, 2026
9d0c373
fix(android-helper): read commands nonblocking against the accept dea…
thymikee Nov 19, 2026
652c465
fix(android): require the launched session port in the readiness record
thymikee Nov 19, 2026
639d6f8
refactor(android-helper): activate sessions by versioned mode, not by…
thymikee Nov 19, 2026
d51238b
refactor(android-helper): drop the artifact capability gate and thin …
thymikee Nov 19, 2026
1a79bce
fix(android-helper): poll in short slices so a pause cannot overrun t…
thymikee Nov 20, 2026
8043156
fix(android-helper): prove a per-session secret on every connection
thymikee Nov 20, 2026
23ff71b
fix(android): send session commands only after the helper proves the …
thymikee Nov 20, 2026
68adbe9
fix(android): back off a session whose peer did not prove the secret
thymikee Nov 20, 2026
e15bc9d
fix(android): call a peer unverified only after it answered without a…
thymikee Nov 20, 2026
8eaec9b
fix(android): accept the session hello only as one nonce and one proof
thymikee Nov 20, 2026
2496202
fix(android): keep at most one hello line from an unverified peer
thymikee Nov 20, 2026
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
25 changes: 21 additions & 4 deletions android/snapshot-helper/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,27 @@ The `gesture` payload is a base64-encoded JSON object using protocol `android-to
## Persistent Session

Passing `-e sessionPort <port>` keeps the instrumentation alive after startup and serves repeated
commands over a local TCP server on `127.0.0.1:<port>`, instead of exiting after one snapshot. This
avoids paying UiAutomation connect/teardown cost per call. Each command uses one short-lived
connection: the client connects, sends a single command line, reads the response, and the server
closes that connection; the process stays alive for the next connection:
commands over an abstract `localabstract:` UNIX socket named `agentdevice-snapshot-helper-<port>`,
reached from the host through `adb forward tcp:<port> localabstract:agentdevice-snapshot-helper-<port>`,
instead of exiting after one snapshot. This avoids paying UiAutomation connect/teardown cost per
call. Each command uses one short-lived connection: the client connects, sends a single command
line, reads the response, and the server closes that connection; the process stays alive for the
next connection.

Each accepted connection is admitted before any command byte is read: the helper reads the
forwarded peer's kernel credentials with `LocalSocket.getPeerCredentials()` and serves only adbd —
shell uid 2000, or root uid 0 when adb runs in its supported root mode. Both are the adb operator
trust boundary; any other uid (or an unreadable credential) is closed without a response. The socket
name derives from the port and carries no secret, and no token travels in argv.

The command line of each connection is bounded twice. Its read runs under an absolute per-connection
deadline fixed at accept time, owned by the session's own `timeoutMs` (fallback 8000 ms), so a
silent or drip-feeding peer cannot hold the command reader past that budget; and the line itself is
capped at 256 KiB, a bound derived from the largest supported producer of this channel (a 10 s
two-contact gesture carries 1,252 densified samples, at most ~130 KB base64; the documented 64 KiB
`fill --text-stdin` contract encodes to ~88 KB — the cap keeps at least 2x headroom over both). A
connection that hits either bound, or fails its read or response with an expected I/O error, is
answered with a session error and closed; the session keeps serving the next connection:

- `snapshot <requestId>` — capture and return an XML snapshot, same semantics as the default mode
- `snapshot-immediate <requestId>` — capture fresh XML without an idle wait when the caller owns settling
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package com.callstack.agentdevice.snapshothelper;

import java.nio.charset.StandardCharsets;

/**
* Pure admission and bound decisions for persistent-session connections. Every decision is a
* function of its inputs only, so the test suite drives it with synthetic peers: no socket, no
* clock, no Android runtime.
*
* <p>The session transport is an abstract {@code localabstract:} socket reached through
* {@code adb forward tcp:<host port> localabstract:<name>}. The forwarded peer of such a
* connection is adbd, which runs as root when adb is rooted and as shell otherwise; both uids are
* the adb operator trust boundary, and the forwarded uid is not the original host user's identity.
* Any other uid is an untrusted co-installed peer and is rejected before any command byte is read.
*/
final class SessionPeerPolicy {
/** adbd with {@code adb root} (a supported adb mode); the root-mode adb operator. */
static final int PEER_UID_ROOT = 0;
/** adbd in its default shell configuration. */
static final int PEER_UID_SHELL = 2000;

/**
* Prefix of the abstract socket name, shared with the host's forward spec. The name is derived
* from the session port and carries no secret: admission is the peer uid, not name secrecy.
*/
static final String SESSION_SOCKET_PREFIX = "agentdevice-snapshot-helper-";

/**
* The per-connection command-line byte cap. Derived from the largest supported producer of this
* channel, measured with the repository's own plan builders: a 10 s two-contact gesture carries
* 1,252 densified samples (2 pointers x 626 samples on the 16 ms grid), whose base64 command line
* is at most ~130 KB, and the documented 64 KiB {@code fill --text-stdin} contract encodes to
* ~88 KB. 256 KiB bounds both with at least 2x headroom. The IME helper's 64,000-base64-char
* cap belongs to its separate am/broadcast channel and is deliberately not reused here.
*/
static final int MAX_COMMAND_LINE_BYTES = 256 * 1024;

enum Admission {
ADMITTED,
REJECTED_UNAUTHORIZED_PEER
}

enum LineDecision {
ACCEPTED,
REJECTED_EMPTY,
REJECTED_OVER_LIMIT
}

private SessionPeerPolicy() {}

static Admission admitPeer(int uid) {
return uid == PEER_UID_ROOT || uid == PEER_UID_SHELL
? Admission.ADMITTED
: Admission.REJECTED_UNAUTHORIZED_PEER;
}

/**
* The abstract socket name for a session port. Deterministic and secret-free, so the host and
* the helper derive the same name from the same port without passing anything sensitive in argv.
*/
static String sessionSocketName(int sessionPort) {
return SESSION_SOCKET_PREFIX + sessionPort;
}

/**
* The per-connection command read budget, owned by the session's own configured timeout: a host
* sends its command immediately after connecting, so a peer silent past that budget is rejected
* instead of occupying the command reader. Zero or negative falls back to the caller's default
* timeout, never to an unbounded read.
*/
static long commandReadDeadlineMs(long sessionTimeoutMs, long fallbackTimeoutMs) {
long budgetMs = sessionTimeoutMs > 0 ? sessionTimeoutMs : Math.max(0, fallbackTimeoutMs);
return Math.min(Integer.MAX_VALUE, budgetMs);
}

/**
* The absolute deadline instant for one connection's command read, fixed at accept time. The
* remaining budget shrinks toward zero no matter how many reads the peer forces, unlike a
* rolling SO_TIMEOUT that resets on every read.
*/
static long commandReadDeadlineAtMs(long acceptedAtMs, long budgetMs) {
return acceptedAtMs + Math.max(0, budgetMs);
}

/** The budget left before {@code deadlineAtMs}, never negative. */
static long remainingBudgetMs(long deadlineAtMs, long nowMs) {
return Math.max(0, deadlineAtMs - nowMs);
}

static LineDecision commandLineDecision(String line, int maxLineBytes) {
if (line == null || line.isEmpty()) {
return LineDecision.REJECTED_EMPTY;
}
return line.getBytes(StandardCharsets.UTF_8).length > maxLineBytes
? LineDecision.REJECTED_OVER_LIMIT
: LineDecision.ACCEPTED;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,24 @@
import android.app.Instrumentation;
import android.app.UiAutomation;
import android.content.res.Resources;
import android.net.Credentials;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.lang.reflect.Field;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.concurrent.TimeoutException;
Expand Down Expand Up @@ -178,8 +180,12 @@
int maxDepth,
int maxNodes)
throws IOException {
try (ServerSocket server =
new ServerSocket(sessionPort, 1, InetAddress.getByName("127.0.0.1"))) {
// The session socket lives in the abstract namespace, reached from the host through
// `adb forward tcp:<port> localabstract:<name>`; the forwarded peer is adbd, and its uid is
// checked before any command byte is read. The name is derived from the port and carries no
// secret — admission is the peer uid, not name secrecy.
try (LocalServerSocket server =
new LocalServerSocket(SessionPeerPolicy.sessionSocketName(sessionPort))) {
Bundle ready = new Bundle();
putBaseMetadata(
ready, waitForIdleTimeoutMs, waitForIdleQuietMs, timeoutMs, maxDepth, maxNodes);
Expand All @@ -189,66 +195,161 @@
ready.putString("sessionPort", Integer.toString(sessionPort));
sendStatus(2, ready);

// Each connection's command read is bounded by the session's own timeout, fixed at accept
// time: a host sends its command immediately after connecting, so a peer silent past that
// budget is answered with an error instead of occupying the command reader.
long readBudgetMs =
SessionPeerPolicy.commandReadDeadlineMs(timeoutMs, DEFAULT_TIMEOUT_MS);
while (!Thread.currentThread().isInterrupted()) {
try (Socket socket = server.accept()) {
String command =
new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8))
.readLine();
if (command == null) {
SessionResponseWriter.writeSessionError(
socket.getOutputStream(), "", new EOFException("empty command"));
try (LocalSocket socket = server.accept()) {
// Positive peer identity first: a peer that is not adbd (shell uid 2000, or root uid 0
// under `adb root`) — or whose credentials cannot be read at all — is rejected before
// any command byte is read and before any response is written.
if (!admitSessionPeer(socket)) {
continue;
}
String[] parts = command.trim().split("\\s+", 3);
String action = parts.length > 0 ? parts[0] : "";
String requestId = parts.length > 1 ? parts[1] : "";
if ("quit".equals(action)) {
SessionResponseWriter.writeSessionOk(socket.getOutputStream(), requestId);
return;
}
if ("input".equals(action) || "screenshot".equals(action) || "focus".equals(action) || "app".equals(action)) {
AutomationCommandHandler.writeSessionResponse(
socket.getOutputStream(), requestId, action,
parts.length > 2 ? parts[2] : "", getConnectedUiAutomationUnchecked(), getContext());
continue;
}
if ("viewport".equals(action)) {
TouchCommandHandler.writeSessionViewport(
socket.getOutputStream(), requestId, getConnectedUiAutomationUnchecked());
continue;
}
if ("gesture".equals(action)) {
TouchCommandHandler.writeSessionGesture(
socket.getOutputStream(),
requestId,
parts.length > 2 ? parts[2] : "",
getConnectedUiAutomationUnchecked());
continue;
}
if (!"snapshot".equals(action) && !"snapshot-immediate".equals(action)
&& !"snapshot-short-idle".equals(action)) {
SessionResponseWriter.writeSessionError(
long deadlineAtMs =
SessionPeerPolicy.commandReadDeadlineAtMs(SystemClock.elapsedRealtime(), readBudgetMs);
String requestId = "";
try {
String command =
readSessionCommandLine(socket, deadlineAtMs, SessionPeerPolicy.MAX_COMMAND_LINE_BYTES);
SessionPeerPolicy.LineDecision lineDecision =
SessionPeerPolicy.commandLineDecision(command, SessionPeerPolicy.MAX_COMMAND_LINE_BYTES);
if (lineDecision == SessionPeerPolicy.LineDecision.REJECTED_EMPTY) {
SessionResponseWriter.writeSessionError(
socket.getOutputStream(), "", new EOFException("empty command"));
continue;
}
if (lineDecision == SessionPeerPolicy.LineDecision.REJECTED_OVER_LIMIT) {
SessionResponseWriter.writeSessionError(
socket.getOutputStream(), "",
new IllegalArgumentException("session command over the byte limit"));
continue;
}
String[] parts = command.trim().split("\\s+", 3);
String action = parts.length > 0 ? parts[0] : "";
requestId = parts.length > 1 ? parts[1] : "";
if ("quit".equals(action)) {
writeSessionOkQuietly(socket, requestId);
return;
}
// The automation context is acquired per connection, after admission: a connect
// failure is this connection's failure, answered like the capture failure below
// instead of ending the session for the next peer.
UiAutomation automation;
try {
automation = getConnectedUiAutomationUnchecked();
} catch (RuntimeException error) {
SessionResponseWriter.writeSessionError(socket.getOutputStream(), requestId, error);
continue;
}
if ("input".equals(action) || "screenshot".equals(action) || "focus".equals(action) || "app".equals(action)) {
AutomationCommandHandler.writeSessionResponse(
socket.getOutputStream(), requestId, action,
parts.length > 2 ? parts[2] : "", automation, getContext());
continue;
}
if ("viewport".equals(action)) {
TouchCommandHandler.writeSessionViewport(
socket.getOutputStream(), requestId, automation);
continue;
}
if ("gesture".equals(action)) {
TouchCommandHandler.writeSessionGesture(
socket.getOutputStream(),
requestId,
parts.length > 2 ? parts[2] : "",
automation);
continue;
}
if (!"snapshot".equals(action) && !"snapshot-immediate".equals(action)
&& !"snapshot-short-idle".equals(action)) {
SessionResponseWriter.writeSessionError(
socket.getOutputStream(),
requestId,
new IllegalArgumentException("unknown session command"));
continue;
}
writeSessionSnapshot(
socket.getOutputStream(),
requestId,
new IllegalArgumentException("unknown session command"));
continue;
waitForIdleQuietMs,
"snapshot-immediate".equals(action) ? 0
: "snapshot-short-idle".equals(action) ? Math.min(waitForIdleTimeoutMs, SHORT_IDLE_TIMEOUT_MS)
: waitForIdleTimeoutMs,
timeoutMs,
maxDepth,
maxNodes);
} catch (IOException error) {
// One connection's expected I/O failure — a silent peer past the absolute read
// deadline, a command line over the byte cap, a response the peer never read — is
// answered with an error and contained here, so the session keeps serving the next
// connection. Command handlers contain their own throwables and answer with session
// errors themselves.
try {
SessionResponseWriter.writeSessionError(socket.getOutputStream(), requestId, error);
} catch (IOException ignored) {
// The peer is already gone; nothing is left to tell it.
}
}
writeSessionSnapshot(
socket.getOutputStream(),
requestId,
waitForIdleQuietMs,
"snapshot-immediate".equals(action) ? 0
: "snapshot-short-idle".equals(action) ? Math.min(waitForIdleTimeoutMs, SHORT_IDLE_TIMEOUT_MS)
: waitForIdleTimeoutMs,
timeoutMs,
maxDepth,
maxNodes);
}
}
}
}

/**
* Reads the peer's kernel credentials and admits only adbd. A credential read that fails for any
* reason is a peer that cannot be positively identified, so it is rejected: the session never
* serves a peer it could not verify.
*/
private static boolean admitSessionPeer(LocalSocket socket) {
Credentials credentials;
try {
credentials = socket.getPeerCredentials();
} catch (Throwable error) {
return false;
}
return SessionPeerPolicy.admitPeer(credentials.getUid()) == SessionPeerPolicy.Admission.ADMITTED;
}

/**
* Reads one newline-terminated command line under an absolute deadline fixed at accept time and
* a hard byte cap. Each read gets only the budget still left before the deadline, so a peer that
* drip-feeds bytes cannot extend the connection past it the way a rolling SO_TIMEOUT would. The
* buffer holds at most {@code maxBytes + 1} bytes: past the cap the read stops and the line is
* returned for the policy to reject, so the over-limit response has one owner. Returns null on
* end-of-stream before any byte.
*/
private static String readSessionCommandLine(LocalSocket socket, long deadlineAtMs, int maxBytes)
throws IOException {
InputStream input = socket.getInputStream();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
while (true) {
long remainingMs =
SessionPeerPolicy.remainingBudgetMs(deadlineAtMs, SystemClock.elapsedRealtime());
if (remainingMs <= 0) {
throw new SocketTimeoutException("session command read deadline exceeded");
}
socket.setSoTimeout((int) remainingMs);
int next = input.read();
if (next < 0 && bytes.size() == 0) return null;
if (next < 0 || next == '\n') break;
bytes.write(next);
if (bytes.size() > maxBytes) break;
}
return new String(bytes.toByteArray(), StandardCharsets.UTF_8);
}

Check warning on line 342 in android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/SnapshotInstrumentation.java

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

minor: Byte-at-a-time command read can blow the 2 s session read budget on large gestures

A \~130 KB base64 gesture frame requires \~260,000 `input.read()` and `socket.setSoTimeout()` syscalls (one per byte) to finish inside the 2-second `SESSION_CAPTURE_TIMEOUT_MS = 2000` deadline, so on a slow host the read crosses it and the gesture is lost with `dispatched: unknown`. The predecessor used `BufferedReader.readLine()`, costing a handful of reads for the same frame.

private static void writeSessionOkQuietly(LocalSocket socket, String requestId) {
try {
SessionResponseWriter.writeSessionOk(socket.getOutputStream(), requestId);
} catch (IOException ignored) {
// A quit the peer never read still ends the session; the host reads release from the
// process exit, not from this acknowledgement.
}
}

private void writeSessionSnapshot(
OutputStream output,
String requestId,
Expand Down
Loading
Loading