mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
fix(core): present client certificates only on model requests and never to an HTTPS proxy
This commit is contained in:
parent
aa6a9d2c0e
commit
8331d74646
7 changed files with 84 additions and 31 deletions
|
|
@ -9,6 +9,7 @@ import { Global } from "@opencode/util/global"
|
|||
import { AppProcess } from "@opencode/util/process"
|
||||
import { Config } from "./config.js"
|
||||
import { ConfigDiscovery } from "./config/discovery.js"
|
||||
import { WebSocketConstructor } from "./effect/websocket-constructor.js"
|
||||
import { Wildcard } from "./util/wildcard.js"
|
||||
|
||||
export interface Rule {
|
||||
|
|
@ -102,7 +103,10 @@ export function configured(options?: Options) {
|
|||
|
||||
export const node = configured()
|
||||
|
||||
/** Fetch-backed HTTP client that presents the matching client certificate on each HTTPS request. */
|
||||
/**
|
||||
* Wraps the fetch-backed HTTP client so each HTTPS request to a matching host presents its client certificate. Only
|
||||
* model requests use it: tools such as webfetch and URLs from project config must not borrow the machine's identity.
|
||||
*/
|
||||
export const httpClientLayer = Layer.effect(
|
||||
HttpClient.HttpClient,
|
||||
Effect.gen(function* () {
|
||||
|
|
@ -112,13 +116,18 @@ export const httpClientLayer = Layer.effect(
|
|||
Effect.gen(function* () {
|
||||
const rule = match(yield* certificates.rules(), request.url)
|
||||
if (!rule) return yield* effect
|
||||
const host = new URL(request.url).hostname
|
||||
const fail = (description: string) =>
|
||||
new HttpClientError.HttpClientError({ reason: new HttpClientError.TransportError({ request, description }) })
|
||||
if (typeof Bun === "undefined")
|
||||
return yield* new HttpClientError.HttpClientError({
|
||||
reason: new HttpClientError.TransportError({
|
||||
request,
|
||||
description: `A client certificate is configured for ${new URL(request.url).hostname}, but this runtime cannot present one`,
|
||||
}),
|
||||
})
|
||||
return yield* fail(`A client certificate is configured for ${host}, but this runtime cannot present one`)
|
||||
// Bun also uses the request's TLS options for an HTTPS proxy's own handshake, which would present the
|
||||
// certificate to the proxy.
|
||||
const proxy = WebSocketConstructor.proxy(request.url)
|
||||
if (proxy?.startsWith("https:"))
|
||||
return yield* fail(
|
||||
`A client certificate is configured for ${host}, which would also be sent to the HTTPS proxy. Add ${host} to NO_PROXY or use an http:// proxy`,
|
||||
)
|
||||
const fetch = yield* FetchHttpClient.Fetch
|
||||
return yield* effect.pipe(
|
||||
Effect.provideService(
|
||||
|
|
@ -137,6 +146,8 @@ export const httpClientLayer = Layer.effect(
|
|||
// Fetch would follow a redirect with the same TLS options, presenting the certificate to whatever
|
||||
// host the server names. Only callers that handle redirects themselves see the 3xx.
|
||||
redirect: init?.redirect === "manual" ? "manual" : "error",
|
||||
// Pin the proxy decision checked above so Bun cannot choose a different one.
|
||||
proxy: proxy ?? false,
|
||||
}),
|
||||
{ preconnect: fetch.preconnect },
|
||||
),
|
||||
|
|
@ -145,6 +156,7 @@ export const httpClientLayer = Layer.effect(
|
|||
}),
|
||||
)
|
||||
}),
|
||||
).pipe(Layer.provide(FetchHttpClient.layer))
|
||||
)
|
||||
|
||||
export const httpClient = makeGlobalNode({ service: HttpClient.HttpClient, layer: httpClientLayer, deps: [node] })
|
||||
/** No machine configuration: for runtimes such as workerd that have no host filesystem. */
|
||||
export const empty = Layer.succeed(Service, Service.of({ rules: () => Effect.succeed([]) }))
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { FetchHttpClient, HttpClient } from "effect/http"
|
|||
import { Socket } from "effect/socket"
|
||||
import { makeGlobalNode } from "@opencode/util/effect/app-node"
|
||||
import { httpClient } from "@opencode/util/effect/app-node-platform"
|
||||
import { ClientCertificate } from "../client-certificate.js"
|
||||
import { WebSocketConstructor } from "./websocket-constructor.js"
|
||||
|
||||
// Bun's fetch ends a request after five quiet minutes, before provider routes' own header and chunk timeouts.
|
||||
|
|
@ -20,8 +21,8 @@ const withoutBunTimeout = Layer.effect(
|
|||
|
||||
export const requestExecutor = makeGlobalNode({
|
||||
service: RequestExecutor.Service,
|
||||
layer: RequestExecutor.layer.pipe(Layer.provide(withoutBunTimeout)),
|
||||
deps: [httpClient],
|
||||
layer: RequestExecutor.layer.pipe(Layer.provide(withoutBunTimeout), Layer.provide(ClientCertificate.httpClientLayer)),
|
||||
deps: [httpClient, ClientCertificate.node],
|
||||
})
|
||||
|
||||
export const llmClient = makeGlobalNode({ service: LLMClient.Service, layer: LLMClient.layer, deps: [requestExecutor] })
|
||||
|
|
|
|||
|
|
@ -19,9 +19,11 @@ type Environment = Readonly<Record<string, string | undefined>>
|
|||
const environmentValue = (environment: Environment, name: string) =>
|
||||
environment[name] ?? environment[name.toLowerCase()]
|
||||
|
||||
const secure = (url: URL) => url.protocol === "wss:" || url.protocol === "https:"
|
||||
|
||||
const bypassesProxy = (url: URL, value: string | undefined) => {
|
||||
if (!value) return false
|
||||
const port = url.port || (url.protocol === "wss:" ? "443" : "80")
|
||||
const port = url.port || (secure(url) ? "443" : "80")
|
||||
const hostname = url.hostname.toLowerCase()
|
||||
return value.split(/[\s,]+/).some((entry) => {
|
||||
if (!entry) return false
|
||||
|
|
@ -33,15 +35,15 @@ const bypassesProxy = (url: URL, value: string | undefined) => {
|
|||
})
|
||||
}
|
||||
|
||||
/** The proxy the environment selects for a WebSocket or HTTP URL, if any. */
|
||||
const proxy = (value: string, environment: Environment = process.env) => {
|
||||
const url = new URL(value)
|
||||
if (["127.0.0.1", "localhost", "::1"].includes(url.hostname)) return undefined
|
||||
if (bypassesProxy(url, environmentValue(environment, "NO_PROXY"))) return undefined
|
||||
const protocolProxy = url.protocol === "wss:" ? "WSS_PROXY" : "WS_PROXY"
|
||||
const standardProxy = url.protocol === "wss:" ? "HTTPS_PROXY" : "HTTP_PROXY"
|
||||
const protocolProxy = url.protocol.startsWith("ws") ? (secure(url) ? "WSS_PROXY" : "WS_PROXY") : undefined
|
||||
return (
|
||||
environmentValue(environment, protocolProxy) ??
|
||||
environmentValue(environment, standardProxy) ??
|
||||
(protocolProxy ? environmentValue(environment, protocolProxy) : undefined) ??
|
||||
environmentValue(environment, secure(url) ? "HTTPS_PROXY" : "HTTP_PROXY") ??
|
||||
environmentValue(environment, "ALL_PROXY")
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,11 +3,15 @@ import fs from "fs/promises"
|
|||
import { afterAll, beforeAll, describe, expect, test } from "bun:test"
|
||||
import { Effect, Layer, Option, Schema } from "effect"
|
||||
import { ConfigNetwork } from "@opencode/schema/config/network"
|
||||
import { FetchHttpClient, HttpClient } from "effect/http"
|
||||
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"
|
||||
import { RequestExecutor } from "@opencode/ai/route"
|
||||
import { ClientCertificate } from "@opencode/core/client-certificate"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { LayerNodePlatform } from "@opencode/core/effect/app-node-platform"
|
||||
import { httpClient } from "@opencode/util/effect/app-node-platform"
|
||||
import { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { Global } from "@opencode/util/global"
|
||||
import { withEnv } from "./fixture/env"
|
||||
import { tmpdir } from "./fixture/tmpdir"
|
||||
import { testEffect } from "./lib/effect"
|
||||
|
||||
|
|
@ -76,7 +80,7 @@ const certificate = (hosts: string[]) => ({
|
|||
})
|
||||
|
||||
const layer = () =>
|
||||
AppNodeBuilder.build(LayerNode.group([ClientCertificate.httpClient, ClientCertificate.node]), [
|
||||
AppNodeBuilder.build(LayerNode.group([LayerNodePlatform.requestExecutor, httpClient, ClientCertificate.node]), [
|
||||
ClientCertificate.node.replace(ClientCertificate.configured({ system: path.join(root.path, "system") })),
|
||||
Global.node.replace(
|
||||
Global.layerWith({ config: path.join(root.path, "global"), home: path.join(root.path, "home") }),
|
||||
|
|
@ -84,12 +88,25 @@ const layer = () =>
|
|||
])
|
||||
|
||||
// The test CA only verifies the server; trust for real gateways comes from the system store or NODE_EXTRA_CA_CERTS.
|
||||
const trusted = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
effect.pipe(
|
||||
Effect.provideService(
|
||||
FetchHttpClient.Fetch,
|
||||
Object.assign(
|
||||
(input: Parameters<typeof fetch>[0], init?: BunFetchRequestInit) =>
|
||||
fetch(input, { ...init, tls: { ca, ...init?.tls } }),
|
||||
{ preconnect: fetch.preconnect },
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
/** A model request, the only kind that presents client certificates. */
|
||||
const get = (host: string, pathname = "/") =>
|
||||
Effect.gen(function* () {
|
||||
const client = yield* HttpClient.HttpClient
|
||||
const response = yield* client.get(`https://${host}:${server.port}${pathname}`)
|
||||
const executor = yield* RequestExecutor.Service
|
||||
const response = yield* executor.execute(HttpClientRequest.get(`https://${host}:${server?.port ?? 443}${pathname}`))
|
||||
return yield* response.text
|
||||
}).pipe(Effect.provideService(FetchHttpClient.RequestInit, { tls: { ca } } as BunFetchRequestInit))
|
||||
}).pipe(trusted)
|
||||
|
||||
describe("ClientCertificate", () => {
|
||||
test("accepts hostnames and rejects URLs, ports, and wildcard-only patterns", () => {
|
||||
|
|
@ -117,6 +134,26 @@ describe("ClientCertificate", () => {
|
|||
}).pipe(Effect.provide(layer())),
|
||||
)
|
||||
|
||||
itWithOpenSSL("does not present the certificate on requests other than model requests", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* write("system", certificate(["localhost"]))
|
||||
const client = yield* HttpClient.HttpClient
|
||||
expect(yield* Effect.flip(client.get(`https://localhost:${server.port}/`).pipe(trusted))).toBeDefined()
|
||||
}).pipe(Effect.provide(layer())),
|
||||
)
|
||||
|
||||
it.live("refuses to send the certificate through an HTTPS proxy", () =>
|
||||
withEnv(
|
||||
{ HTTPS_PROXY: "https://proxy.test", https_proxy: undefined, NO_PROXY: undefined, no_proxy: undefined },
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
yield* write("system", certificate(["llm.corp.test"]))
|
||||
const error = yield* Effect.flip(get("llm.corp.test"))
|
||||
expect(String(error)).toContain("NO_PROXY")
|
||||
}),
|
||||
).pipe(Effect.provide(layer())),
|
||||
)
|
||||
|
||||
itWithOpenSSL("fails instead of following a redirect with the certificate", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* write("system", certificate(["localhost", "127.0.0.1"]))
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ import { Bus } from "@opencode/core/bus"
|
|||
import { EventLogger } from "@opencode/core/event-logger"
|
||||
import { FileSystemSearch } from "@opencode/core/filesystem/search"
|
||||
import { Credential } from "@opencode/core/credential"
|
||||
import { ClientCertificate } from "@opencode/core/client-certificate"
|
||||
import { Config } from "@opencode/core/config"
|
||||
import { PermissionSaved } from "@opencode/core/permission/saved"
|
||||
import { PtyTicket } from "@opencode/core/pty/ticket"
|
||||
|
|
@ -130,7 +129,6 @@ function makeRoutes<AuthError, AuthServices>(
|
|||
FileWatch.node.replace(FileWatch.configured({ enabled: options.fs?.filewatcher })),
|
||||
FileSystemSearch.node.replace(FileSystemSearch.configured({ fff: options.fs?.fff })),
|
||||
Global.node.replace(Global.layerWith(options.config?.directory ? { config: options.config.directory } : {})),
|
||||
httpClient.replace(ClientCertificate.httpClient),
|
||||
Config.node.replace(
|
||||
Config.configured({
|
||||
project: options.config?.project,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
export * as ServerWorkerd from "./workerd"
|
||||
|
||||
import { Effect, Layer } from "effect"
|
||||
import { ClientCertificate } from "@opencode/core/client-certificate"
|
||||
import { ConfigPluginSource } from "@opencode/core/config/plugin/source"
|
||||
import { Database } from "@opencode/core/database/database"
|
||||
import { sqliteLayer } from "@opencode/core/database/sqlite.workerd"
|
||||
|
|
@ -12,9 +13,7 @@ import { Pty } from "@opencode/core/pty"
|
|||
import { Snapshot } from "@opencode/core/snapshot"
|
||||
import { Vcs } from "@opencode/core/vcs"
|
||||
import { CrossSpawnSpawner } from "@opencode/util/cross-spawn-spawner"
|
||||
import { httpClient } from "@opencode/util/effect/app-node-platform"
|
||||
import type { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { FetchHttpClient } from "effect/http"
|
||||
import { ServerFetch } from "./fetch"
|
||||
import type { ServerOptions } from "./options"
|
||||
|
||||
|
|
@ -87,8 +86,8 @@ export function replacements(options: Options): LayerNode.Replacements {
|
|||
// Precompiled (internal and SDK) plugins only: no plugin-directory scan, npm
|
||||
// install, or import of plugin code from disk.
|
||||
ConfigPluginSource.node.replace(ConfigPluginSource.empty),
|
||||
// workerd has no machine configuration to read client certificates from, and its fetch cannot present one.
|
||||
httpClient.replace(FetchHttpClient.layer),
|
||||
// workerd has no machine configuration to read client certificates from.
|
||||
ClientCertificate.node.replace(ClientCertificate.empty),
|
||||
]
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -75,8 +75,9 @@ opencode service start
|
|||
## Client certificates
|
||||
|
||||
When a gateway requires mutual TLS, list the hosts that should receive a client certificate under
|
||||
`network.client_certificates`. OpenCode presents the matching certificate on HTTPS requests to those hosts, such as model
|
||||
requests and model catalogs, and to no other host.
|
||||
`network.client_certificates`. OpenCode presents the matching certificate on model requests to those hosts, and to no
|
||||
other host. Other requests, such as web fetches and instruction or skill URLs from configuration, never present it, so a
|
||||
fetched page cannot use the machine's identity.
|
||||
|
||||
```jsonc title="/etc/opencode/opencode.json"
|
||||
{
|
||||
|
|
@ -110,8 +111,11 @@ This is a machine setting, so OpenCode reads it only from managed and global con
|
|||
within a minute.
|
||||
|
||||
Requests that present a client certificate do not follow redirects, because a redirect would present it to the host the
|
||||
server names. The server's own certificate is still verified against the system trust store; add a private certificate
|
||||
authority with `NODE_EXTRA_CA_CERTS`, described in [Certificates](#certificates).
|
||||
server names. They also fail when an `https://` proxy applies, because the proxy's own TLS handshake would receive the
|
||||
certificate. Add the gateway to `NO_PROXY`, or use an `http://` proxy, which only tunnels the connection.
|
||||
|
||||
The server's own certificate is still verified against the system trust store; add a private certificate authority with
|
||||
`NODE_EXTRA_CA_CERTS`, described in [Certificates](#certificates).
|
||||
|
||||
Client certificates are not yet presented by remote MCP servers, the WebSocket transport, or AI SDK provider packages
|
||||
that OpenCode runs without translating to a native provider. The Node.js build of OpenCode fails requests to a matching
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue