Repository navigation
fix(android): authenticate and bound persistent snapshot helper sessions - #4729
Conversation
…ted abstract socket (#4519) The persistent snapshot-helper session accepted loopback TCP connections and read each command line with no peer check, no deadline, and no failure containment. This implements the coordinator-approved minimal bounded protocol: - Transport: the helper binds an abstract LocalServerSocket named agentdevice-snapshot-helper-<port> (derived from sessionPort, no secret in argv) and the host forwards tcp:<port> to localabstract:<name> instead of tcp:<port>. - Admission: each accepted connection's peer is identified via LocalSocket.getPeerCredentials() before any command byte is read or any response is written; only adbd (shell uid 2000, or root uid 0 under adb root) is admitted, the adb operator trust boundary. Unreadable credentials or any other uid are closed without a response. - Absolute per-connection read budget fixed at accept time, owned by the session's own timeoutMs (fallback 8000 ms); each read gets only the remaining budget, so a drip-feeding peer cannot extend the connection the way a rolling SO_TIMEOUT would. - Bounded command framing: the command line is capped at 256 KiB, derived from the largest supported producer of this channel measured with the repo's own plan builders (a 10 s two-contact gesture is at most ~130 KB base64; the documented 64 KiB fill --text-stdin encodes to ~88 KB; the IME helper's 64,000-char cap belongs to its separate am/broadcast channel and is not reused). - Narrow containment: expected per-connection I/O failures (deadline, reset, failed response write) are answered with a session error and contained at the connection boundary; command handlers keep containing their own throwables, and a UiAutomation connect failure is answered per connection instead of ending the session. - No token in argv and no fallback that bypasses this policy: the ADR 0002 one-shot fallback after a failed start never uses the session socket. Verified on the owned Pixel_7_CI emulator (Android 16, SELinux Enforcing) through the controlled public runtime path: authorized snapshot/input/focus/quit answered ok=true over the adb-forwarded abstract socket; unknown command, silent peer (absolute deadline at ~3 s), drip-fed peer (cut at ~3 s, proving the deadline is absolute), and a 300 KiB over-limit line were each answered with a structured error while the session kept serving. SessionPeerPolicyTest covers admission, deadline, socket-name, and line decisions with synthetic inputs. Host unit tests assert the localabstract forward target. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
Size Report
Startup median (7 runs, lower is better):
|
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 2 new findings on 811e7a1. The verdict and the full list are in the summary comment.
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 2 new findings on 4ee65e1. The verdict and the full list are in the summary comment.
This comment has been minimized.
This comment has been minimized.
|
At 55bc5ee the change has one regression and two gaps against #4519. All 17 checks pass, and there are no conflicts. Before merge, please fix the snapshot connect wait, add a JVM test for the bounded reader, and post a live silent-peer and partial-peer run at the new head. The per-connection pre-acquire at SnapshotInstrumentation.java:251 is not needed for #4519. Every admitted command, including snapshot, now calls getConnectedUiAutomationUnchecked() before dispatch. That waits 8 s and wraps a timeout in IllegalStateException. Before, snapshot connected inside captureXml with the session's 2 s budget and threw TimeoutException. So when UiAutomation is not connected, a session snapshot now waits 6 s longer and answers errorType=java.lang.IllegalStateException. snapshot-capture-failure-reason.ts:12 does not classify that type, so the typed 'accessibility-timeout' reason is lost on the production session route. The host test for the fallback diagnostic still passes only because its fake helper hand-writes TimeoutException. The rule: the session snapshot connect wait is the session timeoutMs, and its failure surfaces as java.util.concurrent.TimeoutException. Please acquire the automation only in the branches that already did (input, screenshot, focus, app, viewport, gesture) and leave snapshot to captureXml. Dropping the pre-acquire entirely and keeping this PR to admission and bounds also works. The PR body reports normal snapshot, press, scroll, gesture and close runs, plus an SELinux-denied probe that never reached Java admission. It reports no run of a silent or partial authorized peer against the new deadline and cap, and #4519 requires that evidence (SnapshotInstrumentation.java:218). At the exact head, on the emulator with a live session: (a) open the host forward port with nc 127.0.0.1 , send nothing and hold it. (b) Open a second connection, send 'snapshot x' without a newline and hold it. (c) While both are held, run a CLI snapshot. The proof is that the snapshot returns within about 2 s per held connection in the same helper process, with no respawn and no android_snapshot_helper_persistent_session_disabled or session_start_failed diagnostic. Each held connection should also receive an ok=false session error frame and close at about 2 s. The UID-rejection branch being unreachable because of SELinux is fine if the PR says so. SessionPeerPolicyTest.java:455 covers only pure arithmetic and enum helpers. No test calls readSessionCommandLine or the accept loop, so two mutants survive. Deleting the admission guard at SnapshotInstrumentation.java:210 keeps every test green. Replacing the absolute deadline with one rolling setSoTimeout(readBudgetMs), or dropping the post-read clock check, does too. Admission before read and an absolute read bound are the two things #4519 is about, and nothing proves either. Please make the reader testable as readSessionCommandLine(InputStream, IntConsumer setReadTimeout, LongSupplier clock, int maxBytes). Then cover a drip-feed past the deadline throwing, exactly maxBytes plus a newline accepted, maxBytes+1 over the limit, and EOF before any byte returning null. If the reader test owns commandReadDeadlineAtMs and remainingBudgetMs, delete them. For admission, either cover it the same way with a handler that takes the peer uid, or state the gap in the PR. Not blocking, and you can take or leave these: a helper without the sessionTransport marker fails start with a deterministic reason but gets only the 10-60 s retry backoff at snapshot-helper-session-lifecycle.ts:213, so setting failedSessions(identity) to POSITIVE_INFINITY for transport_unsupported, as reusedSessionTimedOut does, would keep it one-shot; the 256 KiB frame cap and the socket-name prefix are declared in both the APK and the host (snapshot-helper-session.ts:119), so advertising the limit in the ready bundle or adding one test that compares the Java constants would tie them together; the oversize decline at snapshot-helper-session.ts:152 returns silently while the identity-mismatch skip warns, so a diagnostic with the byte length would help; and the README says an I/O failure on the response gets a session error, while the code closes that connection without a frame (SnapshotInstrumentation.java:293), and the PR body says 11 files where the diff has 13. Four inline threads no longer apply, so please resolve them: the per-byte timeout concern is moot because the reader uses one setSoTimeout per 8 KiB chunk (#4729 (comment)); the older-APK fallback is the intended fail-closed behavior from #4519 (#4729 (comment)); the abstract-namespace concern is wrong because LocalServerSocket(String) binds in the Linux abstract namespace, matching the localabstract forward (#4729 (comment)); and the SO_TIMEOUT concern is moot because both the error and normal paths reset it to the 8 s write timeout before any response write (#4729 (comment)). Please also confirm that remote adb providers accept 'forward tcp:N localabstract:name'. A provider that rewrites forward specs would make every session start fall back to one-shot. Last, the helper authenticates the client but the host does not authenticate the helper, so a co-installed app could squat the socket name after the helper dies and before the host notices. That is not a regression, since the same window existed with device TCP. The fixed 2 s read budget for a ~130 KB gesture frame over a slow adb link is also not measured. |
|
Pushed The JVM suite now calls the production reader with an injected stream, timeout setter, and clock. It covers a drip-fed newline arriving after the cutoff, exactly-max, max+1, and empty EOF. Removing the post-read clock check makes the regression fail. The UID policy has JVM coverage. The prior device negative was denied by SELinux before Java admission. For provider compatibility, the serial-backed ADB adapter passes the forward arguments through, and Android supports the abstract socket spec. Limrun supplies no process spawning and uses the existing one-shot path. I have no live third-party provider run to claim. The Android helper build and 30 focused tests passed. I resolved the four stale threads. Exact validation, hosted CI, and the requested current-head peer timing run are pending. |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 1 finding moved to a new line on 00236cd. The verdict and the full list are in the summary comment.
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 2 findings moved to a new line on f5f830b. The verdict and the full list are in the summary comment.
|
The code asks from the 55bc5ee review are fixed at f5f830b: the read budget is now a fixed 2 s from accept, independent of the capture timeout. One item is still open: there is no device run of the new read deadline and byte cap with silent and partial authorized peers. #4519 asks for that evidence, and the PR body still says live peer timing on the final head is pending. The device runs so far cover normal commands, plus an SELinux-denied probe that never reached Java. So the single-reader deadline, which is the point of #4519, is unproven on a device. Nothing yet shows that Not blocking, take or leave: add one test where the first read returns The reader tests were traced against SessionPeerPolicy.java:80-105. Whether 2 s is enough for a ~130 KB gesture frame over a slow remote adb link is still unmeasured. Of the earlier inline threads, the fixed read budget is fixed at this head, with the post-read check kept on purpose for the drip test. These three do not apply, so please resolve them: older provider APKs falling back to the one-shot path is the fail-closed behavior #4519 asks for; the abstract namespace claim is wrong, because CI is still running. Only Apex Sentinel is in progress, and it is a review bot rather than a test job; the other 16 checks passed. Before merge, please post the silent-peer and partial-peer run described above. This review covers f5f830b; the newer 1925572 will be reviewed next. |
|
The PR now distinguishes the enforcement layers. On the enforcing Pixel_7_CI image, SELinux denied the untrusted-app connection before accept, so that peer could not reach Java's UID-rejection branch. The JVM policy test covers UID decisions. The accept-loop rejection branch was not exercised live. At |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 3 new findings on 1925572. The verdict and the full list are in the summary comment.
This comment has been minimized.
This comment has been minimized.
|
Head Fixed the Coverage job failure. It was not a flake. Commit 178a45b made The three Sentinel findings were already fixed at 178a45b and their threads are resolved. The permanent unsupported-build marker needs a verified installed SHA-256 and carries its own diagnostic phase. A different verified checksum can start a session again. A host test reads Validation: |
|
The earlier findings from the review of 55bc5ee (#4729 (comment)) are fixed at 3efebd6: the read budget is now a fixed 2 s from accept, a verified marker-less build is no longer respawned after the backoff, the transport_unsupported warn fires once per build, and the host cap is one exported constant checked against the Java policy. The code looks right to me, but I cannot call it ready yet, because the evidence for the silent and partial peer run is a summary at 00236cd with no raw output. The code suggests it covers this head (same 2000 ms APK read budget and the same Java runtime as f5f830b). Please either say so in the PR body, or rerun it and show whether each held connection received an ok=false error frame. The Coverage check failed at 3efebd6. The newer 799e636 changes the session command-limit test fake, which looks like the fix; the next review will confirm it on that head. No conflicts are known. After Coverage is green, the PR can move on. Could the one-shot behavior be simpler? In the catch of tryStartAndroidSnapshotHelperSession, on the typed SESSION_TRANSPORT_UNSUPPORTED_REASON, you could call failedSessions().set(params.identity, Number.POSITIVE_INFINITY), as https://github.com/callstack/agent-device/blob/3efebd6/packages/platform-android/src/snapshot-helper-session-lifecycle.ts#L319 already does, and emit the dedicated warn only when the entry was not already present. isAndroidSnapshotHelperSessionBackedOff already stops any spawn. Production session identity is constant per build, so this keeps the one-shot behavior on every production route. It would let you delete unsupportedSessionBuilds, buildIdentity, helperSha256Verified, the install parameter of buildAndroidSnapshotHelperCaptureOptions and its threading through snapshot.ts and touch-helper.ts, about 40 production lines. The test's { ...options, waitForIdleTimeoutMs: 40 } case is input no production caller can produce. If the verified-install gate (https://github.com/callstack/agent-device/blob/3efebd6/packages/platform-android/src/snapshot-helper-session-lifecycle.ts#L192) is there on purpose for unverified providers, a line in the PR saying why closes this. Not blocking, take or leave: the simplification above; the Validation section of the PR body still names head 1925572 and a pending timing rerun, and its summary says the daemon remembers unsupported helper builds without the verified-install condition from 178a45b, so please update the head line and qualify that claim as verified installs only; and the earlier questions are still open on whether remote adb providers accept 'forward tcp:N localabstract:name' and whether the 2 s read budget holds for a ~130 KB gesture frame over a slow remote adb link. On the other review threads, the one on the read budget (#4729 (comment)), the marker-less respawn (#4729 (comment)), the transport_unsupported warn (#4729 (comment)), the verified-install gate (#4729 (comment)) and the host cap constant (#4729 (comment)) are fixed at this head, so you can resolve them. Two do not apply: the read timeout reset is already handled, since both the error and normal paths reset SO_TIMEOUT to the 8 s write timeout before any response write (#4729 (comment)), and LocalServerSocket(String) binds in the abstract namespace, matching the localabstract forward (#4729 (comment)). |
The peer uid does not bind a forwarded connection to the host: adbd relays every connection to the host forward, including one an emulator guest opens through 10.0.2.2. The helper now draws a 32-byte secret at startup, reports it only in its ready record on the am instrument stdout, and runs an HMAC-SHA256 challenge-response before it reads any command: the peer sends a nonce, the helper answers with its nonce and a proof over both, and the peer must answer with its own proof. The uid check stays as defense in depth.
…secret The host keeps the ready record's session secret in memory, proves it on each connection, and sends the command only after the helper's proof matches with a constant-time compare. A listener that cannot prove it, such as a process that bound the freed socket name, gets the nonce and no command; the session is dropped with a typed diagnostic and the call runs one-shot.
|
Head Design: a per-session secret, proven on every connection#4519 earlier listed a helper-generated token as "a separate possible policy, not adopted". This review makes it the chosen policy. The peer uid does not bind a forwarded connection to the host. adbd relays every connection to the host forward, including one that an emulator guest opens through
Production line counts for this round (excluding tests and fixtures, against
Tests (each fails on 1a79bce)
Live evidence
(a) Session start, then a reused snapshot: (b) Forward bypass, through the host forward From inside the guest, through After the bypass attempts, the helper PID stayed 4667, and the next CLI snapshot reused the session. Logcat has no crash and no I did not run (b) for socket substitution on a device. Making a foreign process bind the helper's abstract name needs a second app or root. The host tests cover it with a listener that answers without the proof. Security pass
Validation
|
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 1 new finding on 23ff71b. The verdict and the full list are in the summary comment.
A touch command that meets an unverified listener now retires the session through the same timed start backoff a failed capture earns, instead of a plain stop, so the commands that follow go straight to one-shot rather than restarting the session and paying the refusal again.
|
Head
|
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 1 new finding on 68adbe9. The verdict and the full list are in the summary comment.
… valid proof The handshake now tracks its phase explicitly. A refused connection or a socket that closes before the peer's first byte stays the ordinary transport failure with its original error, so it is stopped and disclosed as before; only a peer that answered and failed the proof is refused as unverified and backed off.
|
Head
|
This comment has been minimized.
This comment has been minimized.
|
Thanks for the handshake. At e15bc9d both bypasses from the earlier review are closed. A forwarded connection without the session secret cannot get a command dispatched, and a substituted listener receives only the host nonce. The secret reaches the host over the instrumentation watcher and is fresh per launch. Both proofs use distinct labels and constant-time comparison, a clean close before the hello fails without retrying input, and CI is green. One small hardening gap remains on the host side before this is ready.
Not blocking: SessionFrameWriter.java:57–61 checks the clock before the last nonblocking send and counts a positive result without checking again, so a pause between the check and the send lets that send finish after the deadline. A deadline cannot take back bytes the kernel accepted, so a one-line comment saying so, or a recheck after the send, is enough. Also from the 68adbe9 pass: a silent peer that times out before the hello could be classified as not dispatched so the touch path falls back to one-shot, and the helper README should describe the hello as one line, |
The host now requires the hello newline at exactly byte 129 and the line to be one 64-hex nonce, a space and one 64-hex proof, checked before any HMAC is computed; a longer line or a third field is refused. A request that times out before a proven hello is disclosed as not dispatched, so a mutation falls back to one-shot. The helper README describes the hello line, and the frame writer notes why a send that ends past the deadline is not checked again.
|
Head
|
This comment has been minimized.
This comment has been minimized.
|
Thanks. At 8eaec9b the hello is accepted only as exactly The data handler still concatenates the whole incoming chunk into |
The host takes at most the 130 bytes of the hello line from each chunk and refuses when byte 129 is not the newline, or when any byte follows the line before the client proof is sent; nothing from that window reaches the response. The refusal reports how many bytes it kept.
|
Head
|
Apex Sentinel · ✅ Approve · review of
|
| Command | What it does |
|---|---|
@apex-sentinel-staging note <context> |
Adds context; Sentinel re-checks the cited code |
@apex-sentinel-staging pivot <why> |
Says the finding is wrong; Sentinel re-checks the cited code |
@apex-sentinel-staging like |
Marks the finding as useful |
@apex-sentinel-staging dislike <why> |
Marks it as not useful, so it is not raised again |
On this conversation, comment @apex-sentinel-staging review to run a full review once again.
|
This PR is ready at 2496202. The pre-verification buffer now holds at most one hello line on every chunk split, a byte past that window or a misplaced newline is refused, and nothing after the newline is kept before the proof verifies. With that, the session boundary holds end to end:
All checks pass. Not blocking: the same-chunk test in snapshot-helper-session-touch-peer.test.ts writes the hello and the trailing bytes in one |
* origin/main: (70 commits) refactor(apple-runner): one RUNNER_ERROR_CODES row per runner error code with parity/docs gates (callstack#4774) fix(android): require acknowledgements for test IME typing (callstack#4722) feat(scroll): add scroll refresh for pull-to-refresh (callstack#4770) refactor(host-kit): add request Scope and use it for the wait capture deadline (callstack#4794) fix(android): let permission all change nothing on an app that declares no permissions (callstack#4796) fix(cli): replace the CLI session and generated remote config instead of rewriting them in place (callstack#4797) fix(host-kit): accept a group-writable script directory the user owns (callstack#4799) fix(cli): escape control characters at the CLI's stdout and stderr writes (callstack#4778) fix(audit): do not report rows under a persistent bar that scrolling reveals (callstack#4775) fix(daemon): refuse an unsafe state directory before first use (callstack#4783) refactor: settle remaining single-deadline races through settleWithin (callstack#4788) refactor(host-kit): settle deadline races via settleWithin with R87 race ratchet (callstack#4766) fix(android): authenticate and bound persistent snapshot helper sessions (callstack#4729) fix(daemon): bound upload ingress and finalization (callstack#4721) chore(gates): ratchet wire-published reason literals by value (R89) (callstack#4779) feat(audit): evaluate role-less clickable views on Android (callstack#4780) fix(mutation): keep umask-setting tests out of Stryker's thread pool (callstack#4785) feat(audit): report controls that share one accessible name (callstack#4771) fix(contracts): pair open runtime hints with their apply operation (callstack#4754) refactor(daemon): report startup progress over the launch channel instead of marker files (callstack#4777) ...
Summary
Persistent snapshot-helper sessions are activated by a versioned mode, not by a port. The host
launches
-e mode authenticated-session-v1 -e sessionSocket <name>and neversessionPort. Ahelper build that does not implement that mode rejects the launch in
onStart, before it bindsanything, so an old build on the device keeps the one-shot transport and never opens a loopback TCP
listener. Nothing is read from the artifact to decide this: provider-supplied artifacts serve
sessions exactly like the bundled one.
The host owns the whole abstract socket name. The helper binds the launched name unchanged and
refuses any name outside the
agentdevice-snapshot-helper-namespace. Readiness repeats the name insessionSocket, and the host refuses a record naming another socket, so the launch arguments, theforward, and the ready record must agree. A ready record that is not well formed is an ordinary
failed start, handled by the existing finite start backoff.
Before reading a command, the helper admits only the kernel-reported shell or root UID used by adb,
or closes the peer when that identity cannot be read at all. The UID check alone does not bind a
connection to the host: adbd relays every connection to the host forward, including one an emulator
guest opens through
10.0.2.2:<port>, and adbd re-resolves the abstract name per connection, so aprocess that binds the name after the helper exits would receive the next command. The per-session
secret binds both directions. At startup the helper draws 32 bytes with
SecureRandomand reportsthem only as
sessionSecretin its ready record, on the stdout of theam instrumentrun the hoststarted; the secret is never in argv, logcat, a file or a diagnostic, and it never crosses the
socket. Every connection runs an HMAC-SHA256 challenge-response before any command byte: the host
sends a nonce, the helper answers with its nonce and a server proof over both, the host checks it in
constant time and only then sends its client proof and the command, and the helper checks the client
proof with
MessageDigest.isEqualbefore it reads the command. A listener that cannot prove thesecret gets the nonce and nothing else; the host drops that session with a typed diagnostic and
answers the call one-shot. The UID check stays as defense in depth.
Each command ends with a newline. Reads are nonblocking with poll, so the deadline holds on Android
7.0 and 7.1.0 too, where the socket timeout covers sends only. A connection gets a read deadline of
2 s from accept plus 1 s for each 64 KiB of command bytes received; bytes after the newline, and
bytes after the deadline, earn nothing. A silent peer closes at 2 s, and the largest frame can arrive
over a link of about 0.5 Mbit/s. A read that expires, or that reaches EOF before the newline, closes
without a reply. Each command frame is limited to 513 KiB on the host and in the helper, covering a
64 KiB stdin fill of JSON-escaped control characters and the largest gesture plan. The cap is decided
from the raw byte count as soon as it is crossed, so a capped prefix is never decoded, and a complete
frame is decoded strictly: malformed UTF-8 closes the connection instead of reaching the parser. An
empty or over-cap frame is answered with one error frame; any other read failure closes silently.
Every session wait takes the absolute deadline and measures its own remaining time when it starts,
through one helper, so a pause before a wait cannot extend it. Each response is one frame, built
inside the command's failure boundary, so an encoding failure returns a minimal error frame without
the success payload. The frame goes out in nonblocking sends under one deadline, fixed when the write
starts: 8 s plus the frame size at 64 KiB/s. A peer that stops reading is closed at that deadline.
The helper uses only API 23 platform classes.
Refs #4519.
Validation
Base
6e18ea3349. Head249620200b.249620200b,pnpm check:affected --run: passed (exactCommit=true): format, lint, typecheck, layering, fallow, native-dupes, build, vitest-related, unit. The JVM suite runs inpnpm build:androidand passed. Coverage and Android smoke run in CI.1a79bce: with the 1a79bce host, an unproven listener receivedsnapshot snapshot-…and the touch path sent the input; with the handshake removed from the helper, all sixSessionHandshakeTestcases fail.emulator-5562, because that AVD was running onemulator-5556), head APK with installed digest equal to the artifact: session snapshot then a reused snapshot onandroid-helper. Through the host forward, a command without the handshake got 0 bytes and a close; a valid nonce got the server hello, and a wrong client proof plus command got a close with nothing more. From inside the guest through10.0.2.2, a raw command got 0 bytes and a nonce got only the hello. The helper PID did not change and the next snapshot reused the session.68adbe9b79(host only): a touch command that meets an unverified listener retires the session through the timed start backoff, so later commands go one-shot without restarting the session; the new test fails on23ff71bc9f.e15bc9db48(host only): a refused connection or a socket that closes before the peer's first byte is an ordinary transport failure with its original error; only a peer that answered without a valid proof is unverified. The new tests fail on68adbe9b79.8eaec9b1e7(host only, plus a Java comment): the hello is accepted only as one 64-hex nonce, one space and one 64-hex proof with the newline at byte 129, validated before any HMAC; a request that times out before a proven hello is disclosed as not dispatched. The new tests fail one15bc9db48.249620200b(host only): the host keeps at most the 130-byte hello line from an unverified peer and refuses a missing newline at byte 129 or any byte after the line before its client proof; the new tests fail on8eaec9b1e7.Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.