Skip to content

sql: treat a BunFile tls option as the CA certificate to verify the server against - #41761

Merged
Jarred-Sumner merged 1 commit into
mainfrom
robobun/9d65c10e/sql-tls-bunfile
Sep 30, 2026
Merged

Jarred-Sumner merged 1 commit into
mainfrom
robobun/9d65c10e/sql-tls-bunfile

Conversation

@robobun

@robobun robobun commented Sep 6, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • new Bun.SQL({ url, tls: Bun.file("ca.pem") }) is a form the public type advertises (tls?: Bun.BunFile | TLSOptions | …). It negotiated TLS but never verified the server certificate and never read the file. A wrong CA, a nonexistent path and a non-PEM file all connected. The ssl alias behaved the same.
  • Cause: parseOptions (src/js/internal/sql/shared.ts:2027) kept the Blob as the tls object. A Blob has no ca, caFile or rejectUnauthorized, so the sslmode was only raised to require.

Fix

  • A BunFile tls or ssl option becomes { ca: file }. The existing rules then select verify-full (an explicit verify-ca is kept), add serverName, and read the file when the connection is created. A wrong CA, a missing file (ENOENT) and a non-file Blob (ERR_INVALID_ARG_TYPE) now reject.
  • The alternative was to throw for a BunFile and drop it from the type. test/js/sql/sql-mysql.test.ts already passes tls: Bun.file(ca.pem) for the TLS image with this meaning, so this PR implements it. That suite now runs with verify-full.
  • Verified: test/js/sql/adapter-env-var-precedence.test.ts. Also tls-sql.test.ts and the new MySQL test against local TLS servers with the repo certificates, and bun-types.test.ts.

Background

  • Bun.SQL folds the tls/ssl options, URL ?sslmode= and PGSSLMODE into one sslMode plus a TLSOptions object for the native connection.
  • require encrypts but does not authenticate the server. verify-ca checks the chain against the CA. verify-full also checks the hostname.
  • TLSOptions.ca already accepts a BunFile. SSLConfig reads it when the connection object is constructed (src/runtime/socket/SSLConfig.rs:75).
Notes
  • Reproduced on 1.4.3-canary (f42e980) against a python pg-over-TLS stub whose leaf chains to root.pem only. Before: tls: Bun.file(other.pem), tls: Bun.file('/nonexistent.pem'), ssl: Bun.file(other.pem) and tls: new Blob([..]) all connected and ran the query. After: UNABLE_TO_VERIFY_LEAF_SIGNATURE, ENOENT, UNABLE_TO_VERIFY_LEAF_SIGNATURE, ERR_INVALID_ARG_TYPE; tls: Bun.file(root.pem) connects with verification on.
  • The new adapter-env-var-precedence.test.ts block fails on 1.4.3-canary (sslMode is 2, tls is the Blob) and passes with this change.
  • MySQL shares the normaliser. Checked against a local MariaDB with test/js/sql/mysql-tls/ssl certs: right CA connects (verify-full, IP:127.0.0.1 SAN), wrong CA rejects with SELF_SIGNED_CERT_IN_CHAIN, missing file ENOENT.
  • The postgres docker test uses ?sslmode=verify-ca for the positive case because docker-tls/server.crt names 127.0.0.1 as a DNS SAN, not an IP SAN, and a bare BunFile leaves no room for serverName. The MySQL certificate has an IP SAN, so that suite verifies the hostname too.
  • tls-sql.test.ts: 34 pass against a local postgres 17 started with the postgres_tls certificates and hba rules (BUN_TEST_SERVICE_postgres_tls=...). The new test fails on 1.4.3-canary against the same server (the wrong-CA connection succeeds).
  • Docs: added a short "Custom CA Certificates" section to docs/runtime/sql.mdx and a JSDoc note on tls.

no test proof · iteration 0 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/sql/adapter-env-var-precedence.test.ts

…erver against

`new SQL({ tls: Bun.file(path) })` is a form the public type advertises.
The option normaliser kept the Blob as the tls object. A Blob has no
`ca`, so the sslmode stayed at `require`: TLS was negotiated but the
server certificate was never verified and the file was never read.

Map a BunFile `tls` (or `ssl`) to `{ ca: file }`. That selects
verify-full, reads the file when the connection is created, and fails
the connection for a wrong CA, a missing file, or a non-file Blob.
@coderabbitai

coderabbitai Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

  • Run on-demand review

On-demand reviews are free for the next 14 days. After that, they cost $0.25 per reviewed file.

Or wait 31 seconds for your next included review.

Check out review usage here.

View limit details

Limit details: You’ve used all 10 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Essentials

Run ID: a2b1c9e4-4f71-4e5f-937a-a15a9fd38f49

📥 Commits

Reviewing files that changed from the base of the PR and between d316760 and e4bf079.

📒 Files selected for processing (6)
  • docs/runtime/sql.mdx
  • packages/bun-types/sql.d.ts
  • src/js/internal/sql/shared.ts
  • test/js/sql/adapter-env-var-precedence.test.ts
  • test/js/sql/sql-mysql.test.ts
  • test/js/sql/tls-sql.test.ts

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added the claude label Sep 6, 2026
@robobun

robobun commented Sep 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status

Reproduced on 1.4.3-canary (f42e980) against a local pg-over-TLS stub whose certificate chains to root.pem only:

tls: Bun.file('other.pem')  (WRONG CA)    CONNECTED, query ran
tls: Bun.file('/nonexistent.pem')         CONNECTED, query ran
ssl: Bun.file('other.pem')  (WRONG CA)    CONNECTED, query ran
control tls: {ca: Bun.file('other.pem')}  rejected: UNABLE_TO_VERIFY_LEAF_SIGNATURE
control tls: 'verify-full'                rejected: UNABLE_TO_VERIFY_LEAF_SIGNATURE

With this branch:

tls: Bun.file('other.pem')  (WRONG CA)    rejected: UNABLE_TO_VERIFY_LEAF_SIGNATURE
tls: Bun.file('/nonexistent.pem')         rejected: ENOENT
tls: Bun.file('root.pem')   (RIGHT CA)    CONNECTED, query ran
ssl: Bun.file('other.pem')  (WRONG CA)    rejected: UNABLE_TO_VERIFY_LEAF_SIGNATURE

Tests run locally with the debug build:

  • test/js/sql/adapter-env-var-precedence.test.ts: 94 pass (the new BunFile block fails on 1.4.3-canary).
  • test/js/sql/tls-sql.test.ts: 34 pass against a local postgres 17 with the postgres_tls certificates. The new test fails on 1.4.3-canary against the same server.
  • The new sql-mysql.test.ts TLS test passes against a local MariaDB with the mysql-tls certificates.
  • test/integration/bun-types/bun-types.test.ts: 21 pass.

CI (build 111833): 179 of 181 jobs passed. sql-mysql.test.ts ran against the mysql_tls container (315 pass, 0 fail), so the "MySQL with TLS" suite passes with verify-full. The two red jobs are unrelated to this diff: test/js/bun/util/password.test.ts (RSS leak threshold, debian x64) and test/js/node/test/parallel/test-crypto-dh-leak.js (x64-asan, also red on main). Ready for review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I reviewed this PR and didn't find any bugs. The 3-line runtime change is a strict security hardening — a BunFile tls option previously fell through to sslMode = require (encrypt without verifying), and now selects verify-full with the file as the CA — but because it changes TLS certificate-verification semantics for database connections, a human look at the API decision is still worthwhile.

What was reviewed:

  • Traced the new $inheritsBlob branch through the downstream sslMode < verify_ca promotion (line 2119) and serverName injection (line 2125) — { ca: file } correctly reaches verify_full, and an explicit ?sslmode=verify-ca is preserved because the promotion guard is <, not <=.
  • Confirmed the change only tightens: no path that previously verified now skips verification; the fallback else branch is unchanged for non-Blob objects.
  • Tests follow file-local conventions (tempDir, container-gated, await using, negative case asserts a specific error code); the unit test covers both tls/ssl keys and both adapters.
