Skip to content

fix(android): authenticate and bound persistent snapshot helper sessions - #4729

Merged
thymikee merged 37 commits into
mainfrom
t3/android-helper-auth-main
Nov 20, 2026
Merged

thymikee merged 37 commits into
mainfrom
t3/android-helper-auth-main

Conversation

@thymikee

@thymikee thymikee commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

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 never sessionPort. A
helper build that does not implement that mode rejects the launch in onStart, before it binds
anything, 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 in
sessionSocket, and the host refuses a record naming another socket, so the launch arguments, the
forward, 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 a
process 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 SecureRandom and reports
them only as sessionSecret in its ready record, on the stdout of the am instrument run the host
started; 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.isEqual before it reads the command. A listener that cannot prove the
secret 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. Head 249620200b.

  • At 249620200b, pnpm check:affected --run: passed (exactCommit=true): format, lint, typecheck, layering, fallow, native-dupes, build, vitest-related, unit. The JVM suite runs in pnpm build:android and passed. Coverage and Android smoke run in CI.
  • Secret handshake, red on 1a79bce: with the 1a79bce host, an unproven listener received snapshot snapshot-… and the touch path sent the input; with the handshake removed from the helper, all six SessionHandshakeTest cases fail.
  • Android 17 emulator (a temporary clone of the Pixel_9_Pro_XL_API_37 image on emulator-5562, because that AVD was running on emulator-5556), head APK with installed digest equal to the artifact: session snapshot then a reused snapshot on android-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 through 10.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 on 23ff71bc9f.
  • 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 on 68adbe9b79.
  • 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 on e15bc9db48.
  • 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 on 8eaec9b1e7.
  • Earlier rounds, still valid for the unchanged transport: Android 7.0 and API 23 runs, and real LocalSocket backpressure on a rootable Android 16 emulator.

Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

View guided diff Turn on auto-fix

thymikee and others added 2 commits November 19, 2026 06:48
…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>
@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.39 MB 6.40 MB +7.3 kB
Package (unpacked) 6.39 MB 6.40 MB +7.3 kB
Package (download) 1.94 MB 1.95 MB +7.1 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 40.3 ms 51.5 ms +11.1 ms
CLI --help 80.0 ms 92.4 ms +12.4 ms

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 2 new findings on 811e7a1. The verdict and the full list are in the summary comment.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 2 new findings on 4ee65e1. The verdict and the full list are in the summary comment.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

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.

@thymikee

Copy link
Copy Markdown
Member Author

Pushed 00236cd52 for the reader and snapshot review. Snapshot commands again acquire UiAutomation through captureXml under the session budget. Only the existing automation, viewport, and gesture branches use the explicit connection helper.

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.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 finding moved to a new line on 00236cd. The verdict and the full list are in the summary comment.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 2 findings moved to a new line on f5f830b. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

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 LocalSocket SO_TIMEOUT fires within the remaining budget and that the session survives without a respawn (SnapshotInstrumentation.java:206). Please run this at the current head (1925572 or later; it only changes host-side transport memory) on the emulator with a live session and the rebuilt APK. First, run nc 127.0.0.1 <sessionPort>, send nothing, and hold the connection. Second, open another connection, send snapshot x with no newline, and hold it. Third, while both are held, run a CLI snapshot. Please post the timings and output. The run should show four things: each held connection gets an ok=false session error frame and closes about 2 s after accept; the CLI snapshot returns after roughly 2 s per queued held connection; the helper process stays the same, with no respawn; and no android_snapshot_helper_persistent_session_disabled or session_start_failed diagnostic appears. Please also state in the PR that the UID-rejection branch cannot be reached on a device because of SELinux. This run also settles whether SO_TIMEOUT raises an exception instead of returning -1 after a partial line, which needs a device to settle.

