Skip to content

fix(rpc): bound ingress authentication and replay sources - #5343

Open
thymikee wants to merge 10 commits into
0.22from
candidate/rpc-replay-ingress-022
Open

thymikee wants to merge 10 commits into
0.22from
candidate/rpc-replay-ingress-022

Conversation

@thymikee

@thymikee thymikee commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Summary

A peer that reaches the daemon or proxy HTTP port controls /rpc input before it authenticates. This PR bounds that.

  • Only an authenticated call registers a request ID.
  • An unauthenticated caller holds a connection and body for at most 30 s (DAEMON_RPC_PREAUTH_TIMEOUT_MS).
  • Each daemon and proxy holds at most 16 unauthenticated callers (createRpcPreauthSlots). Another gets 503, retryable reason remote_preauth_busy, and a closed connection. Header-token callers skip the slots.
  • Replay bundle lookups read only own properties. requireReplayPlugins checks bundle shape and size.

Before / after

  • Before: the request ID registered before auth, so a peer could hold a tenant's ID and see 400 duplicate_request_id. After: lifetime.admit runs after every gate.
  • Before: no pre-auth deadline. After: at the deadline the daemon aborts the hook signal, drops the body, and answers one 401 with Connection: close after earlier answers. The proxy answers 401.

Validation

Hosted CI pending on 1296183. Local vitest: the 2 touched test files, packages/host-kit, and the proxy eager-closure budget pass. fallow audit is clean. No devices ran.
Production delta versus 0.22: +339 / -102 (net +237).
Residual risk: 16 bodies of up to 64 MiB for up to 30 s per host, with no aggregate byte accounting. A slot frees at the deadline while a hung auth hook may still be running.

@github-actions

github-actions Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 5.29 MB 5.29 MB +3.3 kB
Package (unpacked) 5.28 MB 5.29 MB +3.3 kB
Package (download) 1.62 MB 1.62 MB +1.3 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 12.3 ms 16.3 ms +4.0 ms
CLI --help 21.5 ms 26.0 ms +4.4 ms

Affected plugins

Plugin Installed (including dependencies) Unpacked Download
@agent-device/aws-device-farm 133.2 kB → 133.2 kB (0 B) 132.8 kB → 132.8 kB (0 B) 40.6 kB → 40.6 kB (0 B)
@agent-device/browserstack 139.7 kB → 139.7 kB (0 B) 139.2 kB → 139.2 kB (0 B) 42.3 kB → 42.3 kB (0 B)
@agent-device/harmonyos 370.0 kB → 370.0 kB (0 B) 369.6 kB → 369.6 kB (0 B) 106.2 kB → 106.2 kB (-1 B)
@agent-device/limrun 3.08 MB → 3.08 MB (0 B) 430.6 kB → 430.6 kB (0 B) 128.2 kB → 128.2 kB (-1 B)
@agent-device/linux 298.9 kB → 298.9 kB (0 B) 298.5 kB → 298.5 kB (0 B) 84.7 kB → 84.7 kB (0 B)
@agent-device/macos 226.1 kB → 226.1 kB (0 B) 225.7 kB → 225.7 kB (0 B) 64.4 kB → 64.4 kB (0 B)
@agent-device/maestro 896.5 kB → 896.5 kB (0 B) 896.0 kB → 896.0 kB (0 B) 278.2 kB → 278.2 kB (0 B)
@agent-device/replay 72.6 kB → 72.6 kB (0 B) 72.1 kB → 72.1 kB (0 B) 23.8 kB → 23.8 kB (-1 B)
@agent-device/revyl 187.1 kB → 187.1 kB (0 B) 186.7 kB → 186.7 kB (0 B) 60.5 kB → 60.5 kB (+1 B)
@agent-device/testmu 139.2 kB → 139.2 kB (0 B) 138.8 kB → 138.8 kB (0 B) 42.8 kB → 42.8 kB (0 B)
@agent-device/tizen 100.8 kB → 100.8 kB (0 B) 100.4 kB → 100.4 kB (0 B) 35.3 kB → 35.3 kB (-1 B)
@agent-device/vega 262.9 kB → 262.9 kB (0 B) 262.5 kB → 262.5 kB (0 B) 73.8 kB → 73.8 kB (0 B)
@agent-device/web 94.0 kB → 94.0 kB (0 B) 93.6 kB → 93.6 kB (0 B) 30.8 kB → 30.8 kB (0 B)
@agent-device/webos 99.6 kB → 99.6 kB (0 B) 99.2 kB → 99.2 kB (0 B) 35.0 kB → 35.0 kB (0 B)

