Repository navigation
Stream localhost proxy responses - #18541
Conversation
RStudio E2E - all platformsAll tests passed!
View / download the full reportView report online -- opens in the browser, no download needed. Available for 14 days. Download playwright-report.zip -- extract and open
All platforms - commit |
574dd8b to
e283495
Compare
Add an opt-in setStreamNonChunkedResponses() flag plus a header-time buffer predicate so a Content-Length/EOF-delimited response body can be delivered piece-wise to chunkHandler_ (reusing the chunked path's deliverChunks/resumeChunkProcessing backpressure) instead of being fully buffered into response_. Completion in streaming mode is tracked via a running byte counter against the upstream Content-Length, and the computed completion flag is threaded through chunkState_ so a backpressure-paused final piece resumes into closeAndRespond() instead of hanging (#17807 keep-alive class). Default is off, so every existing wiring site keeps its current buffering behavior.
ChunkProxy previously always enveloped proxied bytes as HTTP chunked transfer, which was only correct because it only ever saw upstream responses that were already chunked. Now that AsyncClient can also feed it Content-Length-delimited bodies, decide the client-facing framing once at header time: preserve a known upstream Content-Length and write raw body bytes (so browser download progress works), or fall back to chunked framing when the upstream length is unknown. Also strips the hop-by-hop Transfer-Encoding header and preserves any Set-Cookie already stamped on the client response across assign.
In Content-Length framing the empty final completion signal enqueues no bytes, so if it arrives before the header write's completion handler runs, writeBuffer_ still appears to hold only one chunk and a second concurrent asyncWrite of the same buffered entry could be issued, eventually popping an already-emptied queue. Track an explicit clientWriteInProgress_ flag so a write is only kicked off when none is already outstanding.
Fills the Step 4 unit-test gaps left after Steps 1-2's early test files (Content-Length header visible to the chunk handler, backpressure on the final piece over a kept-alive upstream, chunked-with-handler regression guard), and adds e2e coverage for large and concurrent downloads through the /p/ localhost proxy, asserting Content-Length framing and byte-exact completion end-to-end.
closeAndRespond() sent the empty completion chunk directly to chunkHandler_ and ignored its return value, unlike every other chunk delivery (which flows through deliverChunks()/chunkState_ and can be paused/resumed). If ChunkProxy's outbound buffer happened to be exactly full at the instant the body finished, that decline was silently dropped: nothing recorded that completion still needed sending, and ChunkProxy's writeChunk() prioritizes a pending buffer-full condition over closing on "received final, nothing left to write" -- leaving both proxied connections open indefinitely. Track a dedicated completionPending_ flag, checked first in resumeChunkProcessing(), so a declined completion signal is retried via closeAndRespond() itself once the consumer drains -- kept separate from chunkState_ so retrying never risks sending completion twice.
The previous fix (854b05103f) treated any false return from the completion-signal call as "pause, resume later" -- but that return value is overloaded across ChunkHandler consumers. RPC-style streaming consumers (LauncherClient, sendMethodToSession's onChunk wrapper) also return false on the empty chunk, but to mean "stream is done," closing the connection themselves synchronously within that same call. They never call resumeChunkProcessing() (no ChunkProxy in that path), so the previous fix would have left completionPending_ stuck true forever, permanently skipping disableHandlers() on every ordinary completion of those RPC calls. Add setChunkHandlerSupportsPause(), an explicit opt-in only ChunkProxy sets (alongside setChunkHandler in proxy()), so closeAndRespond() only tracks a declined completion signal for consumers that actually follow the pause/resume contract. Every other consumer's behavior is unchanged from before 854b05103f.
…, harden body-forwarding edge cases ChunkProxy now handles both chunked and non-chunked (Content-Length) response bodies, so the old name was misleading; renamed it and the ChunkHandler type throughout core/http and their call sites. While auditing streaming edge cases against Go's net/http/httputil ReverseProxy test suite, found and fixed a real defect: FixedBufferProxy writes response headers/body directly to the downstream connection, but nothing prevented a later upstream-error handler from writing a second, malformed response on the same connection once streaming had already begun. AsyncConnectionImpl now guards against this via sendingResponse_. Also fixed FixedBufferProxy's framing decision to validate Content-Length the same way AsyncClient does, rather than choosing Content-Length framing from bare header presence and forwarding an unparseable value verbatim. Added unit tests covering the above, plus buffer-full backpressure in Content-Length framing mode, downstream write failures during header/body writes, multiple queued chunks/backpressure cycles, and characterization tests documenting known (not fixed in this pass) gaps around truncated/over-long Content-Length bodies and HEAD responses with stray bodies.
kevinushey
left a comment
There was a problem hiding this comment.
Thanks @mbaynton for all your work on this so far -- this is coming together really well! Streaming the localhost proxy responses is a big improvement, and the depth of test coverage here is much appreciated.
I took a detailed pass over the latest changes and left inline comments. The broad themes:
- Streamed-path parity: a few behaviors the old buffered path guaranteed are dropped on the streaming path -- the server response filter (
server-add-header, theServer: RStudiostamp) is bypassed inwriteResponseHeaders(), and the framing decision mishandles some RFC-legal cases (case variants / multi-codingTransfer-Encodingvalues, bodiless 204/304 responses, HTTP/1.0 peers). - Concurrency / teardown: a few places where a race or exception leaves a connection wedged instead of failing fast (
setConnectHandler()underhandlersDisabled_,responseAlreadyStarted()'s guarded path, exception handling inqueueChunk()). - Consistency / hot path: hop-by-hop stripping now differs between the buffered and streamed delivery modes, the buffer predicate duplicates dispatch logic from
handleLocalhostResponse, andqueueChunk()does some avoidable per-piece work. - Test hygiene: a couple of test-naming and timing nits.
Smaller things I didn't comment on inline: the !chunkedEncoding_ term in the streamResponse_ computation looks dead (chunked upstreams take the pre-existing chunk path); the Set-Cookie preservation loop re-implements http::headerValues(); and some of the contract comments are duplicated between AsyncClient.hpp and FixedBufferProxy and could probably live in one place.
| // work -- confirmed via git history) calls closeAndRespond() unconditionally | ||
| // on EOF without checking responseBodyComplete(), so this is silently | ||
| // accepted as a complete, successful (if short) response today. | ||
| TEST(AsyncClientContentLength, TruncatedContentLengthBodyReportsErrorNotSilentSuccess) |
There was a problem hiding this comment.
A few of the "known gap" tests have names asserting the opposite of what their bodies pin: this one (and its Streamed twin) is named ...ReportsErrorNotSilentSuccess but asserts EXPECT_FALSE(gotError), i.e. silent success; BodyLongerThanDeclaredContentLengthStopsAtDeclaredBoundary asserts the excess bytes ARE forwarded; HeadRequestWithStrayUpstreamBodyBytesIsNotForwarded asserts the body IS forwarded. Green tests named for the fixed behavior are easy to misread in triage, and they'll start failing the moment the gap is actually fixed. Renaming them to describe current behavior (e.g. TruncatedContentLengthBodyIsSilentlyAcceptedToday) would match the block comment above, which already says these characterize current behavior.
|
|
||
| // Format the outbound bytes for this piece: raw for Content-Length, or a | ||
| // size-prefixed HTTP chunk for chunked framing. | ||
| std::string formatted = |
There was a problem hiding this comment.
Hot-path note: formatted is built before the buffer-full check, so under backpressure every declined piece constructs and discards the fully formatted string, then rebuilds it on redelivery -- and the motivating workload (large download, slow browser) keeps the buffer near-full, so most pieces get formatted twice. With the ostringstream in formatMessageAsHttpChunk() adding two more copies per piece, a 1GB download memcpys roughly 2-3GB through userspace beyond the unavoidable read copy. Cheaper to size-check arithmetically first (chunk.size() [+ hex prefix + 4] vs. maxBufferSize_) and only build formatted on acceptance; the chunk envelope could also be built with a reserved string + snprintf hex prefix instead of a stringstream.
There was a problem hiding this comment.
A convincing enough argument, when you put it that way :)
Fixed in 9e4de22
| // the client before resetting -- SO_LINGER{0} can otherwise discard | ||
| // unacknowledged data, silently turning "partial body then reset" | ||
| // into "no body at all then reset". | ||
| std::this_thread::sleep_for(std::chrono::milliseconds(25)); |
There was a problem hiding this comment.
This 25ms sleep makes the test timing-dependent: SO_LINGER{0} RST processing discards unread data in the receiver's buffer, so on a loaded CI runner where the client io thread hasn't parsed the headers within 25ms, the whole response is discarded and the error path runs before FixedBufferProxy ever writes headers -- UpstreamErrorArrivesAfterFixedBufferProxyHasFlushedHeaders then fails EXPECT_EQ(writeResponseHeadersCount_, 1) with 0. A deterministic handshake (server waits for a signal that the first piece was delivered downstream before sending the RST) would remove the race.
| virtual void setStrand(boost::asio::io_context::strand* pStrand) = 0; | ||
|
|
||
| // Opt in to treating a `false` return from the FixedBufferHandler's completion | ||
| // call (the empty chunk sent by closeAndRespond()) as "temporary |
There was a problem hiding this comment.
This flag makes the same false return from the same callback mean three different things: pause (data chunk), pause (final chunk, flag set), or ignored/done (final chunk, flag unset). A future consumer that wires setFixedBufferHandler + setStreamNonChunkedResponses but misses this third knob gets a load-dependent hang (a completion declined at an exactly-full buffer is dropped and never retried), and a done-style consumer that copies FixedBufferProxy's wiring latches completionPending_ forever. Since the rename in this PR already touches every consumer, the same migration could change the callback's return to an enum (Continue / Pause / Done), or split completion into its own handler -- which would delete the flag and the defensive comments around it.
| // its auth-cookie stamping (getAuthCookies(), ServerSessionProxy.cpp:267, | ||
| // 1003) will need to move from handleProxyResponse's single post-completion | ||
| // writeResponse(response, true, authCookies) call into *this* header-write | ||
| // path — headers are flushed here, at the first queueChunk, before any |
There was a problem hiding this comment.
Nit: non-ASCII em-dash (U+2014) in this comment; the rest of the PR uses ASCII --.
FixedBufferProxy decided its client-facing framing from the upstream response alone: chunked whenever no parseable Content-Length was found. Nothing consulted the response status code or the client's own request, so two of RFC 7230 3.3.1's MUST NOTs were reachable once this branch started streaming non-chunked localhost-proxy responses (on main, ChunkProxy only ever forwarded a Transfer-Encoding the upstream had set itself, and only on the /s/ path). "A server MUST NOT send a response containing Transfer-Encoding unless the corresponding request indicates HTTP/1.1 (or later)." An HTTP/1.0 client does not de-chunk, and since we always send Connection: close it applies 3.3.3 rule 7 and reads to EOF -- so it would hand the hex chunk-size lines to the user as body content. Realistic in front of nginx, whose default proxy_http_version for upstreams is 1.0. Framing now falls back to close-delimited (no framing header, raw bytes, delimited by the close every terminal path here already performs) when the length is unknown and the client is pre-1.1. "A server MUST NOT send a Transfer-Encoding header field in any response with a status code of 1xx (Informational) or 204 (No Content)." A 204 commonly carries no Content-Length, which put it squarely in the chunked fallback, and 1xx got there too (ResponseParser has no interim-response handling, so a 103 Early Hints is parsed as the response; 101 is already routed to the buffered path by the localhost proxy's buffer predicate). Both then received a 0\r\n\r\n terminator that 3.3.3 rule 1 says cannot be present at all. Adds a NoBody framing covering everything 3.3.3 rule 1 describes -- responses to HEAD and all 1xx/204/304 responses: headers only, no framing header, no body bytes, no terminator. Upstream body bytes on such a response are dropped rather than relayed, since the client will not read them and they would otherwise land on the wire as the start of a different message. Per 3.3.2 the upstream Content-Length is also removed for 1xx/204, but kept for HEAD/304 where it legitimately describes the body an equivalent GET would return. Not addressed here: double-chunking when the upstream sends a Transfer-Encoding that AsyncClient's exact-match de-chunk predicate and ours disagree about, and the inherited upstream HTTP-version in the status line (RFC 7230 2.6).
RFC 7230 2.6: "Intermediaries that process HTTP messages (i.e., all intermediaries other than those acting as tunnels) MUST send their own HTTP-version in forwarded messages." Responses rserver generates itself already carry 1.1 -- http::Message's constructor sets it -- but proxied ones do not. Response::assign() copies httpVersionMajor_/Minor_ off the upstream response, and Response::appendFirstLineBuffers() writes them straight into the status line, so an HTTP/1.0 backend on the localhost port proxy produced an HTTP/1.0 status line on our HTTP/1.1 connection. That was harmless while every proxied response was fully buffered and Content-Length framed. It stopped being harmless once this hop started choosing its own framing: "HTTP/1.0 200 OK" followed by "Transfer-Encoding: chunked" is self-contradictory, and clients that key de-chunking off the response version rather than the request version get the chunk-size lines as body content -- the same corruption the HTTP/1.0-client fix in the previous commit avoids, reached by a different route. Normalizing centrally in AsyncConnectionImpl's two response emit points rather than at each proxy call site keeps the streaming and buffered paths from disagreeing, and covers the overlay proxy paths in the pro repo for free. It is narrower than it looks: the only responses whose version is not already 1.1 are proxied ones, which is exactly the set that needs correcting.
The last of RFC 7230 3.3.1's Transfer-Encoding MUST NOTs: "A server MUST NOT send a Transfer-Encoding header field in any 2xx (Successful) response to a CONNECT request." This is reachable rather than theoretical. AsyncServerImpl enforces a method allowlist (GET/POST/HEAD/PUT/OPTIONS/PATCH/DELETE, everything else 405) -- but explicitly skips it for proxy handlers, "as we flow all traffic like a proxy", and /p/ and /p6/ are registered via addProxyHandler(). A CONNECT whose request-target routes to the port proxy is therefore forwarded to the user's app like any other method, and a 2xx from that app without a Content-Length picked up chunked framing. Nothing in either repo implements inbound CONNECT tunneling -- the only "CONNECT" in the tree is TcpIpAsyncClientSsl, which sends one outbound to an HTTPS forward proxy -- so there is no tunnel to preserve here. NoBody is the least-wrong framing available: per 3.3.3 rule 2 such a response has no body framing at all and the client must ignore any Content-Length or Transfer-Encoding it sees, so we send headers, no body, then the close we always perform. Scoped to 2xx: per RFC 7231 4.3.6 any other status means no tunnel was formed and the connection remains governed by HTTP, so an upstream 405/502 keeps ordinary framing and its body. Rejecting CONNECT outright at the front door would arguably be better still, but that means narrowing the deliberate "flow all traffic" contract for proxy handlers, which reaches past this class.
RFC 7230 3.2: header-field = field-name ":" OWS field-value OWS. The whitespace after the colon is *optional* whitespace, so "Name:value" and "Name:" are both well-formed. parseHeader() searched for a literal ": " and returned false otherwise, so those fields were discarded and parsing continued with the rest of the message. Discarding is worse than rejecting: it left this process and the sender disagreeing about which fields the message even carries. For a framing field that disagreement is a smuggling primitive -- an upstream "Transfer-Encoding:chunked" disappeared here, so the body was read as unencoded while still chunk-framed on the wire, and every downstream chunked-ness check had nothing left to see. That is one of the routes into the double-chunking fixed in the following commit. This affects response headers (via ResponseParser) and multipart part headers. Inbound request headers are unaffected: RequestParser has its own state machine, which also requires the space but errors the whole request out rather than dropping a field -- non-conformant too, but fail-closed, so it is left alone here. Not addressed: parseHeader() still accepts "Name : value" by trimming the name, which RFC 7230 3.2.4 says a server MUST reject.
RFC 7230 3.3.1: "A sender MUST NOT apply chunked more than once to a
message body."
AsyncClient decides whether to de-chunk a response; FixedBufferProxy
decides how to frame what it is handed; the buffered localhost path
decides whether to strip the header and set a Content-Length. All three
answered "is this body chunked" independently, by comparing the raw
Transfer-Encoding field to the string "chunked". Inputs where those
answers diverged -- or agreed but were both wrong about the bytes on the
wire -- produced a body chunked twice. On the wire:
1f\r\n14\r\n{"name":"jsonlite"}\n\r\n0\r\n\r\n\r\n0\r\n\r\n
an outer chunk wrapping the entire inner chunked body, terminator and
all. A browser de-chunks one layer and renders the inner chunk-size
lines as content.
Three ways in, all now covered by end-to-end tests through the real
socket/AsyncClient/FixedBufferProxy path:
- Transfer-Encoding plus a non-zero Content-Length. AsyncClient required
contentLength() == 0 before de-chunking, so it read chunk-framed bytes
as an opaque body while FixedBufferProxy, reading the same header,
re-wrapped them. RFC 7230 3.3.3 rule 3 says the Transfer-Encoding wins
and the Content-Length must be removed before forwarding -- which is
what the chunked branch does -- so the guard is gone. This header pair
is also the response-smuggling shape, and here the upstream is a user's
own app.
- "Chunked". Coding names are case-insensitive tokens (RFC 7230 4).
- "gzip, chunked". Chunk-framed, but de-chunking leaves gzip-encoded
bytes. There is no honest way to pass those on, so AsyncClient now
refuses the response rather than relabelling them. Likewise "chunked,
gzip", which is not chunk-framed at all. The obsolete "identity"
coding is ignored rather than refused.
Replaces all three comparisons with util::parseTransferEncoding(), which
flattens the (possibly repeated, possibly multi-valued, parameterized)
field into an ordered coding list and reports whether chunked is final
and whether anything else is present. Sharing one parse is the actual
fix: two call sites cannot disagree about a body they are handing
between them if they ask the same question.
Also answers the standing TODO on the buffered path about "gzip, chunked
or chunked, gzip" -- those are now rejected upstream of it.
Follow-up to the previous commit, from review: "chunked, chunked" (or the same coding repeated across two header fields) slipped through every signal parseTransferEncoding() reported. chunkedIsFinal was true and no other coding was present, so it read as ordinary chunking -- AsyncClient stripped one layer and FixedBufferProxy added one back, leaving the browser a body that still had a chunk layer inside it. Two layers in, two layers out: the same corruption the previous commit set out to remove, reached from the other direction. RFC 7230 3.3.1 forbids a sender applying chunked more than once, so such a message is malformed on arrival and there is nothing to preserve by accepting it. Fixed by moving the verdict into the parse rather than counting codings at the call site: TransferEncoding::isDecodable now says whether the declared codings are ones this process can actually undo -- none, or exactly one "chunked" applied last -- and AsyncClient just asks. The old shape had AsyncClient reassemble that judgement from two flags, which is the same reassemble-it-yourself pattern that let the call sites disagree before; hasOtherCodings existed only to feed it and is gone.
"HTTP/1.1 204 No Content\r\n\r\n" -- a complete, well-formed response -- never arrived. The read waited for a terminator that never came and the exchange ended in an EOF error. ResponseParser::parseStatusLine() consumes the status line including its CRLF, so a response with no header fields leaves only the lone terminating CRLF behind it. Two things then went wrong with that: - the header read searched for "\r\n\r\n", which a bare "\r\n" cannot match, so it read past the end of this response looking for a terminator belonging to some later one; - http::parseHeaders() treats a leading blank line as leading whitespace and keeps going, so even once the bytes were there it walked into whatever followed and adopted those lines as this response's header fields. Replaces the delimiter with a match condition that scans line by line and stops at the first empty line -- correct whether or not any fields precede it -- and teaches ResponseParser::parseHeaders() to recognize and consume an empty header block rather than handing it to the lenient shared parser. The leniency in http::parseHeaders() itself is left alone; other callers (multipart) may rely on it, and responses no longer reach it in that state. Found while implementing 1xx handling, which cannot work without it: a 100 Continue is normally exactly this shape. Independent of that, and pre-existing -- the 204 above is broken today.
RFC 7231 6.2: "A client MUST be able to parse one or more 1xx responses received prior to a final response, even if the client does not expect one." A 1xx carries no body and another response follows it on the same connection. AsyncClient took the first status line it saw as the final response, so everything after the interim response's header block was read as that response's body. Before the framing work earlier on this branch the caller got a 103 whose "body" was the literal bytes "HTTP/1.1 200 OK\r\n..."; after it, the 103 takes the no-body framing and the real response is discarded outright. Either way it was never delivered. Reachable both ways in: nothing in this tree strips a client's "Expect: 100-continue" before the request is proxied on, so an upstream may answer with 100 Continue, and 103 Early Hints is emitted unprompted by a growing number of servers. handleReadHeaders() now discards an interim response and goes back for the next status line. A 1xx has no body, so the bytes after its header block begin the next response, which async_read_until finds already buffered rather than waiting on the socket for them; it always posts its completion handler, so looping this way does not nest stack frames. The skip is bounded (8) so an upstream that never commits to a final response fails rather than being allowed to keep us reading. 101 is deliberately excluded despite its status. It is the final HTTP response on the connection -- what follows is the upgraded protocol, not another response -- so skipping it would discard the handshake and then try to parse websocket frames as a status line. The test harness now installs the same buffer predicate the localhost proxy uses, so a 101 takes the buffered websocket-upgrade path there as it does in production. Not addressed: RFC 7231 6.2 also says "A proxy MUST forward 1xx responses", and these are dropped rather than relayed to the browser. Forwarding needs an interim-response write path downstream -- AsyncConnectionImpl's sendingResponse_ guard makes any second write a no-op by design -- which is more than this change. The cost is losing 103 preload hints; nothing breaks.
From review: writeResponse() has always called responseFilter_ before sending, and writeResponseHeaders() never did -- so every response streamed through FixedBufferProxy lost whatever the filter contributes. That is not an optional hook only some deployments configure. AsyncServerImpl::acceptNextConnection() hands its own connectionResponseFilter to every connection it accepts, and that filter stamps the "Server" header and each server-add-header header, which server-options.json documents as applying to *all* responses from RStudio Server and which in practice carry HSTS / X-Frame-Options. In pro it also runs the multi-session Location/Refresh rewriting. Since this branch makes streaming the default for /p/, the headers were going missing on exactly the path that serves arbitrary user apps. The gap predates this branch -- ChunkProxy already wrote headers this way for chunked /s/ responses -- but was narrow enough there to go unnoticed. Called in the same position writeResponse() calls it: last, after this method's own HTTP-version/Date/nosniff handling, so a filter that deliberately overrides one of those wins identically on both paths. It sits after the responseAlreadyStarted() guard like every other mutation here, so a second header write, or a late writeResponse() from an upstream error handler, cannot re-run it and append duplicate fields. Checked every ResponseFilter in both trees for path-independence first: connectionResponseFilter (Server + server-add-header), sessionContextResponseFilter (Location/Refresh only, and already forced down the buffered path by proxyLocalhostRequest's buffer predicate), recordLastRequestTime (records a timestamp, mutates nothing), and TestMain's stub. All header-only and idempotent, so none behaves differently for having been reached from here. One thing deliberately not defended against: the filter runs after FixedBufferProxy has chosen framing headers, so a filter -- or an admin's server-add-header -- setting Content-Length or Transfer-Encoding would override them. writeResponse() has the same exposure today, so this is parity rather than a new hazard, and hardening it belongs with the framing work, not here. Noted at the call site.
Review flagged that the filter now runs after FixedBufferProxy has chosen framing, so a server-add-header could reintroduce Content-Length, Transfer-Encoding or Connection and produce a malformed response, and suggested either filtering before framing is settled or restoring the framing headers afterward. Not taking either. Both would make writeResponseHeaders() disagree with writeResponse(), which allows exactly these overrides -- the filter runs there before the response is serialized, and its Content-Length default only applies when none is present. Diverging the two paths is the class of bug the previous commit set out to remove, and filtering earlier is not reachable anyway without handing responseFilter_ to callers so each can invoke it at its own chosen moment. The desync half of the concern also does not hold here. Every terminal path in FixedBufferProxy closes the client connection, and writeResponse()'s default close=true does the same, so a client misled by a bogus length reads what it believes is the body and then hits EOF rather than parsing a following response out of leftover bytes. The one close=false caller on this path is the websocket upgrade, which the localhost proxy's buffer predicate forces down the buffered path. What is left is a single malformed response from a misconfiguration that breaks the buffered majority of responses identically, so it would not survive first contact with a browser. Taking the third suggestion, which stands on its own: the parity was asserted in a comment and nothing enforced it. Two tests now write the same framing-mutating filter down each path and pin that both let it win -- including a declared Content-Length of 999 against a five-byte body on the buffered path, the exact shape the streaming path was said to be uniquely vulnerable to. If either path is later hardened, the pair fails until both are.
From review (r3806681220): the handlersDisabled_ gate added earlier on
this branch made setConnectHandler() silently drop the notification
rather than deliver it. At base a late registration -- requestWritten_
already true -- always invoked the handler, so FormProxy::writeData()
hit the closed upstream and tore down. Now the handler is neither stored
nor invoked, connectedDownstream_ never becomes true, form data buffers
to maxBufferSize_, and parsing pauses with no writer to lift it.
Reachable because registration is deliberately late.
ServerSessionProxy::proxyRequest() posts its ClientHandler to the
io_context after execute() to preserve the caller's ordering, and
FormProxy::initialize() runs from there; on rserver's multi-threaded
io_context the settle and the post land on different threads.
setConnectHandler() now takes a second handler and guarantees one of the
two is delivered, across all three registration cases:
- Already settled when it is called: reported synchronously. Terminal,
so the answer cannot go stale.
- Registered before the request was written, then settled before
handleWrite() could deliver the connect: reported by
disableHandlers() as it detaches the stored handler.
- Registered after the request was written, so this call owns delivery:
dispatched to the strand and decided there rather than at
registration, since a decision made under socketMutex_ and acted on
after releasing it is one another thread can invalidate in between.
The latter two go through the strand rather than being invoked directly.
disableHandlers() may be called with a consumer's own lock held
(FixedBufferProxy::closeConnections() holds its mutex_) or from inside a
handler invocation, so calling out from there would invert the lock order
its declaration warns about; posting defers until the caller has unwound
and keeps the notification serialized with every other handler
invocation.
Staleness matters because of what a caller does with a connect
notification. FormProxy responds by writing, so a connect delivered for a
socket that has since closed has it set connectedDownstream_, fail the
write, and take its error path -- which closes the upstream connection
too, resetting whatever response FixedBufferProxy was mid-write of. That
is the same truncation the FormProxy side below is careful to avoid, so
reporting the settle instead is what makes the two consistent. The
re-read checks closed_ as well as handlersDisabled_: a bare close() (an
embedder tearing down, a deadline firing) marks only the former, and a
connect notification is equally untrue then.
handleWrite() copies connectHandler_ out without clearing it, so a
non-empty handler does not by itself mean one is still pending;
requestWritten_ -- set in that same critical section -- is what
discriminates. Reporting on the handler alone would fire on every
ordinary completed request and have FormProxy discard form data
mid-upload, so both directions are pinned by tests.
Checked when the gate can actually be closed, since a failure path that
fires while the connection is still usable would fail uploads that would
otherwise have succeeded. It cannot: all three sites -- handleError(),
closeAndRespond(), FixedBufferProxy::closeConnections() -- have already
closed the socket, and keepConnectionAlive() has no override anywhere in
either tree, so closeAndRespond()'s close is unconditional. Retries are
excluded too: handleConnectionError() runs retryConnectionIfRequired()
first and only reaches handleError() once retrying is done, so a
transient connect failure that later succeeds never trips the gate.
FormProxy's side deliberately does not close pUpstreamConnection_.
Whoever settled the client already owns finishing it -- the error path
has run the ErrorHandler, and the ordinary path has handed a complete
response to FixedBufferProxy, which closes both connections once it has
written it. That ordinary path is not an error case: a session may
legitimately answer a 401/403/413/redirect without reading the whole
request body, and closing from here would race that write and turn a
clean status code into a connection reset. So it drops what it has
buffered and accepts-and-discards the rest, which keeps the upstream
connection parsing so it can be closed normally. The drain is bounded by
that in-flight response, which is already complete.
Tests, all against a real socket, one per case above plus the negatives:
registration after a completed exchange and after a refused connection
report closed; a stored registration detached before the write completes
reports closed exactly once, and only once the loop is pumped, proving it
is posted rather than invoked inline, with a second disable adding
nothing; a registration after the write with a settle racing its delivery
reports closed, while the same registration against a live client still
reports connect; a delivered connect reports closed zero times; and a
control that the ordinary pre-execute() ordering still reports connect.
The two races are driven deterministically rather than by contending
threads -- a server that accepts and never replies leaves the request
written with the exchange still live, which is the only state the third
case is reachable from. Each test was confirmed to fail against the
unfixed code. New FormProxyTests.cpp covers the write-through baseline,
that a settled downstream keeps accepting form data (100 pieces against a
16-byte buffer, every one of which would trip the pause if it were still
buffering), and that neither connection is closed.
Review (r3806681292) noted that queueChunk() built the formatted envelope before the buffer-full check, so every piece declined under backpressure was formatted and discarded, then formatted again on redelivery -- and the motivating workload, a large download to a slow browser, sits near the buffer limit for most of its life, so that is most of the body formatted twice. With formatMessageAsHttpChunk()'s ostringstream adding two more copies per piece on top, a 1GB download memcpys several GB through userspace beyond the unavoidable read copy. Both halves of the suggestion taken. queueChunk()'s switch now yields a size rather than a string, computed arithmetically, and the envelope is built at the single point where the piece is certain to be enqueued -- after the buffer-full check and after the receivedFinal_ latch, so a declined piece costs no formatting at all. formatMessageAsHttpChunk() drops the stringstream for one reserved string plus an snprintf'd hex prefix, so the payload is copied once instead of three times. Measured on a synthetic 1GB stream, formatting alone: 131ms -> 20ms at 64KB pieces, 81ms -> 14ms at 8KB. The arithmetic needs a companion the proxy can trust exactly rather than an open-coded `size + hex + 4` at the call site, because the prediction is what currentBufferSize_ is charged with while onChunkWrote() credits back the formatted string's real size(). Any disagreement drifts the accounting: upward until backpressure never releases and the download stalls, downward until the buffer outgrows the bound it exists to enforce. So httpChunkSize() lives beside the formatter, both derive the size line from one hexDigitCount(), and a new test walks every length up to 300 plus the hex rollover boundaries asserting the two agree. The same file covers the envelope shape, the zero-length terminator, and a payload with embedded NULs -- the envelope is length-delimited, and a snprintf'd size line should not tempt anyone into treating the body as a C string. No NEWS.md entry: this is a change to an unreleased feature still under review on this branch.
Review found the settle-reporting added in 745b11b keyed only on handlersDisabled_, which close() does not set. Both sides of setConnectHandler()'s race were affected: - Registered, then closed: the !requestWritten_ branch stores a handler that only disableHandlers() ever reports. After a bare close() the aborted connect/write completion enters handleError(), returns early on closed_, and never reaches the disableHandlers() at the end of that function -- so nothing detached the handler and nothing reported it. - Closed, then registered: handlersDisabled_ is false, so the terminal branch did not fire and the registration went down that same storing branch. Either way the caller hears nothing, which for FormProxy means connectedDownstream_ stays false, form data buffers to maxBufferSize_, and parsing pauses with no writer left to lift it. The asymmetry was already recognized one function over: deliverLateConnectNotification() checks closed_ as well, precisely because a bare close() marks only that flag and a connect notification is equally untrue then. The registration path was the one place that did not. It now tests both, and stays synchronous for the same reason it always did -- neither flag is ever cleared, so the answer cannot go stale. close() now also detaches and reports a pending connect, using the same `connectHandler_ && !requestWritten_` test as disableHandlers(): a non-empty handler alone does not mean one is pending, because handleWrite() invokes its own copy without clearing the member. Posted rather than invoked, again as disableHandlers() does, since FixedBufferProxy::closeConnections() calls close() with its own mutex_ held and calling out from under socketMutex_ would invert that order. Detaching is what keeps the pair reporting exactly once: the ordinary close()-then-disableHandlers() teardown now finds the handler gone. On reachability, this hardens the stated contract rather than fixing an observed hang. close() is public API and there are bare-close callers -- FormProxy's own error path, the launcher and session-pid clients that close a streaming client to stop it, SocketProxy -- but every one runs with requestWritten_ already true, FormProxy included, since it only writes after the connect was delivered. What was wrong is that "exactly one of the two handlers is ever delivered; neither is silently dropped" was violable by a legal call sequence against a public method. Tests, both confirmed to fail beforehand: a bare close() after registration reports closed exactly once and only once the loop is pumped, proving it is posted rather than invoked inline, with a following disableHandlers() adding nothing; and a registration after a bare close() reports closed rather than storing a handler nothing would deliver. The existing detach-before-write and delivered-connect tests pin that the count stays at one and zero respectively. Also dropped the desktop::NetworkReply citation from the close() comment: disableHandlers()'s own docs name it as the embedder that motivated it, but that class no longer exists in this tree, so it cannot serve as a live example of a bare-closing caller.
|
|
||
| boost::shared_ptr<AsyncConnection> pClientConnection_; | ||
| boost::shared_ptr<IAsyncClient> pServerConnection_; | ||
| http::Response serverResponse_; |
There was a problem hiding this comment.
This serverResponse_ variable is not used.
jeffvroom
left a comment
There was a problem hiding this comment.
LGTM! It would be nice to fix that bad_alloc and the one unused serverResponse_ member in FixedBufferProxy.cpp but looks really great. We'll have to reconcile some changes I made to ChunkProxy.cpp in the agentsview ui PR - for setting auth cookies, but I think this fix will remove the need for those changes.
The double-response guard read sendingResponse_ and then set it, on a plain bool, from callers that are not all on the same execution context -- so two writers could both observe "not started" and both proceed. Make it a single atomic exchange instead: a claim that exactly one caller can win. The entry points that mutate response_ before writing it (assign(), setError()) claim first and then reach the write through a new private writeResponseImpl(), rather than re-entering the public writeResponse() and failing the claim against themselves. Losing callers are now settled with already_started instead of dropped. Returning silently stranded whatever the caller meant to do in its completion handler: for FixedBufferProxy's header write that left clientWriteInProgress_ latched true forever, so queued chunks never flushed, backpressure never resumed, and both sockets leaked with no timeout to reap them. The handler is posted rather than invoked inline, both because asio's contract is that a completion never runs inside the initiating call and because callers hold locks across it. Neither side closes the client connection on that path. The winner owns it and its write may still be in flight, so closing would truncate or reset the response the claim exists to protect -- which means FixedBufferProxy has to tell already_started apart from the transport failures its handleError() otherwise sees, and detach from its upstream alone. Its closeConnections() grows a closeUpstream() half for that. From review discussion r3806681239.
continueParsing() posted handleRead() bare onto the io_context, so a resumed parse ran on an arbitrary pool thread while every other invocation of handleRead() arrives on strand_ (readSome() binds its completion to it). A resumed parse is not a passive operation: it can decide to write a response of its own, either because the parser rejects what follows (RequestParser::error -> writeResponse(BadRequest)) or because the request completes and callHandler() runs. And its caller is a body writer on some other context entirely -- FormProxy resumes us from the *downstream* connection's handlers. That is how a second response writer appears on a connection even where the proxy wiring deliberately shares one strand between the two hops (proxyLocalhostRequest), and it races this connection's own reads and response state besides. Post through strand_ so every handleRead() is serialized with the rest of the connection. Still a post, not a dispatch, so callers are not reentrantly locked. From review discussion r3806681239.
FixedBufferProxy built the client-facing response by mutating pClientConnection_->response() in place from the upstream AsyncClient's context, and only then called writeResponseHeaders(). The connection has writers of its own -- its read path can turn a request-parse error into writeResponse(BadRequest) at any moment -- and an in-flight write hands asio buffers that point straight into that response's own member strings: Message::appendHeader() buffers Header::name/Header::value, and Response::appendFirstLineBuffers() buffers statusCodeStr_/statusMessage_. Nothing is copied into a serialization buffer. So assembling that response from elsewhere can free the storage asio is mid-read, which is a use-after-free rather than merely a duplicate response -- and it happens even when the assembling caller goes on to write nothing at all, because the claim it then fails is reached only after the mutation. Running on the connection's strand is not a fix for this on its own: a strand serializes handlers, not the asynchronous writes they start, so the previous winner's write is still outstanding while the next handler runs. The response has to be claimed before it is assigned. So: - writeResponseHeaders() gains an overload that takes the response to send, mirroring the writeResponse() pair, and assigns it only after winning the claim. - FixedBufferProxy assembles into its own copy of the upstream response and hands that over. It no longer touches the connection's response while streaming at all, in either direction. - The one read it did need -- carrying over Set-Cookie headers stamped on that response before we were asked to proxy anything -- moves to proxy(), the point where the response is still ours alone. That runs on the connection's own request-handling path before the upstream request is executed, and after authentication has stamped its refreshed cookies (ServerSecureUriHandler refreshes them before dispatching), so it sees the same headers the old read did without racing an upstream error handler on another context. - The assembly still moves out of queueChunk() into a writeHeaders() dispatched onto the client connection's strand, so the header write is initiated there like every other write on it. dispatch() rather than post() so the wiring that already shares a strand between the two hops (proxyLocalhostRequest) runs it inline, exactly where it ran before. queueChunk() keeps only the bookkeeping, latching wroteHeaders_ and clientWriteInProgress_ before the handoff so a chunk queued in the gap falls through to the "a write is already in flight" branch instead of starting a second write. It copies the upstream response into serverResponse_ for writeHeaders() to assemble from, since http::Response is noncopyable and cannot be bound into the dispatched call; the streaming path never fills response_.body(), so that copies headers only. Record the resulting rule on AsyncConnection::response() itself, since it binds anyone else who populates a response directly. From review discussion r3806681239.
FixedBufferProxy used core/Thread.hpp's LOCK_MUTEX/END_LOCK_MUTEX for each of its locked regions. That pair swallows anything escaping the block (via CATCH_UNEXPECTED_EXCEPTION) and then lets control fall out of it into whatever follows, which for this class is never survivable: - In queueChunk() the next statement is `return true`, reporting a chunk as delivered when it was in fact dropped. The client gets a Content-Length-framed body with a hole in it and only a log line as evidence. - A throw after writeChunk() latches clientWriteInProgress_ but before the write is initiated wedges the proxy permanently. No completion handler will ever run to clear the flag, so the upstream stays paused, neither connection is closed, and the proxy plus every buffered chunk leaks. - writeHeaders() had no guard at all. Only the inline-dispatch case runs inside queueChunk()'s locked region; otherwise it runs straight off the client connection's strand, so an escape from its header assembly unwinds through asio and out of AsyncServerImpl::runServiceThread()'s ioContext().run(), which logs it and lets that server worker thread exit for good. bad_alloc is the realistic trigger. formatMessageAsHttpChunk() copies a piece up to maxChunkSize (1MB) on every body chunk, under exactly the memory pressure that motivated streaming these responses in the first place. So every path that can throw now tears the proxy down instead: - failConnection() logs, marks the proxy failed, and closes both connections. It never throws and is idempotent, since its callers are catch blocks with nowhere to escalate to. - LOCK_MUTEX_OR_FAIL/END_LOCK_MUTEX_OR_FAIL replace the Thread.hpp pair throughout. The outer try covers lock acquisition itself (the thread_resource_error the old pair handled explicitly); the inner one covers the body, so its teardown runs with mutex_ still held and cannot interleave with a completion handler arriving on another thread. - writeHeaders() and handleError() get their own guards. handleError() needs one separately because both completion handlers reach it ahead of taking the lock, and Error construction, LOG_ERROR and the virtual close()/disableHandlers() calls can all throw. Both split their bodies into a helper so the guard could be added without reindenting the comments they carry. - A failed_ flag gates queueChunk(), writeHeaders() and both completion handlers. disableHandlers() already stops delivery in the ordinary case -- deliverChunks() rechecks handlersDisabled_ before every piece -- but failConnection() can only try to reach it: if closing the upstream throws on the way there, the handler stays attached and pieces keep coming. queueChunk() discards them with `true` rather than `false`, since `false` means "pause and redeliver" and nothing will ever resume us now. The tests inject a throw from the fake connection's header and body writes, and a throw from the fake client's close() for the teardown-fails case. Reaching the guards in onHeadersWrote()/onChunkWrote() needs the new runOneHandler(): the write those initiate is chained from the previous write's completion, so an injected failure can only be armed between two writes, not from a queueChunk() call the test drives directly.
Two follow-ups to the exception guards, from review of 8dc99d2: failConnection() drove its teardown through closeConnections(), which chains pClientConnection_->close(), pServerConnection_->close() and disableHandlers(). Those are virtual calls into asio and any of them can throw, so a failure in an earlier step abandoned the later ones -- and because failed_ is already latched by then, nothing retries them. Skipping disableHandlers() is the expensive outcome: it is what breaks the FixedBufferProxy <-> AsyncClient reference cycle, so without it this proxy, both connections and every buffered chunk leak for the life of the process. Each step is now attempted independently. handleError()'s guard also closed the client connection on every path, including already_started. That error is not a transport failure: it is claimResponse() reporting that another writer owns this connection's one response and may still be writing it, which is why handleErrorImpl() detaches from the upstream and deliberately leaves the client alone. Closing it from the exception path truncates exactly the response the claim exists to protect, and a failed upstream close is no reason to do that. The guard now honors the same rule via failConnection()'s new closeClientConnection argument. The teardown-failure test grows a throwing disableHandlers() to match: with every step now attempted, that is what keeps the handler attached, which is the precondition for an upstream still delivering into a torn-down proxy. A new test covers the already_started path with an injected upstream-close failure.
Two follow-ups to 3a84991, from review: Making the teardown steps independent left their failures silent, which removed the only evidence a failed cleanup would ever produce. failConnection() is the last code that runs for a proxy, so a step that did not complete leaves state nothing else will clean up -- a skipped upstream detach leaks this proxy, both connections and every buffered chunk for the life of the process. attemptTeardownStep() now names its step and logs a failure, under a guard of its own so a failing log cannot cost the caller its remaining steps. The teardown-failure test also claimed every step throws while injecting failures for only two of the three. The client close was the one missing, and it is the step whose failure matters most: it runs first, so it is what would take the other two down with it if the steps were ever chained again. The fake client connection gains a close() injection point and the test now fails all three.
kevinushey
left a comment
There was a problem hiding this comment.
Approved. The implementation looks reasonable to merge. I filed two separate follow-ups from this review:
- #18625 tracks fail-closed handling when copying AsyncClient callbacks throws. This is a very low-probability exception-safety hardening item.
- #18626 tracks normalizing de-chunked localhost proxy responses before redirect and Spark UI rewriting.
Neither follow-up needs to hold this PR.
Intent
OSS components for https://github.com/rstudio/rstudio-pro/issues/11740 - Proxied non-chunked responses are fully buffered in rserver memory.
Fixes #18546
Approach
This adds the proxying implementation itself that is capable of avoiding buffering entire response bodies, but does not actually employ it against session proxying in
rserver, where such a thing is probably highest value. It does go ahead and make use of it for the localhost proxy. In a follow-up, I'll enable it for session proxying.The basic idea is to
The reasons for this approach, as opposed to e.g. reverting to acting like a layer 2 dumb proxy as soon as we're done looking at headers, was
ChunkHandler/ChunkProxycode. It survives with some improvements, but has been renamed because now it handles proxying of unchunked responses. It's nowFixedBufferProxy.Automated Tests
Extensive integration tests are included covering a decent range of badness that proxies can see in the real world. These are inspired by scenarios the Go team has coverage for in their standard library.
QA Notes
Documentation
Checklist
NEWS.md