Not blocking, take or leave: add one test where the first read returns a and moves the clock to exactly deadlineAtMs, asserting a SocketTimeoutException and no setMillis(0), because the > check at SessionPeerPolicy.java:92 now lets that case through and only the pre-read guard prevents an infinite read, yet deleting it keeps the suite green; reword the class doc at SessionPeerPolicy.java:10, which still says "no socket, no clock", to say the clock and timeout are injected; and in the PR body, say that admission is covered at the policy level only (the accept-loop guard at SnapshotInstrumentation.java:203 is not), and that the diff has 13 files, not 11.

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 LocalServerSocket(String) binds in the abstract namespace like the localabstract forward; and the SO_TIMEOUT reset claim is moot, because both paths reset it to the 8 s write timeout before any response write.

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.

@thymikee

Copy link
Copy Markdown
Member Author

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 00236cd, two live runs showed silent-peer closure at 2.018–2.029 s and partial-peer closure about 2.0 s after the helper accepted it. The CLI snapshot was submitted while both peers were held, returned successfully in the same process, and emitted no warnings or errors. I'll repeat the run on the current head once the IME check releases the shared emulator.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 3 new findings on 1925572. The verdict and the full list are in the summary comment.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Head 799e636162ae97400aa6fc5d68a769fd64c3d248.

Fixed the Coverage job failure. It was not a flake. Commit 178a45b made snapshot-helper-session.ts import ANDROID_SNAPSHOT_HELPER_SESSION_MAX_COMMAND_BYTES from the session protocol module. The command-limit test mocked that module with only the dispatch spy. The missing export made the import throw in every run. The test now keeps the real constant through a partial mock and doubles only dispatch. No thresholds or allowlists changed.

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 SessionPeerPolicy.java and asserts the socket prefix and command byte cap match the host.

Validation: pnpm check:affected --run passed at 799e636 with exactCommit: true (format, lint, typecheck, layering, fallow, native-dupes, build, vitest-related, unit). Coverage and Android lanes are GitHub-authoritative and will run on this push.

@thymikee

Copy link
Copy Markdown
Member Author

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.
@thymikee

Copy link
Copy Markdown
Member Author

Head 23ff71bc9f1e57dc9d4cbbb6e7b390aa68ae1263. This answers the 1a79bce review: forward bypass and socket substitution. The fixes are in 80431569a5 (helper) and 23ff71bc9f (host).

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 10.0.2.2:<port>. adbd also re-resolves the abstract name for every connection.

  • Secret: at startup the helper draws 32 bytes with SecureRandom. It reports them only as sessionSecret in its ready record, on the stdout of the am instrument -w run the host started. The secret is never in argv, logcat, a file or a diagnostic. The host keeps it on the in-memory session record.

  • Handshake before any command byte (every field is 64 lowercase hex characters on its own line):

    1. The host sends nonce_c.
    2. The helper answers nonce_s HMAC-SHA256(secret, "agent-device-session-server|" + nonce_c + nonce_s).
    3. The host checks the server proof with timingSafeEqual. Only then does it send HMAC-SHA256(secret, "agent-device-session-client|" + nonce_s + nonce_c), followed by the command line.
    4. The helper checks the client proof with MessageDigest.isEqual, then reads the command.

    The secret never crosses the socket.

  • No over-read: each handshake line is read with the existing frame reader, capped at 64 bytes. It takes at most 65 bytes, so the command that follows a legitimate client proof is never read before the check.

  • Failure: a bad, missing or malformed proof, or the deadline, closes the connection without a reply.

    • On the host, a server proof that fails, a close or error before the hello, or an oversized hello means the listener is not this helper. The host sends no command byte and emits android_snapshot_helper_session_peer_unverified. The capture path retires the session and returns one-shot. The touch path stops the session and returns undefined, so that call runs one-shot.
  • Deadlines: the handshake shares the accept-relative command read deadline. The helper's hello goes through the existing frame writer and its deadline.

  • UID check: kept as defense in depth. It costs a few lines, and it still closes non-adbd peers before the helper spends a nonce or an HMAC on them.

  • Versioned mode: compatible. A ready record without a well-formed 32-byte sessionSecret is malformed, so it is a failed start.

Production line counts for this round (excluding tests and fixtures, against 1a79bce):

  • SessionPeerPolicy.java +73
  • SnapshotInstrumentation.java +14/−1
  • snapshot-helper-session-protocol.ts +91/−10
  • snapshot-helper-session-lifecycle.ts +7/−2
  • snapshot-helper-session.ts +5/−2