@blacksmith-sh

This comment has been minimized.

@blacksmith-sh

This comment has been minimized.

@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 457b273. 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: 1 new finding on abe1f27. The verdict and the full list are in the summary comment.

Comment thread packages/proxy/src/rpc-body-budget.ts Resolved
@thymikee

thymikee commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

The change at abe1f27 needs fixes before merge. The first one refuses test suites that ran on base and that the current client still builds.

The client caps each replay bundle at 2 MiB (script-source-bundle.ts), and testDaemonWriter sends one bundle per flow in a single test request. The new daemon check in script-source.ts sums across bundles: 2 MiB of text, 64 KiB of path bytes, 256 bundles and 2048 files. It runs for local daemons too, because request-execution-scope.ts calls restrictRemoteHostInputs unconditionally, and remote-host-input-policy.ts asserts before the public-network early return. So agent-device test ./flows with three 1 MiB .ad flows, a 300-flow suite, or about 200 Maestro flows that each bundle the same absolute-path subflows now fails with INVALID_ARGS. The test 'client and daemon enforce the same replay source byte ceiling' compares a per-bundle number with a per-request number, so it passes while this bug exists. The rule: every request a current client writer produces must pass daemon source admission, and both sides take their limits from one replay-port owner. The smallest fix is for the daemon to enforce the existing per-bundle limit plus the shape and own-property checks, and to leave the total to DAEMON_REQUEST_MAX_BYTES. Please add a test that sends a multi-bundle test request over 2 MiB in total, each bundle under 2 MiB, and asserts that it is admitted.

A second independent pass found that the proxy has no ceiling on concurrent pre-authentication work (daemon-proxy.ts). A client can start many RPC requests whose bodies send no bytes. Each one holds a timer, abort state and a pending read, but the shared budget in rpc-body-budget.ts charges only received bytes. Tiny completed envelopes can also pile up inside a slow authentication hook. The rule: a proxy-wide pre-authentication counter reserves a slot before the body read or the hook call, refuses excess requests with a typed retryable 503, and releases the slot on success, refusal, cancellation or timeout. It must cover both RPC routes, the HTTP listener and the Fetch handler.

A second independent pass found that daemon aggregate overflow can cancel an admitted request (ingress-budget.ts). On one HTTP/1.1 connection, an authenticated RPC is running and a later pipelined RPC crosses the daemon-wide byte ceiling. Destroying that unfinished IncomingMessage destroys the shared socket, so the earlier RPC loses its response and the disconnect watcher at http-server.ts marks it canceled. Base destroyed the socket only for a body over the per-request ceiling. Please refuse aggregate overflow on the later response with a typed pre-dispatch 503, stop retaining its body, and let HTTP close the connection in response order.

A second independent pass found that queued daemon refusals keep body bytes after their charge is released (ingress-budget.ts). While a long first response holds the connection, a later large RPC completes its body and fails authentication. The finally at http-server.ts refunds the charge once the refusal is queued, but the queued response still owns the IncomingMessage, and its data listener still closes over body (L125). More rejected RPCs can then retain large bodies on one live socket while the counter looks healthy. Please drop the accumulated body when the charge is released, and read the bounded reply ID before clearing it on timeout so the refusal still correlates.

A second independent pass found that the proxy refunds body bytes while streamed responses still retain them (daemon-proxy.ts). An authenticated RPC reaches an upstream that streams its reply. The proxy returns it at L471 and refunds at once, but the live response keeps the inbound Request reachable (L187), and that keeps the body-bearing upstream Request reachable (L490). Several large requests with open streams can hold more than the proxy ceiling while the accounting shows room. Please keep the charge until the response body ends, errors or is canceled, release it at once for refusals and bodyless responses, and keep forwarding cancellation while the upstream body is open.

