Repository navigation
Conversation
|
Updated 7:04 PM PT - Aug 21st, 2026
❌ @robobun, your commit a85fd16 has 1 failures in
🧪 To try this PR locally: bunx bun-pr 29599That installs a local version of the PR into your bun-29599 --bun |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds Server.requestFD(request) to return the underlying OS socket descriptor (or null after request-context release), a ChangesServer request FD and Node socket fd
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@test/js/bun/http/bun-server.test.ts`:
- Around line 1377-1382: The test can race because the server may close the
socket (Connection: close) before the test attaches the close listener; to fix,
create the close waiter before initiating the request: store const closePromise
= once(savedSocket, "close") immediately prior to calling fetch (or before the
request that may trigger close), then after awaiting res.text() call
savedSocket.destroy() and await closePromise, and finally assert savedSocket.fd
=== -1; reference savedSocket, once(savedSocket, "close"), fetch(...) and
savedSocket.destroy().
In `@test/js/bun/http/serve.test.ts`:
- Around line 1595-1613: The test currently resolves on the first data chunk in
the socket data callback (Promise.withResolvers resolve called from socket.data)
which can lead to parsing a partial HTTP response; change the logic in the
connection socket data handler to accumulate chunks into the received Buffer[]
and only resolve the promise after the full HTTP response body has been received
(e.g., parse headers from Buffer.concat(received) to read Content-Length after
the "\r\n\r\n" separator and wait until the concatenated body length equals
Content-Length, or wait for socket close) before splitting and JSON.parse-ing
the body and asserting on parsed.fd.
- Around line 1588-1590: Replace use of tmpdirSync() with the harness-provided
tempDir for isolated test dirs: change the unix socket path creation in the
Bun.serve test from const unix = join(tmpdirSync(), "serve-fd.sock"); to use
const unix = join(tempDir(), "serve-fd.sock"); and ensure tempDir is available
from the test harness (import or reference the harness helper if necessary).
- Around line 1552-1555: The test uses a fixed await Bun.sleep(50) before
asserting server.requestFD(savedRequest) is null, which is flaky; replace the
fixed delay with a condition-based wait that repeatedly checks
server.requestFD(savedRequest) until it returns null or a short timeout elapses.
Locate the test variables savedRequest and the call to server.requestFD(...) in
serve.test.ts and implement a small poll loop or reuse a test helper (e.g.,
waitFor) that awaits the condition (server.requestFD(savedRequest) === null)
with a sensible timeout and throws if not satisfied, then run the existing
expect after the wait.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 66bba3fe-6952-4339-acc1-938a10737505
📒 Files selected for processing (9)
packages/bun-types/serve.d.tssrc/bun.js/api/server.classes.tssrc/bun.js/api/server.zigsrc/bun.js/api/server/AnyRequestContext.zigsrc/bun.js/api/server/RequestContext.zigsrc/bun.js/bindings/node/JSNodeHTTPServerSocketPrototype.cppsrc/js/node/_http_server.tstest/js/bun/http/bun-server.test.tstest/js/bun/http/serve.test.ts
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@test/js/bun/http/bun-server.test.ts`:
- Around line 1335-1342: The test currently constructs a glibc-specific soname
("libc.${suffix}.6") and calls dlopen (libName) which fails on musl-based POSIX
systems; update the test around test.if(isPosix) so dlopen uses a dynamic
lookup/fallback instead of a hard-coded ".6" suffix: keep the macOS branch
as-is, but for other POSIX platforms attempt dlopen with multiple candidate
sonames (e.g., "libc.${suffix}.6", "libc.${suffix}", the musl soname variant)
inside a try/catch or use an existence check like the pattern in
test/js/bun/ffi/ffi.test.js, assign the successfully opened handle to libc (or
skip the test if none succeed), and then call libc.getsockname as before;
reference symbols: test.if(isPosix), libName, dlopen, and getsockname.
In `@test/js/bun/http/serve.test.ts`:
- Around line 1549-1550: The tests currently assert response.fd > 0 which
incorrectly rejects fd 0; update the assertions to allow non-negative FDs by
changing the matcher to assert fd >= 0 (use Jest's toBeGreaterThanOrEqual(0))
for the occurrences that reference response.fd and observedFd in serve.test.ts
(replace the expect(response.fd).toBeGreaterThan(0) checks on the lines near
where response and observedFd are used with
expect(response.fd).toBeGreaterThanOrEqual(0), leaving
expect(observedFd).toBe(response.fd) intact).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 135221e9-22a1-415a-8490-5934acc403e8
📒 Files selected for processing (6)
src/bun.js/api/server.zigsrc/bun.js/api/server/AnyRequestContext.zigsrc/bun.js/api/server/RequestContext.zigsrc/deps/uws/Response.zigtest/js/bun/http/bun-server.test.tstest/js/bun/http/serve.test.ts
There was a problem hiding this comment.
All my earlier feedback has been addressed and the implementation looks correct, but since this introduces a new public API surface (server.requestFD / socket.fd) that exposes raw OS descriptors and threads through core server Zig/C++ paths, it's worth a human sign-off on the API shape before merging.
Extended reasoning...
Overview
This PR adds three related APIs to expose the underlying OS socket file descriptor for HTTP requests: server.requestFD(request) on Bun.serve, a .fd getter on the C++ JSNodeHTTPServerSocket prototype, and a forwarding .fd getter on the node:http Duplex socket wrapper. It touches 10 files spanning the public TypeScript types, the generated server class definitions, server.zig, RequestContext/AnyRequestContext plumbing, the uWS Response wrapper, the C++ prototype bindings, and two test files with ~8 new tests including FFI round-trips against getsockname().
Security risks
Exposing raw OS fds is inherently a sharp tool — users can now close(), dup2(), or setsockopt() directly on descriptors that Bun's event loop owns, which could destabilize the server if misused. That's an intentional, documented capability (the motivating use case is getsockopt(TCP_INFO)), and it doesn't broaden the attack surface beyond what Bun.listen's existing socket.fd already permits, but it does mean the API name/shape and docs deserve a maintainer's eye. There are no injection, auth, or data-exposure risks; the read-only getter returns an integer derived from us_socket_get_fd.
Level of scrutiny
This is new public API on the flagship Bun.serve server object and on the node:http compatibility layer. Even though the implementation is a small, mechanical mirror of the existing requestIP pattern (and the HTTPS SSL*-vs-fd bug I flagged earlier was confirmed and fixed in cf06572 with a regression test), API additions are a design decision that a human reviewer should ratify — naming (requestFD vs requestFd), the -1 vs null sentinel split between the two surfaces, and whether .fd on the node:http socket should match Node's socket._handle.fd semantics are all judgment calls.
Other factors
All eight prior review threads (mine and CodeRabbit's) are resolved: the HTTPS fd fix, the bounded-poll replacement for Bun.sleep(50), the musl libc soname helper, the >= 0 assertions, the docstring clarification, and the test dedup in 2fea9ef. The bug-hunting pass on the current head found nothing. Test coverage is solid (HTTP, HTTPS regression, unix socket, node:http connection event, post-destroy sentinel). I'm deferring solely because this is a public API addition to core server code, not because of any outstanding correctness concern.
|
Final status — this PR is code-complete:
Each empty-commit retrigger just catches a different flake. Deferring to a maintainer for a CI re-run or flake-tolerant merge. |
101d7fb to
99eb404
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/bun.js/api/server/AnyRequestContext.zig`:
- Around line 90-110: The switch in AnyRequestContext.getFd currently omits the
H3-specific request context tags and therefore can hit the panic in the else
branch; update getFd to handle Pointer.Tag values for
HTTPSServer.H3RequestContext and DebugHTTPSServer.H3RequestContext (and any
equivalent H3 tags present in Pointer.Tag) and return null (or otherwise
dispatch safely) for those cases instead of falling through to the else panic;
locate the switch on self.tagged_pointer.tag() in the AnyRequestContext.getFd
function and add cases that call .as(HTTPSServer.H3RequestContext) /
.as(DebugHTTPSServer.H3RequestContext) as needed and return null (or appropriate
safe result).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 3960f34e-27f0-4721-94f5-d811f25015af
📒 Files selected for processing (5)
packages/bun-types/serve.d.tssrc/bun.js/api/server.classes.tssrc/bun.js/api/server.zigsrc/bun.js/api/server/AnyRequestContext.zigsrc/bun.js/api/server/RequestContext.zig
f974a4d to
175c339
Compare
There was a problem hiding this comment.
All earlier feedback (SSL* pointer, H3 panic, test gates, docstrings) has been addressed and nothing new turned up on this pass — but since this adds new public API surface to Bun.serve and node:http across Zig/C++/TS, I'd like a human to sign off on the API shape before merge.
Extended reasoning...
Overview
This PR adds three related APIs that expose the underlying OS socket file descriptor for HTTP server connections: server.requestFD(request) on Bun.serve (mirroring requestIP), a .fd getter on the native JSNodeHTTPServerSocket C++ prototype, and a forwarding .fd getter on the node:http Duplex socket wrapper. Plumbing spans server.zig / server.classes.ts (JS binding), AnyRequestContext.zig / RequestContext.zig (dispatch helper with H3 short-circuit), Response.zig (new getFd() that bypasses the SSL abstraction to reach us_socket_get_fd), JSNodeHTTPServerSocketPrototype.cpp (custom getter with Windows SOCKET widening), _http_server.ts, type definitions, and ~9 new tests across three files including FFI getsockname() round-trips for HTTP/HTTPS/unix and an H3 null-check.
Security risks
The fd is exposed read-only as a number; any actual syscalls require user-side FFI, which is already an unrestricted capability. This doesn't open a new sandbox boundary — the same descriptor is already reachable via Bun.listen's TCPSocket.fd and Node-compat paths. No injection, auth, or data-exposure surface introduced.
Level of scrutiny
Medium-high. This is not a config tweak or bug fix — it's a new, documented public API on a core runtime component (Bun.serve) with cross-platform native plumbing (POSIX fd vs. Windows SOCKET, SSL vs. plain, H1/H2 vs. H3). The review cycle already surfaced and fixed two real correctness bugs (HTTPS returning the SSL* heap pointer instead of an fd; H3 requests panicking on an unhandled tagged-pointer arm), which is a signal that the area is subtle enough to merit a maintainer's eyes on the final shape.
Other factors
All 11 prior inline threads (claude + coderabbit) are marked resolved; the current bug-hunt pass found nothing. Test coverage is solid — including the FFI getsockname(fd) === 0 proof for both HTTP and HTTPS that guards the SSL-pointer regression, and an H3 test guarding the panic regression. Remaining CI failures per the author's 04-23 note are unrelated flakes. I'm deferring solely because new public API on Bun.serve is a design decision a human should ratify, not because of any outstanding correctness concern.
|
Build 51068: 18 jobs "Expired" (not a single real test failure). Code status: unchanged since the last successful review. 9 tests pass locally (5 requestFD, 3 socket.fd, 1 H3). All review threads resolved. |
175c339 to
fa224f2
Compare
|
Build 57453 status check: still running — |
|
PR is mergeable on latest The red X on the latest build (#103028) is not this diff: the only test red on every retry is Ready for a maintainer sign-off on the public API shape ( |
6e3164b to
7a63103
Compare
7a63103 to
9c42632
Compare
|
Rebased onto latest The conflicts were Verified the full |
95b726b to
9873669
Compare
There was a problem hiding this comment.
No new issues found after the latest revisions — implementation and tests look solid, but since this introduces new public API surface (server.requestFD, socket.fd) I'll leave the API-shape sign-off to a maintainer as you requested.
Extended reasoning...
Overview
This PR adds three new public APIs that expose the underlying OS socket file descriptor for HTTP server connections: server.requestFD(request) on Bun.serve (mirroring requestIP), a .fd getter on the native JSNodeHTTPServerSocket C++ prototype, and a forwarding .fd getter on the node:http Duplex wrapper. It spans 11 files across the Rust server runtime (server_body.rs, RequestContext.rs, AnyRequestContext.rs, uws_sys/Response.rs), C++ JSC bindings, the node:http TS shim, public type definitions, and three test files (10 new tests including FFI getsockname() round-trips, TLS, unix sockets, HTTP/3, and arbitrary-receiver hardening).
Security risks
The feature itself is read-only fd exposure — it doesn't grant capabilities the process didn't already have (the fd is already open in-process; users could fish it out via /proc/self/fd or similar). The one security-adjacent concern during review — a type-confusion via uncheckedDowncast on a CustomAccessor getter callable with arbitrary receivers — was fixed (now uses dynamicDowncast with a -1 fallback, plus a subprocess regression test). The earlier HTTPS bug (returning the SSL* heap pointer instead of a real fd) was also fixed via us_socket_get_fd. I see no remaining injection, auth, or data-exposure surface.
Level of scrutiny
This warrants human review because it introduces new public API surface on Bun.Server and node:http sockets — naming, return-value semantics (null vs -1), and the H3-returns-null behavior are user-facing design choices a maintainer should ratify. The author explicitly flagged this ("Ready for a maintainer sign-off on the public API shape"). The native-code changes themselves are small and pattern-following (the Rust get_fd chain mirrors get_remote_socket_info; the C++ getter mirrors its 10 siblings), and the PR has been through multiple thorough review rounds with all threads resolved.
Other factors
Test coverage is strong (TCP, TLS, unix, H3, closed-context, FFI verification, arbitrary-receiver hardening). The PR survived a Zig→Rust migration rebase cleanly. All prior bot findings (mine and CodeRabbit's) have been addressed and resolved. The current bug-hunting pass found nothing new. The only reason not to auto-approve is the new-public-API criterion — not implementation quality.
9873669 to
b8fc7cc
Compare
There was a problem hiding this comment.
I reviewed the latest push (eb6c0a0) and found no issues — the pub(crate) visibility and comment-cop fixes look right, and the dynamicDowncast getter now matches its 13 siblings exactly. I'm not auto-approving because this adds new public API surface (server.requestFD() on all four Server classes, plus socket.fd on node:http), which per repo convention wants a maintainer sign-off on the API shape.
Checked: the get_fd chain routes through us_socket_get_fd (real fd, not SSL*) for both TCP and TLS; H3 short-circuits to null in AnyRequestContext::get_fd; the C++ getter guards !socket || isClosed(); Windows widens SOCKET to double. Test coverage spans TCP/TLS/unix/H3 plus the arbitrary-receiver regression and FFI getsockname() proof.
Extended reasoning...
Overview
This PR adds three complementary fd-exposure APIs: server.requestFD(request) on Bun.serve (all four server classes via server.classes.ts), a native .fd getter on JSNodeHTTPServerSocket (C++ prototype), and a forwarding .fd getter on the node:http Duplex wrapper. Implementation spans Rust (server_body.rs, RequestContext.rs, AnyRequestContext.rs, uws_sys/Response.rs), C++ (JSNodeHTTPServerSocketPrototype.cpp), built-in JS (_http_server.ts), types (serve.d.ts), and 10 tests across three files.
Security risks
The fd is read-only exposure of an already-open descriptor the process owns; no new privilege. The main risk class was type-confusion (arbitrary-receiver on the CustomAccessor getter) — fixed via dynamicDowncast with a regression test, and returning a stale/wrong value under TLS — fixed by bypassing get_native_handle (which returns SSL*) in favor of us_socket_get_fd. No injection, auth, or data-exposure surface.
Level of scrutiny
High: this is new user-facing API on Bun.Server and on node:http sockets, touching native FFI paths (uSockets, JSC bindings) across three languages and all platforms. The implementation itself is small and closely mirrors the existing requestIP chain, but API-shape decisions (method name requestFD, null vs -1 return convention, whether node:http socket.fd is desirable given Node.js has no such property) are the kind REVIEW.md flags as needing maintainer agreement before landing. The author explicitly requested maintainer sign-off on the API shape earlier in the thread.
Other factors
All prior review rounds (SSL* pointer bug, uncheckedDowncast type-confusion, unified-source header dependency, S008 opaque-deref convention, pub(crate) visibility, comment verbosity) have been addressed and the threads resolved. Test coverage is thorough — including an FFI getsockname() round-trip proving the fd is real, a TLS variant guarding the SSL* regression, and an H3 null assertion. The code quality is now consistent with its neighbors. The only reason not to approve is the new-public-API policy, not a correctness concern.
Adds three layers for accessing the OS file descriptor of a server-side HTTP connection, enabling per-connection syscalls like getsockopt(TCP_INFO), setsockopt(TCP_CORK), SO_RCVBUF, etc.: - Bun.serve: server.requestFD(request) returns the fd (number) for the request's underlying socket, mirroring the shape of server.requestIP(). Returns null if the request has already completed and its context has been torn down. - NodeHTTPServerSocket (the C++ wrapper used by Bun's node:http server): exposes a .fd custom getter, returning us_socket_get_fd(socket) or -1 when closed. - node:http server socket (the Duplex wrapper): exposes a .fd getter that forwards to the underlying NodeHTTPServerSocket's .fd, matching how Node.js users reach socket._handle.fd (returns -1 when the socket has been destroyed). On Windows, us_socket_get_fd returns a SOCKET (UINT_PTR); the .fd getter surfaces that value so FFI callers can pass it back to winsock APIs. unix-socket requests also report an fd, unlike requestIP which returns null for unix sockets. Closes #29597
- Critical: `requestFD` for HTTPS servers was returning the OpenSSL SSL*
heap pointer instead of an OS file descriptor. `Response.getNativeHandle`
calls `us_socket_get_native_handle(ssl=1)` which returns `s->ssl` for
TLS sockets; the subsequent `@intCast(@intFromPtr(...))` to a 32-bit fd
panics in debug builds ("integer does not fit in destination type") and
would return a garbage fd in release.
Added `Response.getFd()` / `AnyResponse.getFd()` that calls
`us_socket_get_fd` directly, mirroring what the new C++ NodeHTTPServerSocket
`.fd` getter already does. Renamed `RequestContext.getNativeHandle` →
`getFd` and `AnyRequestContext.getNativeHandle` → `getFd` to match.
Added a test that runs `getsockname()` against an HTTPS `requestFD` to
guard this regression.
- Replaced the fixed-time `Bun.sleep(50)` teardown wait in the
"returns null after the request context has been released" test with a
condition-based poll on `requestFD(savedRequest) === null`.
- Unix socket test: switched `tmpdirSync` to `tempDir`, switched to
`Connection: close` + resolving on the `close` event so the full HTTP
response is always assembled before parsing.
- `socket.fd becomes -1` test: removed the `Connection: close` header (the
server could close the socket before we attached `once('close', ...)`),
guarded `destroy()` with a `destroyed` check, and attached the close
listener before calling `destroy`.
- Switched both test files to harness `libcPathForDlopen()` so the `getsockname()` FFI tests also work on musl (Alpine) — the `libc.so.6` soname is glibc-only. - Assertions now accept fd 0 (`toBeGreaterThanOrEqual(0)`) since any non-negative integer is a legal fd; the -1 closed-socket sentinel is still rejected. - `requestFD` JSDoc now says "once the request has completed" instead of "if the socket was already closed" — the API gates on the request context lifecycle (same condition `requestIP` does), not on the underlying TCP socket, which is reused across requests under keep-alive.
The previous build had a flaky failure in test/js/third_party/grpc-js/test-resolver.test.ts on darwin-13-aarch64 (unrelated to this PR — the retry of the same job passed). Pushing this empty commit to retrigger CI.
Build 47337 had 3 unrelated flakes, all in pre-existing tests: - test/js/valkey/integration/complex-operations.test.ts (timeout, valkey service flake) - test/js/bun/net/socket.test.ts (windows aarch64, known-flaky file with multiple skipIf(isWindows) guards already) - test/js/sql/sql.test.ts (sql service flake) None of these test files are touched by this PR. All 5 shards of windows-11-aarch64-test-bun that did NOT hit socket.test.ts passed, confirming my tests work. Retriggering.
After the rebase onto main, two small tweaks are needed for the .fd getter to build against current API: - us_socket_get_fd is now declared in <libusockets.h>, transitively included here, so my local forward declaration conflicted. Removed. - Use uncheckedDowncast<JSNodeHTTPServerSocket> for the prototype getter's thisValue (matching sibling getters like jsNodeHttpServerSocketGetterClosed after the recent casting refactor) instead of jsCast, which is no longer the idiomatic accessor here. Release build now succeeds; all 8 tests still pass.
AnyRequestContext.getFd was a hand-rolled 4-arm switch with an `else => @panic` fallthrough. Main's Pointer union has 6 tags, not 4: HTTPSServer.H3RequestContext and DebugHTTPSServer.H3RequestContext. Calling server.requestFD(req) from an H3 fetch handler tripped the else branch and aborted the process. - Rewrote getFd to use the existing `dispatch()` helper that every sibling accessor in this file uses (it iterates Pointer.type_map so new tags are covered automatically). H3 branches out early via the same `if (comptime T.is_h3) return null;` idiom used by setRequest / getRequest — HTTP/3 multiplexes streams over one UDP socket, so there is no per-request OS fd to hand back. - Added the matching `.H3 => bun.invalid_fd` arm to AnyResponse.getFd, mirroring the adjacent AnyResponse.getNativeHandle. This was dead code via lazy comptime analysis, but it would fail to compile the first time anything routed through it. - New test in serve-http3.test.ts asserts requestFD returns null for an H3 request instead of crashing.
Two review nits addressed: - `requestFD` JSDoc now documents that HTTP/3 requests always return `null` (they multiplex over a single UDP socket). The H3 behavior was added in 8357c4f but the docstring wasn't updated to match. - The three `getsockname()` FFI tests are now gated on `isLinux || isMacOS` instead of `isPosix`. `libcPathForDlopen()` only handles linux/darwin today and throws on FreeBSD, so the tighter gate stops the tests from being enabled on a platform where they would fail immediately.
Main migrated `Bun.serve` host-fn bindings to Rust (bun_runtime
crate). The codegen in `server.classes.ts` emits a Rust dispatch that
expects `NewServer::do_request_fd`, but only the Zig `doRequestFD`
existed on this branch — build failed with:
error[E0599]: no associated function or constant named
`do_request_fd` found for struct `server::NewServer<SSL, DEBUG>`
Added the matching Rust methods, mirroring the existing Rust
`request_ip` path:
- `uws_sys::Response::get_fd` — calls `us_socket_get_fd` via
`downcast_socket` (same pattern as the Zig side).
- `uws_sys::AnyResponse::get_fd` — `.H3 => Fd::INVALID`, matches
`get_native_handle`.
- `RequestContext::get_fd` — null when `resp` is absent or fd invalid.
- `AnyRequestContext::get_fd` — uses the `dispatch!` helper with
`if T::IS_H3` returning None (same pattern as set_request).
- `server_body::do_request_fd` + `request_fd` — thin wrappers that
decode the Request arg and return JSValue::NULL or the fd via
`FdJsc::to_js_without_making_lib_uv_owned`.
The `fd` property is registered on JSNodeHTTPServerSocketPrototype as a
CustomAccessor without DOMAttribute, which means JSC does not validate
the receiver before invoking the getter. Using `uncheckedDowncast`
asserts in debug and type-confuses in release when called via e.g.
`Object.getOwnPropertyDescriptor(proto, 'fd').get.call({})` — confirmed
to abort (core dump) on the existing debug build.
Switch to `dynamicDowncast` + `if (!thisObject) return -1` so an
unrelated receiver gets -1 instead of tripping the security assertion
at `thisObject->socket`. Same defensive pattern I would expect from
any CustomAccessor on a hand-written prototype without DOMAttribute.
The sibling getters in this file share the same underlying defect;
limiting the change to `fd` keeps the fix scoped to what this PR adds.
Regression test added in bun-server.test.ts — runs in a subprocess so
an assertion abort surfaces as exit code 134 rather than killing the
test runner. Verified: the new test fails without this patch, passes
with it.
eb6c0a0 to
2d7ff2a
Compare
There was a problem hiding this comment.
I reviewed this PR again after a85fd16 and didn't find any bugs — all prior review feedback (the live_resp() UAF guard, pub(crate) visibility, comment-cop hits, and the stale libcPathForDlopen gate comments) has been addressed. Because this adds new public API surface (server.requestFD() on Bun.serve and .fd on node:http server sockets), a maintainer sign-off on the API shape would still be worthwhile.
What was reviewed:
RequestContext::get_fdnow gates onlive_resp()likeget_remote_socket_info/set_timeout, closing the streamed-response-end UAF window.- The C++
fdgetter usesdynamicDowncast+isClosed()like every sibling getter; Windows widensSOCKETto double. Response::get_fdroutes throughus_socket_t::opaque_mut(S008) so TLS returns a real fd, notSSL*; H3 short-circuits tonull.- 10 tests cover TCP/TLS/unix/H3/released-context/arbitrary-receiver, incl. FFI
getsockname()proof-of-real-fd.
Extended reasoning...
Overview
This PR adds three related fd-exposure APIs: server.requestFD(request) on Bun.serve (mirroring requestIP), a .fd custom getter on the C++ JSNodeHTTPServerSocket prototype, and a forwarding .fd getter on the node:http Duplex wrapper. Files touched span Rust (server_body.rs, RequestContext.rs, AnyRequestContext.rs, uws_sys/Response.rs), C++ (JSNodeHTTPServerSocketPrototype.cpp), codegen input (server.classes.ts), builtin JS (_http_server.ts), type declarations, and three test files with 10 new tests.
Security risks
Exposing a raw OS fd to user JS is inherently a capability grant — user code can setsockopt/close/dup it via FFI. That's the stated purpose (issue #29597 wants getsockopt(TCP_INFO)), and Bun already exposes .fd on Bun.listen TCP sockets, so this is consistent with existing precedent rather than a new class of exposure. No injection/auth surface. The one memory-safety concern (deref of a freed us_socket_t in the ended_response window) was fixed in 6c281cd by switching to live_resp().
Level of scrutiny
High — native code in the HTTP server hot path, plus new permanent public API. The implementation has been through many review rounds and every raised issue was addressed; the code now structurally mirrors the established requestIP chain end-to-end. What remains is an API-design question (naming, whether requestFD is the right shape vs. exposing it on the Request, whether node:http .fd should match Node's socket._handle.fd semantics), which is a maintainer call rather than a correctness question.
Other factors
Test coverage is thorough: TCP, HTTPS (guarding the SSL*-vs-fd regression), unix socket, released-context → null, HTTP/3 → null, node:http request handler + connection event, post-destroy → -1, arbitrary-receiver hardening (spawned subprocess so a debug assert would surface), and two FFI getsockname() end-to-end proofs. The last commit (a85fd16) addressed my final open nit. No bugs surfaced in this run's bug-hunting pass.
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-08-22. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Closes #29597
Background
From the issue: an HTTP proxy needs to call
getsockopt(TCP_INFO)on each connection to get kernel-reported byte and segment counts.socket.bytesRead/bytesWrittenare insufficient because they don't include TCP/IP overhead. The syscall needs a real OS file descriptor.What this adds
Three complementary APIs, chosen to parallel patterns that already exist:
1.
server.requestFD(request)— new on Bun.serveMirrors
server.requestIP(request)— same lookup (request.request_context→ response → native socket handle), returns the fd as a number ornullif the request context has been torn down.Unlike
requestIP, this works for unix-socket servers too (the fd exists regardless of address family).2.
socket.fdonNodeHTTPServerSocket(C++ prototype)The native wrapper that Bun's
node:httpserver uses for each connection now exposes a.fdcustom getter pointing atus_socket_get_fd, the same underlying callTCPSocket(Bun.listen) already uses for its.fd. Returns-1when the socket is closed.3.
socket.fdon Bun'snode:httpDuplex socketThe
NodeHTTPServerSocketDuplex wrapper exposed to user code (viahttp.createServer((req, res) => …)and theconnectionevent) gets a matching.fdgetter that forwards to the underlying C++ handle. Returns-1after the socket has been destroyed.Verification
The tests include an end-to-end FFI check that calls
getsockname(fd, ...)on the returned fd and assertsrc === 0, proving the fd is a real OS descriptor — not just a synthetic number. This covers bothserver.requestFDandnode:httpsocket.fd.Platforms
On Windows,
us_socket_get_fdreturns aSOCKET(UINT_PTR). The C++ getter and Rust path both widen that to a JS number so winsock APIs receive the full value, matching howTCPSocket.getFDalready does this viato_js_without_making_lib_uv_owned.Files touched
src/runtime/server/server.classes.ts— declaresrequestFDonServer.src/runtime/server/server_body.rs— implementsdo_request_fd/request_fd.src/runtime/server/RequestContext.rs,AnyRequestContext.rs— add theget_fdhelper, with an HTTP/3 short-circuit that returnsnull(H3 multiplexes streams over one UDP socket, so there is no per-request fd).src/uws_sys/Response.rs— addsget_fd, which goes straight tous_socket_get_fdso TLS connections return a real fd rather than theSSL*pointer.src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp— adds the.fdgetter (usesdynamicDowncast, so an arbitrary receiver returns-1instead of asserting).src/js/node/_http_server.ts— adds.fdto the Duplex wrapper.packages/bun-types/serve.d.ts— types forrequestFD.test/js/bun/http/serve.test.ts— 5 tests forserver.requestFD(TCP, released context, FFIgetsockname, HTTPS/TLS fd vs SSL pointer, unix socket).test/js/bun/http/bun-server.test.ts— 4 tests fornode:httpsocket.fd(incl. FFIgetsocknameand arbitrary-receiver hardening).test/js/bun/http/serve-http3.test.ts— 1 test asserting HTTP/3 returnsnull.Rebase note
The server implementation migrated from Zig to Rust on
mainwhile this PR was open. Rebasing ontomainproduced modify/delete conflicts on the reference.zigfiles (server.zig,RequestContext.zig,AnyRequestContext.zig,uws_sys/Response.zig), which no longer exist there. Those edits were dropped; the shipping logic lives in the.rsfiles listed above, which rebased cleanly.no test proof · iteration 28 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/bun/http/serve.test.ts, test/js/bun/http/bun-server.test.ts