Repository navigation
sql: treat a BunFile tls option as the CA certificate to verify the server against - #41761
Conversation
…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.
|
Warning Review limit reached
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. View limit detailsLimit details: You’ve used all 10 included reviews currently available. Review configuration: ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Essentials Run ID: 📒 Files selected for processing (6)
Comment |
|
Status Reproduced on 1.4.3-canary (f42e980) against a local pg-over-TLS stub whose certificate chains to With this branch: Tests run locally with the debug build:
CI (build 111833): 179 of 181 jobs passed. |
There was a problem hiding this comment.
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
$inheritsBlobbranch through the downstreamsslMode < verify_capromotion (line 2119) andserverNameinjection (line 2125) —{ ca: file }correctly reachesverify_full, and an explicit?sslmode=verify-cais preserved because the promotion guard is<, not<=. - Confirmed the change only tightens: no path that previously verified now skips verification; the fallback
elsebranch 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 bothtls/sslkeys 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.
… 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 -->
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. Thesslalias behaved the same.parseOptions(src/js/internal/sql/shared.ts:2027) kept the Blob as thetlsobject. A Blob has noca,caFileorrejectUnauthorized, so the sslmode was only raised torequire.Fix
tlsorssloption becomes{ ca: file }. The existing rules then selectverify-full(an explicitverify-cais kept), addserverName, and read the file when the connection is created. A wrong CA, a missing file (ENOENT) and a non-fileBlob(ERR_INVALID_ARG_TYPE) now reject.test/js/sql/sql-mysql.test.tsalready passestls: Bun.file(ca.pem)for the TLS image with this meaning, so this PR implements it. That suite now runs withverify-full.test/js/sql/adapter-env-var-precedence.test.ts. Alsotls-sql.test.tsand the new MySQL test against local TLS servers with the repo certificates, andbun-types.test.ts.Background
Bun.SQLfolds thetls/ssloptions, URL?sslmode=andPGSSLMODEinto onesslModeplus aTLSOptionsobject for the native connection.requireencrypts but does not authenticate the server.verify-cachecks the chain against the CA.verify-fullalso checks the hostname.TLSOptions.caalready accepts aBunFile.SSLConfigreads it when the connection object is constructed (src/runtime/socket/SSLConfig.rs:75).Notes
root.pemonly. Before:tls: Bun.file(other.pem),tls: Bun.file('/nonexistent.pem'),ssl: Bun.file(other.pem)andtls: 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.adapter-env-var-precedence.test.tsblock fails on 1.4.3-canary (sslModeis 2,tlsis the Blob) and passes with this change.test/js/sql/mysql-tls/sslcerts: right CA connects (verify-full,IP:127.0.0.1SAN), wrong CA rejects withSELF_SIGNED_CERT_IN_CHAIN, missing fileENOENT.?sslmode=verify-cafor the positive case becausedocker-tls/server.crtnames127.0.0.1as a DNS SAN, not an IP SAN, and a bare BunFile leaves no room forserverName. 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 thepostgres_tlscertificates 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/runtime/sql.mdxand a JSDoc note ontls.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