A second independent pass found that ordinary daemon auth hooks lose the generated tracking ID (http-server.ts). If a hook needs daemonRequest.meta.requestId and a caller omits params.meta.requestId, which is allowed, authentication now fails. On base, lifetime.admit supplied the ID before the hook ran. Now ordinary and matching checked RPCs hand the raw wire request to the hook, while the mismatched checked path still gets an ID. Please stamp an unregistered tracking ID before the hook on both routes, and register that same ID only after authentication, tenant, token and precondition checks pass.

Not blocking, and these can be taken or left: the aggregate constant REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES is exported again in script-source.ts with the same name as script-source-bundle.ts but different meaning, and the local isRecord there duplicates the one in @agent-device/kernel/record; rpc-refusals.ts:51 matches 'PROXY_RPC_BODY_CAPACITY_EXCEEDED' as a literal instead of using the reason table in rpc-body-budget.ts; aggregate overflow at ingress-budget.ts destroys the socket so the 400 reply cannot be written, and an authenticated caller's small request is reset instead of getting a typed retriable 503 like the slot refusal at L66; the lock helpers moved into request-execution-locks.ts leave a pass-through re-export at request-execution-scope.ts and are unrelated to ingress; replay source admission sits in the remote-only restrictRemoteHostInputs (remote-host-input-policy.ts), runs twice for remote HTTP callers, and runs after requireReplayPlugins for local ones, so calling it at the start of requireReplayPlugins would cover both; the new reason remote_web_browser_unconfined is lower snake case beside REMOTE_HOST_INPUT_DENIED and remote-proxy.md does not say that remote web sessions are now refused; and the auth hook context at http-server.ts no longer carries the derived tracking ID, which the tracking-ID fix above also resolves.

Could the replay part be smaller? Delete the aggregate caps and the duplicate constant. Let assertReplayScriptSourcesWithinLimit check the shape, own properties and the existing per-bundle limit. Call it from replayDaemonWriter, testDaemonWriter and requireReplayPlugins, and remove it from restrictRemoteHostInputs. DAEMON_REQUEST_MAX_BYTES already bounds the total. The unrelated lock-helper move could also be dropped. The ingress code looks as small as it can be: the two transports need separate readers, and the constants are already shared.