Tests (each fails on 1a79bce)

  • JVM SessionHandshakeTest:

    • connectionWithoutTheClientProofNeverReadsTheCommand
    • wrongClientProofNeverReadsTheCommand: exactly two proof lines are consumed, and the command bytes are never read.
    • replayedClientProofFails: a proof for another server nonce.
    • serverProofBindsToTheClientNonce: checked against an independent HMAC.
    • malformedClientNonceGetsNoServerProof
    • provenPeerReachesTheCommand

    With the handshake removed (1a79bce behavior), all six fail. The red log is in .tmp/live-4729b/r7/red-java-no-handshake.log.

  • Host snapshot-helper-session-peer.test.ts:

    • "a listener that cannot prove the secret gets no command, and the capture runs one-shot". The listener receives only the 64-hex nonce line. The session is no longer live, and the typed diagnostic is logged. On 1a79bce, the listener received snapshot snapshot-….
    • "the session secret appears in no diagnostic and no error". It runs a verified session plus a refused listener, and asserts on the debug diagnostics file and on normalizeError JSON. On 1a79bce it times out, because 1a79bce cannot complete an authenticated exchange at all. The leak assertion itself has no 1a79bce counterpart.
  • Host snapshot-helper-session-touch-peer.test.ts: an input sent to a listener that answers a fake hello resolves undefined (one-shot). The session is stopped, and the listener saw only the nonce, never the typed text. On 1a79bce, the input was sent and failed with "wrong protocol".

  • Readiness: the secret is required, so a missing, short, uppercase or long secret makes the record malformed. The fake helpers now run the handshake, computed independently of the host.

Live evidence

Pixel_9_Pro_XL_API_37 was already running as emulator-5556, started headless by another process, and that serial is off limits. So I made a temporary AVD from the same image (android-37.0;google_apis_playstore_ps16k, pixel_9_pro_xl, Android 17), started it on emulator-5562, and deleted it afterwards. Before the run I did pnpm clean:daemon. The installed digest equalled the artifact: 2b87c160….

(a) Session start, then a reused snapshot:

snapshot-1 {"success":true,"backend":"android-helper","helperVersion":"0.21.40-dev","helperTransport":"persistent-session","helperSessionReused":false,"installReason":"missing"}
snapshot-2 {"success":true,"backend":"android-helper","helperTransport":"persistent-session","helperSessionReused":true}

(b) Forward bypass, through the host forward tcp:64602 → localabstract:agentdevice-snapshot-helper-64602:

+    4ms [bypass] sent "snapshot req-bypass"
+   13ms [bypass] peer FIN, received 0 bytes; head ""
+    1ms [forged] sent a valid nonce
+   15ms [forged] recv "1637f543…7ef0 7378dc61…9b79\n"
+   15ms [forged] sent a wrong client proof and a command
+   18ms [forged] peer FIN, total 130 bytes

From inside the guest, through 10.0.2.2:64602 (toybox nc): echo 'snapshot req-guest' | nc 10.0.2.2 64602 received 0 bytes. A guest that sent a valid nonce received only the hello line, and could go no further without the secret. This confirms the reviewer's path exists, and that the handshake closes it.

After the bypass attempts, the helper PID stayed 4667, and the next CLI snapshot reused the session. Logcat has no crash and no sessionSecret line. I closed the session, removed the forward, shut down the emulator, and deleted the AVD. Raw logs are in .tmp/live-4729b/r7/.

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

  • Forward bypass (emulator guest via 10.0.2.2): closed. Without the secret, a peer gets at most the server hello and cannot compute a client proof. Proven live.
  • Socket substitution: closed. The host sends nothing but the nonce until the listener proves the secret. Covered by host tests for both the capture path and the touch path.
  • The hello as an oracle: an unauthenticated peer can obtain HMAC(secret, server label ‖ its nonce ‖ server nonce). This cannot serve as a client proof, because the labels differ, every field has a fixed length, and the server nonce is fresh per connection. A recorded server proof does not verify for another client nonce, as serverProofBindsToTheClientNonce shows.
  • Secret exposure:
    • The secret travels only on the am instrument stdout to the host process. Instrumentation result parsing keeps only message fields, so the secret is not in exit results.
    • It is never in argv, files or logcat (checked live). It is not in diagnostics or errors (tested).
    • On the host it lives only on the in-memory session record, and it is dropped with the session.
    • Residual: anything that can read the host process's memory or the adb shell stdout is already inside the adb-operator trust boundary.
  • Unchanged: the UID check, frame caps, accept-relative read deadline and per-frame write deadline. The handshake uses the same deadline, so it does not add a way to hold the accept loop.
  • Residual, as before: the org.json input echo now needs an authenticated peer. The serial-keyed install memo remains a follow-up suggestion.

Validation

pnpm check:affected --run at 23ff71bc9f passed with exactCommit=true. The JVM suite runs in pnpm build:android and passed. I updated the Summary and Validation sections of the PR body. I recorded the decision on #4519.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@thymikee

Copy link
Copy Markdown
Member Author

Head 68adbe9b798a1d036fefb4f1f0847eca8fd774ab. This answers the Sentinel minor on the refused-peer cycle.

  • A touch command that meets a listener that cannot prove the secret now retires the session with retireFailedAndroidSnapshotHelperSession. That is the existing timed start backoff a failed capture earns; there is no new mechanism. Within the backoff, the next commands go straight to one-shot: no new session start, no new connection, no second stop. After the backoff, the next command tries a session again.
  • Test: "after a refused peer, touch commands run one-shot until the start backoff ends" (snapshot-helper-session-peer.test.ts). It fails on 23ff71b with 2 !== 1, because the old plain stop sent a graceful quit over a second connection.
  • pnpm check:affected --run at 68adbe9b79 passed with exactCommit=true. This change is host-only, so I ran no device check. I updated the Validation head in the PR body.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@thymikee

Copy link
Copy Markdown
Member Author

Head e15bc9db4849b671283cf161e80d0a8f34d0d2f5. This answers the Sentinel minor on how dead sockets are classified.

  • The handshake now has a typed phase instead of relying on a truthy buffer. Only a peer that answered and failed the proof is peer_unverified.
  • ECONNREFUSED, or a socket that closes before the peer's first byte, stays the ordinary transport failure with its original error. The session is stopped and the error disclosed as before, with no backoff.
  • Tests (snapshot-helper-session-touch-peer.test.ts): the refused connection and the close before the hello both reach the caller as a transport failure. They fail on 68adbe9. The wrong-proof case still reports peer_unverified.
  • pnpm check:affected --run at e15bc9db48 passed with exactCommit=true. This change is host-only, so I ran no device check. I updated the Validation head.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

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.

sendAndroidSnapshotHelperSessionCommand enforces the 129-byte hello limit only while no newline has arrived. When one chunk carries a newline past byte 129, the host decodes and splits the whole unauthenticated line, computes the expected HMAC before it checks the nonce, and ignores any tokens after the proof. The proof check still runs before any command byte is sent, so nothing is dispatched, but the pre-parse bound and the exact two-field format are not enforced. Please require the newline at exactly offset 129 before decoding, accept only 64 lowercase hex characters, one space and 64 lowercase hex characters, validate both fields before computing the HMAC, and keep the constant-time compare. A test with an oversized line and one with a third token should both refuse.

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, <server nonce> <server proof>.

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.
@thymikee

Copy link
Copy Markdown
Member Author

