fix(core): fall back to the classical TLS handshake on networks that drop the post-quantum one

This commit is contained in:
Luke Parker 2026-11-18 12:47:33 +10:00
parent 63bfe62c91
commit c269eec01f
8 changed files with 504 additions and 3 deletions

View file

@ -1,8 +1,12 @@
import { tlsFallbackFetch } from "@opencode/util/tls-fallback"
import type { Sender, Tls } from "./client-tls.js"
// These requests skip the shared fetch, so they need its handshake fallback here.
const fetch = tlsFallbackFetch() as typeof globalThis.fetch
// Bun's fetch takes the client certificate per request.
export function sender(tls: Tls): Sender | undefined {
return { fetch: globalThis.fetch, init: { tls } }
return { fetch, init: { tls } }
}
export * as ClientTls from "./client-tls.bun.js"

View file

@ -4,6 +4,7 @@ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"
import * as NodePath from "@effect/platform-node/NodePath"
import { Effect, FileSystem, Layer, Path } from "effect"
import { FetchHttpClient, HttpClient } from "effect/http"
import { tlsFallbackFetch } from "../tls-fallback.js"
import { makeGlobalNode } from "./app-node.js"
export const filesystem = makeGlobalNode({ service: FileSystem.FileSystem, layer: NodeFileSystem.layer, deps: [] })
@ -12,14 +13,26 @@ export const path = makeGlobalNode({ service: Path.Path, layer: NodePath.layer,
export type Fetch = (input: Request | string | URL, init?: RequestInit) => Promise<Response>
/**
* The fetch behind `httpClient`, AI SDK providers and remote MCP servers: `fetch` when given, so an embedder can route requests through
* e.g. a Service Binding, otherwise the `FetchHttpClient.Fetch` in scope when the graph is built.
* e.g. a Service Binding, otherwise the `FetchHttpClient.Fetch` in scope when the graph is built. The runtime's own fetch
* falls back to the classical TLS handshake for hosts whose network path drops the post-quantum one.
*/
export const fetchLayer = (fetch?: Fetch) =>
Layer.effect(
FetchHttpClient.Fetch,
Effect.gen(function* () {
// Bun's `typeof fetch` adds `preconnect`, which nothing here calls.
return fetch ? (fetch as typeof globalThis.fetch) : yield* FetchHttpClient.Fetch
if (fetch) return fetch as typeof globalThis.fetch
const ambient = yield* FetchHttpClient.Fetch
if (ambient !== globalThis.fetch) return ambient
const log = Effect.runForkWith(yield* Effect.context())
return tlsFallbackFetch({
onFallback: (origin) =>
log(
Effect.logWarning(
"The network drops the post-quantum TLS handshake to this host; using the classical handshake",
).pipe(Effect.annotateLogs({ origin })),
),
}) as typeof globalThis.fetch
}),
)
export const httpFetch = makeGlobalNode({ service: FetchHttpClient.Fetch, layer: fetchLayer(), deps: [] })

View file

@ -0,0 +1,156 @@
// Bun's TLS ClientHello carries a post-quantum key share (X25519MLKEM768), which makes it about 1.5 KB: too large for one
// TCP segment. Some networks drop a ClientHello that arrives in two segments, so the handshake to an affected host never
// completes: the request hangs, or fails with ECONNRESET, while clients that send a small ClientHello get through.
//
// This fetch notices that for one host at a time. When a request gets no response, it opens two fresh connections to the
// host, one with each handshake. Only when the standard handshake fails and the classical one completes does the host
// switch to the classical handshake, for the request in flight and the ones after it. Certificate verification and the
// cipher are unchanged; the connection only loses protection against a recorded session being decrypted by a future
// quantum computer.
/** Bun's default key exchange groups without the post-quantum one. The ClientHello shrinks from about 1500 to 280 bytes. */
export const CLASSICAL_GROUPS = "X25519:P-256:P-384"
type Fetch = (input: Request | string | URL, init?: RequestInit) => Promise<Response>
export interface TlsFallbackOptions {
/** The fetch to send with. Defaults to the runtime's. */
readonly fetch?: Fetch
/** How long a request waits for a response before its host is checked. */
readonly stall?: number
/** How long a check gives each handshake. */
readonly probe?: number
/** How long a host that passed a check is left alone. */
readonly trust?: number
/** How long a host stays on the classical handshake before the standard one is tried again. */
readonly retry?: number
/** Called each time a check moves a host to the classical handshake. */
readonly onFallback?: (origin: string) => void
}
// Failures of a connection that never produced a response. A handshake that is reset reports the first two.
const CONNECTION_CODES = new Set(["ECONNRESET", "EPROTO", "ETIMEDOUT", "ConnectionClosed"])
interface Host {
readonly classical: boolean
readonly checked: number
readonly check?: Promise<boolean>
}
/** A fetch that falls back to the classical TLS handshake for hosts whose network path drops the post-quantum one. */
export function tlsFallbackFetch(options: TlsFallbackOptions = {}): Fetch {
const base = options.fetch ?? globalThis.fetch
// Only Bun's fetch takes the key exchange groups per request.
if (typeof Bun === "undefined") return base
const stall = options.stall ?? 2_000
const probe = options.probe ?? 3_000
const trust = options.trust ?? 10 * 60_000
const retry = options.retry ?? 60 * 60_000
const hosts = new Map<string, Host>()
// Any response proves the handshake completed. `keepalive: false` forces a new connection, so a pooled one can't
// answer for it, and the probe takes the request's own route: its proxy, certificate authority and client certificate.
const handshakes = (origin: string, init: BunFetchRequestInit | undefined, tls: BunFetchRequestInit["tls"]) =>
base(origin, {
method: "HEAD",
redirect: "manual",
keepalive: false,
proxy: init?.proxy,
tls,
signal: AbortSignal.timeout(probe),
} as BunFetchRequestInit).then(
(response) => {
void response.body?.cancel()
return true
},
() => false,
)
const check = (origin: string, init: BunFetchRequestInit | undefined) => {
const host = hosts.get(origin)
if (host?.check) return host.check
const running = Promise.all([
handshakes(origin, init, init?.tls),
handshakes(origin, init, classical(init).tls),
]).then(([standard, small]) => {
// Neither completing says nothing about the handshake (no network, host down), so the next failure checks again.
if (!standard && !small) {
hosts.delete(origin)
return false
}
hosts.set(origin, { classical: !standard, checked: Date.now() })
if (!standard && !host?.classical) options.onFallback?.(origin)
return !standard
})
hosts.set(origin, { classical: host?.classical ?? false, checked: host?.checked ?? 0, check: running })
return running
}
const blocked = (origin: string, init: BunFetchRequestInit | undefined) => {
const host = hosts.get(origin)
if (host && !host.check && Date.now() - host.checked < trust) return Promise.resolve(host.classical)
return check(origin, init)
}
return (input, init) => {
const url = input instanceof Request ? input.url : String(input)
const request = init as BunFetchRequestInit | undefined
if (!url.startsWith("https:") || (request?.tls as { ecdhCurve?: string } | undefined)?.ecdhCurve)
return base(input, init)
const origin = new URL(url).origin
const host = hosts.get(origin)
if (host?.classical) {
// Runs beside the request, so a host that is still filtered costs nothing.
if (!host.check && Date.now() - host.checked >= retry) void check(origin, request)
return base(input, classical(request))
}
// The first attempt may have consumed a streamed body, so only the requests after it take the classical handshake.
const replayable =
(input instanceof Request ? input.body === null : true) && !(init?.body instanceof ReadableStream)
return new Promise<Response>((resolve, reject) => {
const first = new AbortController()
let open = true
const settle = () => {
if (!open) return false
open = false
clearTimeout(timer)
return true
}
const timer = setTimeout(() => {
void blocked(origin, request).then((yes) => {
if (!yes || !replayable || !settle()) return
first.abort()
resolve(base(input, classical(request)))
})
}, stall)
base(input, {
...init,
signal: AbortSignal.any(
[first.signal, init?.signal, input instanceof Request ? input.signal : undefined].filter(
(signal) => signal != null,
),
),
}).then(
(response) => {
if (settle()) resolve(response)
},
(error: { code?: unknown } | undefined) => {
if (!open) return
if (typeof error?.code !== "string" || !CONNECTION_CODES.has(error.code)) {
settle()
reject(error)
return
}
void blocked(origin, request).then((yes) => {
if (!settle()) return
if (yes && replayable) return resolve(base(input, classical(request)))
reject(error)
})
},
)
})
}
}
const classical = (init: BunFetchRequestInit | undefined) =>
({ ...init, tls: { ...init?.tls, ecdhCurve: CLASSICAL_GROUPS } }) as BunFetchRequestInit

View file

@ -0,0 +1,116 @@
// A TLS server behind a TCP relay that treats a large ClientHello the way the filtering networks in #60399 do. On those
// networks a ClientHello that spans two TCP segments (anything past about 1400 bytes) never reaches the server, while a
// ClientHello that fits one segment passes. The relay sees a byte stream, not segments, so it applies the same rule by
// size: it reads the first TLS record and drops or resets the connection when the record is larger than `LIMIT`.
import path from "node:path"
const LIMIT = 1200
const GROUPS: Record<number, string> = {
0x0017: "P-256",
0x0018: "P-384",
0x001d: "X25519",
0x11ec: "X25519MLKEM768",
}
export interface Hello {
/** Size of the ClientHello on the wire, with its record header. */
readonly bytes: number
/** The groups the client sent a key share for. */
readonly shares: ReadonlyArray<string>
readonly passed: boolean
}
export type FilterMode = "drop" | "reset" | "pass"
interface Relay {
upstream?: Bun.Socket
hello?: Hello
readonly pending: Uint8Array[]
}
const fixture = (name: string) => Bun.file(path.join(import.meta.dir, "tls", name)).text()
export async function tlsFilter(handler: (request: Request) => Response | Promise<Response>) {
const ca = await fixture("localhost.cert.pem")
const hellos: Hello[] = []
const state: { mode: FilterMode } = { mode: "drop" }
const server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
tls: { cert: ca, key: await fixture("localhost.key.pem") },
fetch: handler,
})
const relay = Bun.listen<Relay>({
hostname: "127.0.0.1",
port: 0,
socket: {
open(socket) {
socket.data = { pending: [] }
},
data(socket, chunk) {
if (socket.data.upstream) return void socket.data.upstream.write(chunk)
socket.data.pending.push(Uint8Array.from(chunk))
if (socket.data.hello) return
const hello = parse(Buffer.concat(socket.data.pending), state.mode)
if (!hello) return
socket.data.hello = hello
hellos.push(hello)
if (hello.passed) return void forward(socket, server.port!)
// A dropped ClientHello gets no answer at all; the connection stays open until the client gives up.
if (state.mode === "reset") socket.terminate()
},
close(socket) {
socket.data.upstream?.end()
},
error() {},
},
})
return {
ca,
hellos,
origin: `https://localhost:${relay.port}`,
set mode(mode: FilterMode) {
state.mode = mode
},
async [Symbol.asyncDispose]() {
relay.stop(true)
await server.stop(true)
},
}
}
async function forward(socket: Bun.Socket<Relay>, port: number) {
const upstream = await Bun.connect({
hostname: "127.0.0.1",
port,
socket: {
data: (_, chunk) => void socket.write(chunk),
close: () => void socket.end(),
error: () => void socket.end(),
},
})
socket.data.upstream = upstream
socket.data.pending.splice(0).forEach((chunk) => upstream.write(chunk))
}
// Reads the record and handshake headers, skips to the extensions, and collects the key_share entries.
function parse(data: Buffer, mode: FilterMode): Hello | undefined {
if (data.length < 5) return undefined
const bytes = data.readUInt16BE(3) + 5
if (data.length < bytes) return undefined
const session = 9 + 2 + 32
const ciphers = session + 1 + data[session]!
const compression = ciphers + 2 + data.readUInt16BE(ciphers)
const extensions = compression + 1 + data[compression]!
const shares: string[] = []
for (let at = extensions + 2; at + 4 <= bytes; at += 4 + data.readUInt16BE(at + 2)) {
if (data.readUInt16BE(at) !== 0x0033) continue
const end = at + 4 + data.readUInt16BE(at + 2)
for (let entry = at + 6; entry + 4 <= end; entry += 4 + data.readUInt16BE(entry + 2)) {
const group = data.readUInt16BE(entry)
shares.push(GROUPS[group] ?? `0x${group.toString(16)}`)
}
}
return { bytes, shares, passed: mode === "pass" || bytes <= LIMIT }
}

View file

@ -0,0 +1,11 @@
-----BEGIN CERTIFICATE-----
MIIBnDCCAUGgAwIBAgIUb7hvzkdtQnhIGzjwbgU23Olwjj4wCgYIKoZIzj0EAwIw
FDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTI2MTExODAyMzc1OVoYDzIxMjYxMDI1
MDIzNzU5WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcqhkjOPQIBBggqhkjO
PQMBBwNCAASgwXgSB6cUnF8fAhGg3JVOCe8E7qyEPixcd7v4vCzA1Iw535wgoNky
NY9Nvuy8p4OVDtxSVU7kiCOQP26NY5uqo28wbTAdBgNVHQ4EFgQUWGFvSP9geibG
LlAseo1tmPSgmLUwHwYDVR0jBBgwFoAUWGFvSP9geibGLlAseo1tmPSgmLUwDwYD
VR0TAQH/BAUwAwEB/zAaBgNVHREEEzARgglsb2NhbGhvc3SHBH8AAAEwCgYIKoZI
zj0EAwIDSQAwRgIhAPju3D8UBoHfn+ZqVCJAM6zpb68Q0DJD6vavCcPASPCvAiEA
kboSGT5G88lmfdweoyfhndhuKYxY9x17P6MF0LdasiM=
-----END CERTIFICATE-----

View file

@ -0,0 +1,5 @@
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQga/hCUYCMLqREoUOh
b5ooUbNeR68rCN54YR0wM9Q4Ts+hRANCAASgwXgSB6cUnF8fAhGg3JVOCe8E7qyE
Pixcd7v4vCzA1Iw535wgoNkyNY9Nvuy8p4OVDtxSVU7kiCOQP26NY5uq
-----END PRIVATE KEY-----

View file

@ -0,0 +1,180 @@
import { describe, expect, test } from "bun:test"
import { CLASSICAL_GROUPS, tlsFallbackFetch } from "../src/tls-fallback.js"
import { tlsFilter } from "./fixtures/tls-filter.js"
// The checks wait on real handshakes through the relay, so the windows are real time: long enough for a loopback
// handshake on a loaded runner, short enough that a dropped one is given up on quickly.
const timing = { stall: 100, probe: 1_000 }
const origin = (seen: string[]) =>
tlsFilter(async (request) => {
if (request.method === "HEAD") return new Response(null)
const body = await request.text()
seen.push(`${request.method} ${new URL(request.url).pathname} ${body}`)
return new Response(`echo ${body}`)
})
const post = (ca: string, body: string, extra?: RequestInit) =>
({ method: "POST", body, tls: { ca }, ...extra }) as RequestInit
describe("tlsFallbackFetch", () => {
test("the runtime's standard handshake does not pass a filter that drops a large ClientHello", async () => {
const seen: string[] = []
await using filter = await origin(seen)
const error = await fetch(
`${filter.origin}/chat`,
post(filter.ca, "hi", { signal: AbortSignal.timeout(500) }),
).catch((cause: Error) => cause)
expect(error).toMatchObject({ name: "TimeoutError" })
expect(seen).toEqual([])
expect(filter.hellos).toHaveLength(1)
expect(filter.hellos[0]!.shares).toContain("X25519MLKEM768")
expect(filter.hellos[0]!.bytes).toBeGreaterThan(1400)
expect(filter.hellos[0]!.passed).toBe(false)
})
test("sends the request once, on the classical handshake, when the standard one is dropped", async () => {
const seen: string[] = []
const fallbacks: string[] = []
await using filter = await origin(seen)
const send = tlsFallbackFetch({ ...timing, onFallback: (host) => fallbacks.push(host) })
const response = await send(`${filter.origin}/chat`, post(filter.ca, "hi"))
expect(response.status).toBe(200)
expect(await response.text()).toBe("echo hi")
expect(seen).toEqual(["POST /chat hi"])
expect(fallbacks).toEqual([filter.origin])
const passed = filter.hellos.filter((hello) => hello.passed)
expect(passed.length).toBeGreaterThan(0)
// One TCP segment carries at least 1220 bytes on any IPv6 path and 1360 on the affected lines in #60661.
expect(Math.max(...passed.map((hello) => hello.bytes))).toBeLessThan(600)
expect(passed.flatMap((hello) => hello.shares)).not.toContain("X25519MLKEM768")
})
test("sends the request once when the standard handshake is reset", async () => {
const seen: string[] = []
await using filter = await origin(seen)
filter.mode = "reset"
const send = tlsFallbackFetch(timing)
const response = await send(`${filter.origin}/chat`, post(filter.ca, "hi"))
expect(await response.text()).toBe("echo hi")
expect(seen).toEqual(["POST /chat hi"])
})
test("keeps a host on the classical handshake without trying the standard one again", async () => {
const seen: string[] = []
await using filter = await origin(seen)
const send = tlsFallbackFetch(timing)
await send(`${filter.origin}/first`, post(filter.ca, "a")).then((response) => response.text())
const before = filter.hellos.length
const response = await send(`${filter.origin}/second`, post(filter.ca, "b", { keepalive: false }))
expect(await response.text()).toBe("echo b")
expect(seen).toEqual(["POST /first a", "POST /second b"])
expect(filter.hellos.slice(before).every((hello) => hello.passed)).toBe(true)
})
test("leaves a host that completes the standard handshake alone, even when it answers slowly", async () => {
const requests: string[] = []
const fallbacks: string[] = []
const answer = Promise.withResolvers<void>()
await using filter = await tlsFilter(async (request) => {
if (request.method === "HEAD") return new Response(null)
requests.push(await request.text())
await answer.promise
return new Response("late")
})
filter.mode = "pass"
const send = tlsFallbackFetch({ ...timing, onFallback: (host) => fallbacks.push(host) })
const pending = send(`${filter.origin}/chat`, post(filter.ca, "hi"))
// The check runs once the request has waited `stall`: both of its handshakes reach the relay.
await until(() => filter.hellos.length >= 3)
answer.resolve()
const response = await pending
expect(await response.text()).toBe("late")
expect(requests).toEqual(["hi"])
expect(fallbacks).toEqual([])
expect(filter.hellos[0]!.shares).toContain("X25519MLKEM768")
})
test("still verifies the server certificate on the classical handshake", async () => {
const seen: string[] = []
await using filter = await origin(seen)
const send = tlsFallbackFetch(timing)
await send(`${filter.origin}/first`, post(filter.ca, "a")).then((response) => response.text())
// Without the fixture's certificate authority the server's self-signed certificate is untrusted.
const error = await send(`${filter.origin}/second`, { method: "POST", body: "b" }).catch((cause: Error) => cause)
expect(error).toMatchObject({ code: "DEPTH_ZERO_SELF_SIGNED_CERT" })
expect(seen).toEqual(["POST /first a"])
})
test("does not resend a streamed body, and moves the next request to the classical handshake", async () => {
const seen: string[] = []
await using filter = await origin(seen)
const send = tlsFallbackFetch(timing)
const stream = new Blob(["streamed"]).stream()
const error = await send(
`${filter.origin}/upload`,
post(filter.ca, "", { body: stream, signal: AbortSignal.timeout(timing.stall + timing.probe + 500) }),
).catch((cause: Error) => cause)
const response = await send(`${filter.origin}/chat`, post(filter.ca, "hi"))
expect(error).toMatchObject({ name: "TimeoutError" })
expect(await response.text()).toBe("echo hi")
expect(seen).toEqual(["POST /chat hi"])
})
test("returns a host to the standard handshake once the network passes it", async () => {
const seen: string[] = []
await using filter = await origin(seen)
const send = tlsFallbackFetch({ ...timing, retry: 0 })
await send(`${filter.origin}/first`, post(filter.ca, "a")).then((response) => response.text())
filter.mode = "pass"
// This request still takes the classical handshake and starts the check that clears the host.
await send(`${filter.origin}/second`, post(filter.ca, "b")).then((response) => response.text())
await until(async () => {
const before = filter.hellos.length
await send(`${filter.origin}/again`, post(filter.ca, "c", { keepalive: false })).then((response) =>
response.text(),
)
return filter.hellos.slice(before).some((hello) => hello.shares.includes("X25519MLKEM768"))
})
})
test("leaves a caller's own key exchange groups alone", async () => {
const seen: string[] = []
await using filter = await origin(seen)
filter.mode = "pass"
const send = tlsFallbackFetch(timing)
const response = await send(`${filter.origin}/chat`, {
method: "POST",
body: "hi",
tls: { ca: filter.ca, ecdhCurve: "P-256" },
} as RequestInit)
expect(await response.text()).toBe("echo hi")
expect(filter.hellos.map((hello) => hello.shares)).toEqual([["P-256"]])
expect(CLASSICAL_GROUPS).toBe("X25519:P-256:P-384")
})
})
async function until(condition: () => boolean | Promise<boolean>) {
const deadline = Date.now() + 10_000
while (!(await condition())) {
if (Date.now() > deadline) throw new Error("condition not reached within 10s")
await Bun.sleep(10)
}
}

View file

@ -92,6 +92,22 @@ Fix it in one of two ways:
- Export the inspection certificate authority as a PEM file and trust it with `NODE_EXTRA_CA_CERTS`, as shown in
[Certificates](#certificates).
## Networks that drop the TLS handshake
OpenCode's TLS handshake includes a post-quantum key share, which makes its first message too large for one network
packet. Some networks drop a handshake that arrives in two packets, so requests to an affected host hang or fail with
`ECONNRESET`, while `curl` reaches the same host.
OpenCode detects this for each host and switches that host to the classical handshake. The first request to an affected
host takes about five seconds longer, and later requests are not delayed. The server certificate is still verified. The
service log records the switch:
```text
The network drops the post-quantum TLS handshake to this host; using the classical handshake origin=https://opencode.ai
```
OpenCode tries the post-quantum handshake again every hour and returns to it when the network passes it.
## Client certificates
Set `settings.tls` on a provider whose gateway requires mutual TLS. Its model requests present the certificate, and the