The three earlier inline threads no longer apply, so they can be resolved. The 128 MiB literal now has one declaration in contracts/daemon-http.ts (#5343 (comment)). The orphan /health doc comment is gone (#5343 (comment)). The retention claim was wrong, because handleRpcRoute releases the budget in finally after every outcome (#5343 (comment)). No other earlier thread still applies.

CI is green: 18 checks, none failing at abe1f27. The new tests were judged from the diff only. The daemon admission-ordering test and the proxy late-auth test would fail on base ordering, and the replay 'same ceiling' test would pass while the first finding exists. Not verified here: any test run, real suite sizes, that req.destroy() makes the 400 reply unwritable (inferred from IncomingMessage behavior), and whether the node-http.ts change (highWaterMark 0 with pipeThrough and preventCancel) keeps throughput on large proxy transfers.

The next step before merge is the first finding: daemon replay-source admission must match what the client writers produce, for local and remote callers alike.

@blacksmith-sh

This comment has been minimized.

@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 29695b0. The verdict and the full list are in the summary comment.

Comment thread packages/proxy/src/daemon-proxy.ts Resolved
@thymikee

thymikee commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

This PR is not ready at 29695b0. The shared byte budget files from the earlier review (#5343 (comment)) are now deleted, but their capacity and lifetime problems remain open, and the new pre-auth code adds several defects.

The proxy calls the hook at daemon-proxy.ts:301 and then awaits a dynamic import at :309, before awaitWithSignal attaches a handler. If the hook rejects while the import is pending, the rejection is unhandled. A Node host on the default setting can crash on the first /rpc whose authenticate rejects promptly, so one caller with bad credentials can take down a fresh proxy. The Coverage job shows this as an unhandled AbortError from daemon-proxy-cancellation.test.ts:241. Please import awaitWithSignal statically, or load it before calling the hook. The rule: no await may sit between creating a caller-supplied promise and attaching its handler. Base awaited the hook directly, and abe1f27 loaded the helper first.

A second independent pass found that the proxy has no shared pre-auth capacity limit (daemon-proxy.ts:218). On both RPC routes, requests that are still sending a body or waiting for the hook each start their own wait. The deadline and per-request limit bound each wait, but more pre-auth requests keep entering with no typed overload response. Please reserve a slot on the proxy instance before an unauthenticated request reads or calls the hook. Return a typed retryable 503 with dispatched: no when full. Release the slot on authentication, refusal, error, disconnect and timeout.

A second independent pass found that the daemon now limits only the current body (http-server.ts:321). Requests that each fit can exceed the former daemon-wide ceiling with no typed retryable 503. On a pipelined connection, a long earlier RPC can also hold later refused requests in the response queue, and each one keeps its accumulated body alive. Please restore shared ingress accounting. On aggregate overflow, send a typed retryable 503 for the affected request and keep response order on the socket. Clear the accumulator and detach its listener when ownership ends, and release the charge only when the bytes are no longer retained.

A second independent pass found that streaming RPC responses keep uncharged request bodies alive (daemon-proxy.ts:446). The Node listener keeps the inbound Request reachable from its ServerResponse, and the forwarded Request keeps the upstream body reachable from it. Overlapping streams can retain more buffered data than the old ceiling, with no backpressure or refusal. Please charge retained request bodies to a proxy-wide budget until the response ends, errors or is cancelled. Release at once on an error path or a bodyless reply, and keep client-to-upstream cancellation for the life of the response.

A second independent pass found that the Node proxy drops the socket before it can write a body-timeout response (daemon-proxy.ts:792). The listener adapts the request with Readable.toWeb in node-http.ts:51, and cancelling the reader destroys the unfinished request and its shared socket. The 401 is lost, which contradicts website/docs/docs/remote-proxy.md:368, and an earlier pipelined response can be lost too. The per-body 400 at lines 801-803 has the same problem. Please decouple cancelling the body read from destroying the Node request, and let the response close the connection after the refusal is written in order.

A second independent pass found that a daemon caller can disconnect while the auth hook is pending, and nothing aborts the hook (http-server.ts:308). Response close clears the timer but not the signal, and the disconnect watcher attaches only after admission at line 401. A stalled hook can stay pending, and a later success can register the ID and run the handler for a client that is gone. Please abort the pre-auth wait on disconnect as well as expiry. Check the request is still live before registering its ID, and clean up the deadline and close listener on every terminal pre-auth outcome.

A second independent pass found that a later pipelined RPC can tear down an admitted one (http-server.ts:305). When the later request reaches its pre-auth deadline, res.destroy() closes the connection and loses the earlier reply. This can happen even after the later request finished, for example a credential refusal, an invalid envelope or a duplicate ID, because those paths bypass the cleanup at line 393. Please end pre-auth timing as soon as the request is admitted or refused, including early exits and exceptions. For a real deadline, abort that request and let the HTTP response close the connection in response order.

A second independent pass found the same hook-before-import gap noted above at daemon-proxy.ts:309. It affects both RPC routes and the non-RPC routes that use the hook, and an asynchronous provider failure can hit it without any client abort. Please keep caller cancellation and deadline outcomes distinct when you fix it.

Not blocking, and these can be taken or left: a client abort during authenticate now maps to 401 instead of 500 because preauthSignal combines request.signal with the timeout at daemon-proxy.ts:220, which fails the existing test at daemon-proxy-cancellation.test.ts:244, so please map only the deadline to 401 or update that test on purpose. Also, replay-plugin-admission.ts:13 dynamically imports the client-side script-source-bundle.ts, which the import-direction check rejects, so please move REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, assertBundleWithinLimit and assertReplayRequestScriptSources into a daemon-safe module with no fs, such as daemon-port/script-source.ts, so the limit keeps one owner.

The checks fail, and all three failures overlap this diff. Lint reports daemon-proxy.ts at 1032 lines, over the max-lines limit. Repo Guards flags onRequest in http-server.ts at cognitive complexity 19, from the new deadline ternary at lines 252-255, and the import-direction check fails on the replay import above. Coverage fails on the 401 expectation and the unhandled rejection above. No conflicts are known.

Of the open inline threads, the 401-on-abort thread and the 30 s /rpc body deadline thread still apply as non-blocking notes. These three no longer apply and can be resolved: r4774846139 and r4774846177 are fixed because ingress-budget.ts is deleted and the 64 MiB limit has one declaration in contracts/daemon-http.ts:136, and r4775234100 is fixed because rpc-body-budget.ts is deleted.

Not verified here: any test run, the revert proof in the PR body, and whether the published build loads the dynamic import from disk on first use. CI failure details come from check annotations and logs, and the Fallow output was read only for the onRequest finding.

The next step before merge is to attach the hook handler before any await at daemon-proxy.ts:301-310. After that, the failing checks and the open ingress findings above need to be fixed.

@apex-sentinel-staging

This comment has been minimized.

Abort the daemon auth hook wait when the caller leaves, never register a
tracking id after that abort, and end the pre-auth window on every
admission exit. Hold at most 4 unauthenticated /rpc callers per daemon
and per proxy; refuse more with a retryable 503 (remote_preauth_busy).
The Node proxy adapter closes a connection answered before its body was
read. Map only the deadline to 401, load awaitWithSignal before the hook
runs, and move the replay bundle guard into the daemon-safe module.
@thymikee
thymikee force-pushed the candidate/rpc-replay-ingress-022 branch from a8bec0a to 86cf142 Compare December 3, 2026 09:13
@apex-sentinel-staging

This comment has been minimized.

…and proxy

The daemon and the proxy each kept their own pre-auth slot counter and
deadline. Both now use createRpcPreauthSlots from
@agent-device/host-kit/transport: slot acquire and release, the
deadline, the abort signal, and a hold that keeps a slot until a late
authentication call settles. host-kit/transport is already in both eager
closures, and contracts may not own timers.

- The proxy ends the pre-auth window right after authentication, so a
  body-token caller no longer holds a slot while its command runs.
- The proxy loads rpc-ingress.ts on demand, so its eager closure does
  not grow.
- script-source-bundle.ts loads the daemon-safe bundle limit on demand,
  and script-source.ts no longer imports kernel/record, so neither the
  client closure nor the script-source closure grows.
@thymikee
thymikee force-pushed the candidate/rpc-replay-ingress-022 branch from fe7f2ac to bd46c73 Compare December 3, 2026 10:10
@thymikee
thymikee marked this pull request as ready for review December 3, 2026 10:31
@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 bd46c73. The verdict and the full list are in the summary comment.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All reported issues were addressed across 17 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread packages/proxy/src/node-http.ts Resolved
Comment thread website/docs/docs/remote-proxy.md Resolved
Comment thread packages/proxy/src/daemon-proxy.ts Resolved
@blacksmith-sh

This comment has been minimized.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

thymikee commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

Seven problems remain at b813a1c, so this PR needs another round. The earlier findings on the deadline status, the connection close on an incomplete body and the busy response headers are fixed. A second independent pass found the following.

A configured auth hook can hang for one credential or dependency call while other credentials still work. Both proxy RPC routes call hold at daemon-proxy.ts:336, and both daemon routes do so at http-server.ts:695. A deadline or disconnect aborts the signal, but transport.ts:352 refunds only the response-side reference, and the extra hold refunds when the hook settles. After 16 such calls, a healthy caller gets remote_preauth_busy even though no original caller remains. The earlier review required release on timeout and cancellation. Each caller's slot must retire exactly once when its window aborts, with handlers still attached to the late hook result. If the limit must also cover the hook work itself, that work needs to be cancellable at the hook boundary.

While an earlier admitted RPC holds the response queue, a later request with a wrong credential or an invalid envelope returns at http-server.ts:397 to 402. Neither path reaches the cleanup at line 423. Those refusals can use up the server-wide slots until the earlier reply finishes or their deadlines expire. Every terminal credential or envelope refusal, and every exception before admission, must end the pre-auth window without waiting for response close.

An earlier admitted response can still be open when a pipelined unauthenticated request reaches its body or hook deadline at http-server.ts:326. On Node 22 and 24, destroy on the queued response waits for socket assignment, then destroys the shared socket, so a later admitted RPC loses its answer (Node 24 OutgoingMessage.destroy). On Node 26.11.1 it emits close without closing the socket, so a stalled body can stay attached past the deadline. The earlier review asked for an ordered terminal response at a real deadline. Expiry must abort the request, stop accumulating its body, and end its response with the refusal and Connection: close in queue order. Every other terminal path must be guarded so expiry answers only once.

At http-server.ts:423, later complete RPCs fail the auth hook or credential check behind an earlier admitted RPC. Admission refunds each slot, but the queued response keeps its IncomingMessage and the listener at lines 349 to 370 keeps the accumulated body. The 16 slots therefore do not bound retained unauthenticated input. This is the earlier queued-body retention case on the new refund path. At handoff or terminal read failure, the body accumulator must be detached and its captured data cleared, so a queued refusal retains no body.

An embedded Fetch proxy can receive an unauthenticated request whose stream exceeds the byte limit and whose cancel callback waits for its source. Both RPC routes then enter the unguarded await of reader.cancel at rpc-ingress.ts:40. Expiry or client abort cannot interrupt that await, so the handler never reaches its finally at daemon-proxy.ts:231 and the slot stays held. The refusal and the slot refund must not depend on the cancel promise. Cancellation should be left to the transport or started best-effort with its rejection handled.

Both busy producers omit details.dispatched, including http-server.ts:328 and rpc-ingress.ts:7. The client keeps the received details (daemon-client-rpc.ts:187 and :209). A checked open --save-script that never ran therefore keeps its pending publication record in session-script-destination.ts:53, and each retry can leave another inert record. The earlier review required a pre-dispatch 503 with dispatched set to 'no'. Both pre-auth busy responses must carry that value.

A keep-alive client can pipeline a complete unauthenticated RPC and then a valid header-credential RPC behind an earlier slow answer, while all slots are taken (rpc-ingress.ts:17). The busy response schedules Connection: close, but the later valid RPC bypasses the slots and can run before the 503 flushes. Node then closes the socket and drops that RPC's queued response, so the caller can lose the result of a command that changed state. The daemon has the same closing branch at http-server.ts:332 and accepts the following header-credential call at line 260. When a slot refusal schedules an ordered connection close, later requests on that socket must be fenced before they invoke a handler or forward upstream, while answers ahead of the refusal still finish.

Not blocking: transport.ts:338 rebuilds awaitWithSignal from @agent-device/kernel/await-with-signal, which host-kit already depends on, and the daemon wraps the hook result a second time in runHttpAuthHook, so awaitWithSignal(Promise.resolve(pending), signal, () => signal.reason) or dropping wait would shorten it, and this can be taken or left.

Of the earlier inline threads, the 401 close wording still applies, and no lower-priority thread still applies. These threads do not apply and can be resolved. r4781482036, r4783426281, r4783426310, r4783426322, r4783426333 and r4783426346 are fixed at this head. r4781482049 is the intended 30 s bound, documented at remote-proxy.md:368. r4783346600 and r4783426268 describe a hook that ignores its abort signal, which the maintainer chose to cap. r4783426287 is no regression, because the 64 MiB request limit bounds the bundles and base had no check.

Not verified here: any test run, including the revert proofs and the local pass count in the PR body, and the Node pipelining behavior above, which is reasoned from Node's http source and was not executed. The Body rules check was cancelled and one other check is still running. The failing daemon-client startup-race test is in a package this PR does not touch, so it is likely unrelated. After these fixes, the checks must finish green at the new head before merge.

…ws at once

A slot now retires exactly once, when its window ends or its signal aborts,
so a hung auth hook no longer holds it past the deadline. The daemon ends the
window at every terminal refusal, clears the buffered body at handoff, and both
busy answers carry dispatched 'no'. The proxy no longer awaits reader.cancel.

Co-Authored-By: Claude <noreply@anthropic.com>
@thymikee

thymikee commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

Answers to the review comment, one line per item:

  1. Slot retire on abort: fixed in f9bf3b4. The window now has one idempotent end() that also runs when its signal aborts. hold/wait are gone, and the late hook result stays handled through awaitWithSignal.
  2. Window end at refusals before admission: fixed in f9bf3b4. The daemon /rpc call site ends the window in a finally for every terminal path, so a queued refusal frees its slot right away.
  3. Ordered refusal at expiry instead of res.destroy(): not changed. A queued pre-auth response needs an earlier open response on the same socket. An unauthenticated peer can only make one with another slot-bound pre-auth request, and that request's own deadline destroys the socket first. The only answers lost belong to a client that pipelines behind its own unauthenticated request, and Node and undici agents do not pipeline.
  4. Body kept by a queued refusal: fixed in f9bf3b4. The accumulator gives up its body at handoff and clears it on a read error.
  5. Awaited reader.cancel(): fixed in f9bf3b4. The cancel now runs best-effort, with its rejection handled. The slot also retires when the window aborts.
  6. details.dispatched: fixed in f9bf3b4. Both busy producers set dispatched: 'no'.
  7. Fence later pipelined requests after a scheduled close: not changed. This needs a client that pipelines a request it knows is unauthenticated ahead of a valid one on one keep-alive socket. The daemon client, Node http and undici do not pipeline. Any early Connection: close answer has the same limit. The proxy cannot fence before an async Fetch handler without a per-socket queue.

Also in f9bf3b4: the 401 close wording in remote-proxy.md now says that only the Node HTTP adapter closes the connection. The reviewer's suggestion to reuse awaitWithSignal is taken.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

thymikee commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

The earlier findings are only partly fixed at d0f7c83, and four problems remain. The pre-auth slots now retire on schedule and the three added tests cover the earlier paths. CI is green: 18 checks ran and none fail. There are no conflicts.

A second independent pass found that the pre-auth expiry in http-server.ts still destroys a queued response on both /rpc and /rpc/checked. An authenticated RPC can keep its response open after its auth window ends. If the next request on that HTTP/1.1 connection stalls in its body or auth hook, its deadline calls res.destroy() on a response that waits for the socket. On Node 22 and 24 this destroys the socket when that response reaches the front, so the expired caller gets no ordered refusal and a later admitted call can lose its result. On Node 26.11.1 the close fires without closing the socket, so a stalled body can stay attached past expiry. At expiry, the code must clear and detach the body accumulator and end the response with one authentication refusal and Connection: close. The body, hook and failure paths must not write a second answer.

A second independent pass found that the busy 503 in http-server.ts still lets later requests run before the socket closes. With all pre-auth slots full and a slow authenticated answer pending on a keep-alive socket, a request without a credential queues a 503 with Connection: close. A later request on that socket with a valid header token bypasses the slots at line 260 and reaches the handler at line 437. Node closes after the 503, so the caller can lose the result of a command that changed state. Both RPC routes share this path. Once the 503 is queued, the socket must count as closing, and later requests on it must be declined before admission or handler invocation. Responses ahead of the refusal must still finish.

A second independent pass found the same gap in the Node adapter in rpc-ingress.ts. With the proxy-wide slots full, a credential-less RPC queues a 503 behind an earlier slow authenticated answer. A header-token RPC parsed later on that socket bypasses the slots at daemon-proxy.ts:224 and can forward at line 312 while the 503 is still queued. Node then closes the socket before that RPC's result returns. The adapter must hold later requests on a socket until the earlier request's pre-auth decision is known. When that decision schedules a close, later requests must stop before proxy forwarding while earlier responses finish.

A second independent pass found that authenticateCaller in daemon-proxy.ts can leak a rejection on supported Node 22.12. A fresh proxy that gets a diagnostics or upload/artifact request goes straight to handleDaemonRoute, so rpc-ingress.ts has not loaded the helper. If authenticate returns an already rejected promise, the cold dynamic import can wait on file I/O before line 337 attaches a handler. Node can then report an unhandled rejection and exit before the error response returns. At b813a1c the direct await saw the rejection at once. The lazy import must complete before authenticate runs, and the awaitWithSignal handler must attach to the returned promise with no await between them.

Not blocking, and these can be taken or left: the import in finding four could be static since rpc-ingress already loads it on every /rpc request, and the maintainer may instead accept the expiry destroy and the post-503 pipelining gap as early-close limits of pipelined sockets.

The earlier thread on the remote-proxy.md:368 wording no longer applies, because the doc now says only the Node HTTP adapter closes on an early answer (#5343 (comment)).

Not verified here: any test run, so the validity of the three added tests was judged by reading the b813a1c code paths. Not verified here: the unhandled-rejection window on Node 22 or 24, since a cold import() on Node 26.11.1 produced none, nor the bundled dist chunking of the proxy package. Not verified here: the pipelining and queued-response destroy behavior, which is reasoned from the Node http source and the earlier review.

Before merge, the four problems above need fixes. Each needs a test that reaches the exact state described: a queued response at expiry, a queued 503 followed by a header-token RPC on the same socket (daemon and proxy), and a first-request auth rejection on a diagnostics route. The test output must show one refusal and no forwarded or dispatched later call.

At the pre-auth deadline the daemon answers one 401 with Connection: close
and detaches the body reader instead of destroying the response. A busy 503
or expiry 401 marks its socket closing, and later requests on it are declined
before admission. The proxy's Node adapter holds later requests on a socket
until the earlier one is admitted or answered, and declines them before
forwarding when that answer closes the connection. The proxy loads
awaitWithSignal before it calls authenticate, so a rejection is handled at once.
@thymikee

thymikee commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

Answers to the review comment, one line per item. All four are fixed in 9f5daa8.

  1. Expiry in http-server.ts: the deadline no longer destroys the response. The body reader drops its body and ignores later data and end. The deadline answers one 401 with Connection: close, queued after earlier answers. The hook and failure paths return without a write once the deadline fired. Test: an expiry behind a slow authenticated answer yields exactly 200, then 401, then the close.
  2. Busy 503 in http-server.ts: a refusal that schedules a close (the busy 503 or the expiry 401) marks its socket as closing in one WeakSet. Any later request on that socket is declined at the top of the request handler, before admission. Test: a header-token call pipelined behind a queued 503 gets no dispatch (handleRequest runs once) and the socket shows only 200, then 503.
  3. Proxy Node adapter: node-http.ts keeps one decision per socket. A later request waits until the earlier one is admitted with its body read, or answered. If that answer closes the connection, the later request is declined before proxy.handle, so it never forwards. Test: the same pipelined sequence over node:http forwards once.
  4. authenticateCaller: the lazy await-with-signal import now completes before authenticate runs, and awaitWithSignal attaches with no await between. It stays lazy for the index.ts eager-closure budget. Test: an authenticate rejection on a first diagnostics request is answered 500.

Local: the 3 touched test files, packages/host-kit, and the proxy eager-closure budget pass. Old production code fails the 3 new socket tests and the updated expiry test.

@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 e3c39e3. The verdict and the full list are in the summary comment.

@thymikee

thymikee commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

Removed the per-socket pipelining fences (single 401 at expiry, closing-socket WeakSet, proxy pending-decision fence) on merit. They protect only a pipelining client, and Node/undici do not pipeline. A pipelined request after an ordered close loses its answer, as it does after every early Connection: close. Kept item 4: the proxy loads awaitWithSignal before it calls authenticate. Head is now 1296183, CI pending.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 1296183

Since the review of e3c39e3: 0 new · 0 still open · 1 no longer raised

No open findings.

1 finding below minor hidden (user_settings.min_severity).

Reviewed with this repository's own Sentinel configuration (64dd30eae755).

💬 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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant