Files
bun.sh/test
Alan Stott 7848648e09 fix: clean up raw TCP socket on TLS upgrade close (#26766)
## Summary

Fixes #12117, #24118, #25948

When a TCP socket is upgraded to TLS via `tls.connect({ socket })`,
`upgradeTLS()` creates **two** `TLSSocket` structs — a TLS wrapper and a
raw TCP wrapper. Both are `markActive()`'d and `ref()`'d. On close, uws
fires `onClose` through the **TLS context only**, so the TLS wrapper is
properly cleaned up, but the raw TCP wrapper's `onClose` never fires.
Its `has_pending_activity` stays `true` forever and its `ref_count` is
never decremented, **leaking one raw `TLSSocket` per upgrade cycle**.

This affects any code using the `tls.connect({ socket })` "starttls"
pattern:
- **MongoDB Node.js driver** — SDAM heartbeat connections cycle TLS
upgrades every ~10s, causing unbounded memory growth in production
- **mysql2** TLS upgrade path
- Any custom starttls implementation

### The fix

Adds a `defer` block in `NewWrappedHandler(true).onClose` that cleans up
the raw TCP socket when the TLS socket closes:

```zig
defer {
    if (!this.tcp.socket.isDetached()) {
        this.tcp.socket.detach();
        this.tcp.has_pending_activity.store(false, .release);
        this.tcp.deref();
    }
}
```

- **`isDetached()` guard** — skips cleanup if the raw socket was already
closed through another code path (e.g., JS-side `handle.close()`)
- **`socket.detach()`** — marks `InternalSocket` as `.detached` so
`isClosed()` returns `true` safely (the underlying `us_socket_t` is
freed when uws closes the TLS context)
- **`has_pending_activity.store(false)`** — allows JSC GC to collect the
raw socket's JS wrapper
- **`deref()`** — balances the `ref()` from `upgradeTLS`; the remaining
ref is the implicit one from JSC (`ref_count.init() == 1`). When GC
later calls `finalize()` → `deref()`, ref_count hits 0 and `deinit()`
runs the full cleanup chain (markInactive, handlers, poll_ref,
socket_context)

`markInactive()` is intentionally **not** called in the defer — it must
run inside `deinit()` to avoid double-freeing the handlers struct.

### Why Node.js doesn't have this bug

Node.js implements TLS upgrades purely in JavaScript/C++ with OpenSSL,
where the TLS wrapper takes ownership of the underlying socket. There is
no separate "raw socket wrapper" that needs independent cleanup.

## Test Results

### Regression test
```
$ bun test test/js/node/tls/node-tls-upgrade-leak.test.ts
 1 pass, 0 fail
```
Creates 20 TCP→TLS upgrade cycles, closes all connections, runs GC,
asserts `TLSSocket` count stays below 10.

### Existing TLS test suite (all passing)
```
node-tls-upgrade.test.ts      1 pass
node-tls-connect.test.ts     24 pass, 1 skip
node-tls-server.test.ts      21 pass
node-tls-cert.test.ts        25 pass, 3 todo
renegotiation.test.ts          6 pass
```

### MongoDB TLS scenario (patched Bun, 4 minutes)
```
Baseline: RSS=282.4 MB | Heap Used=26.4 MB
Check #4:  RSS=166.7 MB | Heap Used=24.2 MB — No TLSSocket growth. RSS DECREASED.
```

## Test plan

- [x] New regression test passes (`node-tls-upgrade-leak.test.ts`)
- [x] All existing TLS tests pass (upgrade, connect, server, cert,
renegotiation)
- [x] MongoDB TLS scenario shows zero `TLSSocket` accumulation
- [x] Node.js control confirms leak is Bun-specific
- [ ] CI passes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2026-02-16 23:42:57 -08:00
..
2026-01-18 14:07:30 -08:00
2026-01-07 23:39:10 -08:00

Tests

Finding tests

Tests are located in the test/ directory and are organized using the following structure:

  • test/
    • js/ - tests for JavaScript APIs.
    • cli/ - tests for commands, configs, and stdout.
    • bundler/ - tests for the transpiler/bundler.
    • regression/ - tests that reproduce a specific issue.
    • harness.ts - utility functions that can be imported from any test.

The tests in test/js/ directory are further categorized by the type of API.

  • test/js/
    • bun/ - tests for Bun-specific APIs.
    • node/ - tests for Node.js APIs.
    • web/ - tests for Web APIs, like fetch().
    • first_party/ - tests for npm packages that are built-in, like undici.
    • third_party/ - tests for npm packages that are not built-in, but are popular, like esbuild.

Running tests

To run a test, use Bun's built-in test command: bun test.

bun test # Run all tests
bun test js/bun # Only run tests in a directory
bun test sqlite.test.ts # Only run a specific test

If you encounter lots of errors, try running bun install, then trying again.

Writing tests

Tests are written in TypeScript (preferred) or JavaScript using Jest's describe(), test(), and expect() APIs.

import { describe, test, expect } from "bun:test";
import { gcTick } from "harness";

describe("TextEncoder", () => {
  test("can encode a string", async () => {
    const encoder = new TextEncoder();
    const actual = encoder.encode("bun");
    await gcTick();
    expect(actual).toBe(new Uint8Array([0x62, 0x75, 0x6E]));
  });
});

If you are fixing a bug that was reported from a GitHub issue, remember to add a test in the test/regression/ directory.

// test/regression/issue/02005.test.ts

import { it, expect } from "bun:test";

it("regex literal should work with non-latin1", () => {
  const text = "这是一段要替换的文字";
  expect(text.replace(new RegExp("要替换"), "")).toBe("这是一段的文字");
  expect(text.replace(/要替换/, "")).toBe("这是一段的文字");
});

In the future, a bot will automatically close or re-open issues when a regression is detected or resolved.

Zig tests

These tests live in various .zig files throughout Bun's codebase, leveraging Zig's builtin test keyword.

Currently, they're not run automatically nor is there a simple way to run all of them. We will make this better soon.

TypeScript

Test files should be written in TypeScript. The types in packages/bun-types should be updated to support all new APIs. Changes to the .d.ts files in packages/bun-types will be immediately reflected in test files; no build step is necessary.

Writing a test will often require using invalid syntax, e.g. when checking for errors when an invalid input is passed to a function. TypeScript provides a number of escape hatches here.

  • // @ts-expect-error - This should be your first choice. It tells TypeScript that the next line should fail typechecking.
  • // @ts-ignore - Ignore the next line entirely.
  • // @ts-nocheck - Put this at the top of the file to disable typechecking on the entire file. Useful for autogenerated test files, or when ignoring/disabling type checks an a per-line basis is too onerous.