Extended reasoning...

Overview

The PR adds one else if ($inheritsBlob(tlsOption)) branch to parseOptions() in src/js/internal/sql/shared.ts so that new SQL({ tls: Bun.file("ca.pem") }) is normalized to { ca: <file> } before the existing sslMode/serverName logic runs. Bun.BunFile was already a member of the tls?: union in packages/bun-types/sql.d.ts; this PR makes the runtime honor that shape and adds a JSDoc example plus a docs section. Three test additions land in existing files: a parser-level unit test (both adapters, both tls/ssl keys, URL-sslmode preservation) and two Docker-gated integration tests (postgres and mysql_tls) that assert a matching CA connects and an unrelated CA is rejected with a certificate-verification error code.

Security risks

This is a TLS certificate-verification change, but it is strictly a hardening. Before the change, a BunFile fell into the generic tls = tlsOption branch: the Blob has no .ca/.caFile/.rejectUnauthorized, so the promotion at line 2119 did not fire and explicitTls only raised the mode to require — the server certificate was never verified and the file was never read. After the change, tls becomes { ca: file }, the existing guard promotes sslMode to verify_full, serverName is injected from the hostname, and a mismatched CA or missing file now rejects. I could not construct a path where the new branch weakens verification: it only fires when tlsOption is a Blob (via the tamper-safe $inheritsBlob intrinsic), and the else fallback for plain option objects is untouched. The ?sslmode=verify-ca preservation works because the promotion guard is sslMode < SSLMode.verify_ca, so an already-verifying mode is not overwritten.

Level of scrutiny

Per the approval guidelines, changes to security-sensitive code paths (crypto/TLS) should not be auto-approved even when small and correct-looking. The PR description explicitly frames this as an API-design decision ("the alternative was to throw for a BunFile and drop it from the type"), which is exactly the kind of choice a maintainer should confirm. The runtime diff is tiny and the behavior is well-covered by both a unit test that fails on the old build (sslMode was 2, tls was the Blob) and negative-path integration tests, so the human review needed here is about the design, not correctness.

Other factors

The change follows src/js conventions (uses the $inheritsBlob intrinsic rather than instanceof Blob, single-line explanatory comment). Tests are placed in existing files, use tempDir/await using/container gating consistent with neighbors, cover the ssl alias and the mysql adapter (the normalizer is shared), and assert specific error codes rather than bare rejection. No CODEOWNERS entry covers these paths. No prior review activity on the PR.

Jarred-Sumner pushed a commit that referenced this pull request Sep 25, 2026
… IP host (#42766)

### Problem

- `new Bun.SQL("postgres://u@[::1]:5432/db?sslmode=verify-full")`
rejects a certificate that has `IP:::1` with
`ERR_TLS_CERT_ALTNAME_INVALID`. `mysql://` does the same.
- `parseOptions` copies `URL.hostname`, brackets kept, into
`tls.serverName` (`src/js/internal/sql/shared.ts:2159`). Both adapters
check the certificate against that text, and `"[::1]"` is not an IP
address.
- Both adapters send an IP literal as SNI (`127.0.0.1`). RFC 6066
section 3 forbids that.

### Fix

- `SSLConfig::server_name_bytes()` (`src/sql_jsc/jsc.rs`) returns the
name through `bun_core::ip_address::strip_ipv6_brackets`. The identity
checks of both adapters read the name there.
- New `SSLConfig::sni()` returns no name for an IP literal, bracketed or
not. Both `adopt_tls` sites use it. libpq and fetch send none either.
- Verified: `test/js/sql/sql-tls-ip-literal-host.test.ts` (new, 8
cases). 6 fail on main 0d73249, all pass here.

### Background

- `sslmode=verify-full` checks that the certificate names the host. An
IP host matches only an IP SAN entry, and only as a bare address
(`check_x509_server_identity`, `src/boringssl/lib.rs:452`).
- SNI is the host name a TLS client sends in its first message.
`adopt_tls` sets it.
- Considered a strip in `parseOptions` (the first version). That was a
second copy of `strip_ipv6_brackets`, which fetch, RedisClient and
Bun.connect use, and it changed `sql.options`.

### Downsides

- Bun.SQL sends no SNI for an IP-literal name. A TLS proxy that routes
on such a value loses it.
- A zone-scoped address (`hostname: "::1%lo"`) still fails
`verify-full`, and without brackets it still goes out as SNI:
`is_ip_address` accepts no `%zone`.
- Cost per TLS connection: one `is_ip_address` call (at most 45 bytes,
no allocation) and a bracket check at each name read.

<details><summary>Notes</summary>

- History of this PR. The first version removed the brackets in
`parseOptions` (JS). Main then gained
`bun_core::ip_address::strip_ipv6_brackets` and moved every other client
to it. A review noted that the JS helper disagreed with it (`[db]` lost
its brackets too). aa4d699 moves the fix to the two native accessors
and restores `parseOptions` to its state on main. So this PR no longer
touches `src/js/internal/sql/shared.ts`, and it does not conflict with
#42054 or #41761, which edit that block.
- `sql.options.tls.serverName` and `sql.options.hostname` keep the
brackets, as on main. Only the native reads see the bare address.
- When this PR opened (canary 09bb546), Bun.SQL also accepted a
certificate whose only SAN is `DNS:[::1]`, and a hostname mismatch gave
an `Error` with an empty `code` and `message`. Main changed both since:
#43873 makes a name that is not a hostname match no certificate name,
and #43694 rejects the mismatch inside the handshake with
`ERR_TLS_CERT_ALTNAME_INVALID`. This PR changes neither.
- Probed on the debug build with a mock TLS server on 127.0.0.1 and an
explicit `tls.serverName`. `"[::1]"` and `"::1"` under `verify-full`:
connects, no SNI. `"[db]"` under `verify-full`:
`ERR_TLS_CERT_ALTNAME_INVALID`, as on main. `"[fe80::1%lo]"` under
`require`: no SNI. `"fe80::1%lo"` and `"127.1"` under `require`: sent as
SNI, because `is_ip_address` takes neither as an IP literal (#43979).
`"localhost"`: sent as SNI.
- Observed on main 0d73249: peer SNI `127.0.0.1` for host
`127.0.0.1`. With this change: none.
- The cases that dial `[::1]` gate on `isIPv6()` (Buildkite Linux has no
IPv6 loopback). The other cases run on every lane. One of them dials
127.0.0.1 with `tls.serverName: "[::1]"`, so every lane checks a
bracketed name against the `IP:::1` entry.
- Two gaps in the same `parseOptions` block are on main and stay out of
this PR: `tls.servername` (the Node spelling) is ignored, which #42054
owns, and `tls: true` without an sslmode derives no `serverName`, which
#26369 tracks. A `BunFile` given as `tls` with an explicit sslmode loses
the file there, which #41761 owns.
- Same bug class as #30668, which #30674 fixed for fetch and WebSocket.
The dial path already removes the brackets
(`src/uws_sys/socket.rs:791`).
- Other suites run on the merged debug build (main 601af5a):
`postgres-pgsslmode-env`, `sql-mysql-tls-plaintext-injection`, all of
`adapter-env-var-precedence`, and
`test/js/bun/net/tls-reject-before-client-cert.test.ts` (121 pass, 9
skip). I ran the new file 40 times on the earlier head: 320 of 320 cases
pass. The container TLS suites (`tls-sql`, `local-sql`) need Docker and
run in CI.

</details>

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 0 · platform-specific test(s) that do not
run on this machine, deferring to CI, which covers all platforms:
test/js/sql/adapter-env-var-precedence.test.ts

<!-- robobun:evidence:end -->
@Jarred-Sumner
Jarred-Sumner merged commit 3b7ee8e into main Sep 30, 2026
7 of 9 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the robobun/9d65c10e/sql-tls-bunfile branch September 30, 2026 22:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants