rouse-context/work
monkopedia-coder 96aeeeb872
Cap HTTP framing buffers and make refresh-token rotation atomic (F-Droid audit) (#750)
* fix(bridge): cap HTTP framing so one stream cannot OOM the service

HttpHeaderInjector buffered a request's whole header block with no cap on
total bytes, per-line length or line count, and emitted nothing downstream
until the \r\n\r\n terminator arrived. A peer that never sends the terminator
therefore grows headerBuf without bound while the local Ktor server -- which
has its own limits -- receives zero bytes and so can never fire them.
Measured on the unfixed tree: 16 793 629 bytes buffered, 0 forwarded.
chunkSizeBuf had the same shape.

Reachability is what makes this a blocker. The injector runs on the first
plaintext byte after the TLS handshake, ahead of HTTP parsing, ahead of the
X-Internal-Token guard and ahead of OAuth, and the device does not request
client auth, so the integration secret from the MCP URL is the whole
prerequisite. Up to 32 streams share the process, and the resulting
OutOfMemoryError is an Error, so it walked past every `catch (Exception)` on
the path and took the foreground service down rather than one session.

Caps are matched to ktor-http-cio 3.4.2 so that nothing this layer accepts on
size is something Ktor would then reject on size: 8192 bytes per header line
(HTTP_LINE_LIMIT) and 128 bytes per chunk-size line (MAX_CHUNK_SIZE_LENGTH).
The 64 KiB header-block cap undercuts rather than matches, because Ktor CIO
has no block-level cap at all and a per-line limit bounds nothing against a
peer sending limitless well-formed lines.

Exceeding a cap enters a terminal failed state, releases both buffers and
throws. Deliberately NOT a fall-through to PASSTHROUGH, the injector's
existing escape hatch for malformed framing: passthrough would forward the
request without the internal token, which fails closed at the Ktor guard only
after the bytes have already been consumed and copied.

HttpFramingLimitExceededException is an IOException so classifyTunnelFailure
files it as PeerOrTransport -- INFO, rate visible, no non-fatal. A remotely
triggerable crash report would be a spam channel.

Separately, and regardless of the caps: collectIncomingSessions now catches
Throwable rather than Exception, so an Error raised while serving one session
costs one session instead of the service. An explicit CancellationException
clause is stated first so cancellation still propagates -- reportTunnelFailure
rethrew it anyway, but relying on that left the site reading as a swallow to
both the #674 gate and to anyone else. That retires its backlog row.

Found by @andrewpozdnakov7 reviewing 1.0.10 for F-Droid (fdroiddata!42096).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

* fix(token): rotate refresh tokens with a compare-and-swap

RoomTokenStore.refreshToken was read -> check -> write with no transaction, no
CAS and no lock, over an unconditional `UPDATE tokens SET rotatedAt WHERE id`.
Two concurrent redemptions of one refresh token both read `rotatedAt IS NULL`,
both wrote, and both minted a descendant. Both then looked legitimate, so the
family was never revoked, OAuth 2.1 §4.14 reuse detection never fired, and a
stolen refresh token survived indefinitely. Measured on the unfixed tree: 199
of 200 unassisted rounds minted two descendants.

InMemoryTokenStore already does this correctly -- consumeRefreshToken calls
itself "Atomically validates and consumes" and holds a synchronized block. The
Room implementation, the one that ships, did not get that treatment.

markRotatedIfUnrotated adds `AND rotatedAt IS NULL` and returns the affected
row count, so the predicate and the write cannot be separated; a child is
minted only on 1. A single SQLite UPDATE is atomic, so no surrounding
transaction is needed. A 0 return collapses "replayed minutes later" and
"raced us just now" into one answer: revoke the family, mint nothing. The
expiry check is now guarded on `rotatedAt == null`, because an already-rotated
token presented again is reuse whatever the clock says and must reach the CAS
rather than return early.

BEHAVIOUR CHANGE, flagged for the owner and deliberately not softened here: a
well-behaved client that fires two refreshes concurrently -- 401 storms do
this -- goes from "both succeed" to "one succeeds, family revoked, user
re-authenticates". The spec-clean alternative is a short grace window in which
the immediately-preceding token returns the child already minted for it. That
is a product decision, so it is written down rather than taken.

Both tests assert exactly one descendant, not at most one: "at most" is
satisfied by a store that rejects every refresh, and the lower bound is what
keeps an ordinary single refresh working.

Found by @andrewpozdnakov7 reviewing 1.0.10 for F-Droid (fdroiddata!42096).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

---------

Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 14:42:16 -04:00
..
src Cap HTTP framing buffers and make refresh-token rotation atomic (F-Droid audit) (#750) 2026-09-14 14:42:16 -04:00
build.gradle.kts Enable core library desugaring for :work (#699) (#706) 2026-09-03 03:32:38 -04:00