Head 8eaec9b1e7b311d2af49b12dc1618c2f1db8c709. This answers the e15bc9d review.

  • Hello bound: the host requires the newline at exactly byte 129. It accepts only ^[0-9a-f]{64} [0-9a-f]{64}$, checked before any HMAC is computed, and it keeps the constant-time compare. A longer line, a newline anywhere else, or a third field is refused as peer_unverified. Tests: "a hello longer than one nonce and one proof" and "a hello with a third field", both with an otherwise valid proof. Both fail on e15bc9d: it accepted those hellos and sent the command.
  • Pre-hello timeout: a request that times out before a proven hello carries dispatched: 'no'. The touch path keeps that disclosure, so a mutation falls back to one-shot. A timeout after a proven hello stays unknown. Test: "an input timeout before the hello / after a proven hello". The first case fails on e15bc9d ('unknown' !== 'no').
  • SessionFrameWriter: I added a comment. A send that finishes past the deadline is not checked again, because the kernel already holds the bytes it accepted. A recheck would change no outcome.
  • README: it now describes the hello as one line, <server nonce> <server proof>.
  • Validation: pnpm check:affected --run at 8eaec9b1e7 passed with exactCommit=true. The JVM suite passed in pnpm build:android. This change is host-only, so I ran no device check. I updated the Validation head.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks. At 8eaec9b the hello is accepted only as exactly <64 hex> <64 hex>\n with the newline at byte 129, both fields are validated before the HMAC, and a timeout before a proven hello is reported as not dispatched. The handshake, secret delivery and dispatch disclosure all hold. One last hardening step remains before the label.

The data handler still concatenates the whole incoming chunk into hello and runs indexOf over it before it refuses, and it keeps the bytes after the newline in chunks before the proof is checked. Nothing is parsed or dispatched, but the pre-verification buffer is bounded only by the socket's chunk size, not by the 129-byte window. Please take at most the bytes still missing through offset 129 from each chunk, refuse when that window has no newline at exactly 129, and keep any bytes after the newline out of chunks until the proof verifies (or refuse them, since an honest helper sends nothing before the client proof). A test that sends a valid hello followed by extra bytes in the same chunk, and one that sends 4 KiB with no newline, should both refuse without buffering more than 130 bytes.

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.
@thymikee

Copy link
Copy Markdown
Member Author

Head 249620200bf4854142b61c9c6209e37e4e651d88. This answers the 8eaec9b hardening request.

  • The host takes from each chunk at most the bytes still missing through offset 129, so it keeps 130 bytes at most. It refuses as peer_unverified when byte 129 is not the newline, or when the line has an early newline. It also refuses any byte that follows the hello before the client proof is sent: an honest helper sends nothing in that window. Those bytes never reach chunks.
  • The refusal reports receivedBytes in its typed details, so you can see how much of the unverified answer was kept. The test reads it from the error, with no export added for the test.
  • Tests in snapshot-helper-session-touch-peer.test.ts: a valid hello followed by extra bytes in the same chunk, and 4 KiB with no newline. Both refuse with receivedBytes <= 130, and the listener sees only the nonce. Both fail on 8eaec9b: the first accepted the hello and sent the command, and the second kept 4 KiB.
  • pnpm check:affected --run at 249620200b passed with exactCommit=true. This change is host-only, so I ran no device check. I updated the Validation head.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 2496202

Since the review of 8eaec9b: 0 new · 0 still open · 0 no longer raised

No open findings.

1 new finding away from what changed since 8eaec9b not shown. Comment @apex-sentinel-staging review for a full review.

Reviewed with this repository's own Sentinel configuration (0b9186494f80).

💬 Talking to Sentinel

In a finding's thread, reply with:

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.

@thymikee

Copy link
Copy Markdown
Member Author

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:

  • Peer admission runs before the only reader.
  • Each launch delivers a fresh secret through the instrumentation watcher, and both proofs are domain-separated and compared in constant time.
  • A forwarded emulator guest or a substituted listener never gets a command dispatched or sees command bytes.
  • Reads keep the absolute deadline with sliced polls and the frame cap before decode.

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 write and expects one data event, but TCP may deliver the 130-byte hello separately, which would correctly enter the proven phase and fail the test. Writing them in one Buffer with socket.cork()/uncork(), or asserting either outcome, would keep it stable.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 20, 2026
@thymikee
thymikee merged commit 854bba6 into main Nov 20, 2026
18 checks passed
@thymikee
thymikee deleted the t3/android-helper-auth-main branch November 20, 2026 07:35
thymikee added a commit to pcbeingused333/agent-device that referenced this pull request Nov 20, 2026
* 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)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant