refactor(core): move the client certificate to provider settings.tls

This commit is contained in:
Aiden Cline
2026-11-08 00:21:13 -06:00
Unverified
parent f4fc5cb10e
commit 97930bf7d2
15 changed files with 94 additions and 114 deletions
@@ -1,6 +1,7 @@
import { Context, type Effect } from "effect"
import type { Headers, HttpClientRequest, HttpClientResponse } from "effect/http"
import { HttpContext, type AIError } from "../schema/errors.js"
import type { ClientTls } from "../schema/options.js"
// The service tag lives in its own leaf module so `Media.Asset` (imported by the schema layer) can require the
// executor without pulling the full executor implementation, and therefore the schema barrel, into a cycle.
@@ -23,6 +24,14 @@ export class RequestExecutorService extends Context.Service<RequestExecutorServi
"@opencode/AI/RequestExecutor",
) {}
export const Service = RequestExecutorService
/**
* The client certificate for the HTTP request being executed. Transports set it from `http.tls`; the executor's HTTP
* client presents it, since only the runtime's fetch can.
*/
export const CurrentTls = Context.Reference<ClientTls | undefined>("@opencode/AI/RequestExecutor/CurrentTls", {
defaultValue: () => undefined,
})
export type Service = RequestExecutorService
export const headerDetails = (headers: Headers.Headers) =>
+1 -1
View File
@@ -11,7 +11,7 @@ import { HttpContext, HttpRateLimitDetails, AIError, TransportError } from "../s
import { classifyProviderFailure, providerErrorMessage } from "../provider-error.js"
import { headerDetails, responseHttp, Service, type HttpMiddleware, type Interface } from "./executor-service.js"
export { responseHttp, Service } from "./executor-service.js"
export { CurrentTls, responseHttp, Service } from "./executor-service.js"
export type { HttpHandler, HttpMiddleware, Interface, RequestExecutorService } from "./executor-service.js"
const normalizedHeaders = (headers: Headers.Headers) =>
+1
View File
@@ -110,6 +110,7 @@ export const httpJson = <Body, Frame>(input: HttpJsonInput<Body, Frame>): HttpJs
// Unlike the header and chunk limits, the whole-request budget has no default.
const total = limits.total ? Duration.millis(limits.total) : Duration.infinity
const response = yield* runtime.http.execute(prepared.request, prepared.middleware).pipe(
Effect.provideService(RequestExecutor.CurrentTls, request.http?.tls),
Effect.timeoutOrElse({
duration: Duration.min(timeoutDuration(limits.headers), total),
orElse: () => timeout("request", "Timed out waiting for response headers"),
+10
View File
@@ -72,6 +72,15 @@ export interface HttpOptions {
readonly body?: Record<string, unknown>
/** Compression for JSON request bodies. Only set it for endpoints known to decode it. */
readonly encoding?: RequestEncoding
/** Client certificate presented to HTTPS endpoints that request one (mutual TLS). */
readonly tls?: ClientTls
}
/** PEM client certificate and private key, with the passphrase of an encrypted key. */
export interface ClientTls {
readonly cert: string
readonly key: string
readonly passphrase?: string
}
/** Per-phase time limits in milliseconds. */
@@ -127,6 +136,7 @@ export const mergeTransport = (...items: ReadonlyArray<TransportOptions | undefi
query: mergeStringRecords(...http.map((item) => item?.query)),
body: mergeJsonRecords(...http.map((item) => item?.body)),
encoding: last(http.map((item) => item?.encoding)),
tls: last(http.map((item) => item?.tls)),
}),
}
}
+4 -1
View File
@@ -31,6 +31,8 @@ export type ProviderTransport = "http" | "websocket"
export type ProviderEncoding = "zstd" | "gzip" | "none"
export type ProviderTls = { cert: string; key: string; passphrase?: string }
export type AgentColor = string
export type PermissionEffect = "allow" | "deny" | "ask"
@@ -1056,6 +1058,7 @@ export type ProviderSettings = {
cache?: ProviderCache
transport?: ProviderTransport
encoding?: ProviderEncoding
tls?: ProviderTls
} & { [x: string]: any }
export type ModelSettings = { compaction?: ProviderCompaction; cache?: ProviderCache; encoding?: ProviderEncoding } & {
@@ -1070,6 +1073,7 @@ export type ConfigProviderSettings = {
cache?: ProviderCache
transport?: ProviderTransport
encoding?: ProviderEncoding
tls?: ProviderTls
} & { [x: string]: JsonValue | null }
export type ConfigModelSettings = {
@@ -2495,7 +2499,6 @@ export type ConfigEntry =
plugins?: Array<string | { package: string; options?: { [x: string]: JsonValue } }>
worktree?: ConfigWorktree
warming?: boolean | { prompt?: string; interval?: "auto" | (string & {}); duration?: string }
network?: { client_certificate?: { cert: string; key?: string; passphrase?: string } }
providers?: {
[x: string]: {
canonical?: ProviderID
+3
View File
@@ -134,6 +134,7 @@ function prepareOptions(model: RuntimeInfo, pkg: string, outbound: Fetch) {
const customFetch = settings.fetch
const timeouts = Provider.timeouts(settings)
const tls = Provider.tls(settings)
options.fetch = async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
const opts = { ...(init ?? {}) }
// A plain AbortSignal.timeout would keep running into the body stream, so the header limit uses
@@ -160,6 +161,8 @@ function prepareOptions(model: RuntimeInfo, pkg: string, outbound: Fetch) {
}
}
// A followed redirect keeps the TLS options, so it would present the client certificate to another host.
if (tls) Object.assign(opts, { tls, redirect: "error" })
const send: Fetch = isFetch(customFetch) ? customFetch : outbound
const middleware = httpMiddleware.getStore()
const res = await (
-1
View File
@@ -217,7 +217,6 @@ export function normalize(input: unknown): Result {
websearch: Info.fields.websearch,
worktree: Info.fields.worktree,
warming: Info.fields.warming,
network: Info.fields.network,
}
Object.entries(nativeAtomic).forEach(([key, schema]) => {
if (!own(input, key)) return
+8 -47
View File
@@ -1,15 +1,9 @@
import { LLMClient, RequestExecutor } from "@opencode/ai/route"
import { Document } from "@opencode/schema/config"
import { Effect, Layer, Option } from "effect"
import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http"
import { FetchHttpClient, HttpClient } from "effect/http"
import { Socket } from "effect/socket"
import path from "path"
import { makeGlobalNode } from "@opencode/util/effect/app-node"
import { httpClient } from "@opencode/util/effect/app-node-platform"
import { FSUtil } from "@opencode/util/fs-util"
import { Global } from "@opencode/util/global"
import { Config } from "../config.js"
import { Location } from "../location.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.
@@ -24,49 +18,16 @@ const withoutBunTimeout = Layer.effect(
}),
)
// Presents `network.client_certificate` on HTTPS model requests from a Location whose config sets one. The TLS
// handshake only sends it to servers that request a client certificate.
// Presents the model's client certificate (provider `settings.tls`) on its HTTPS requests. The TLS handshake only
// sends it to servers that request one.
const withClientCertificate = Layer.effect(
HttpClient.HttpClient,
Effect.gen(function* () {
const fs = yield* FSUtil.Service
const global = yield* Global.Service
const client = yield* HttpClient.HttpClient
return HttpClient.transform(client, (effect, request) =>
Effect.gen(function* () {
if (!request.url.startsWith("https:")) return yield* effect
const config = yield* Effect.serviceOption(Config.Service)
if (Option.isNone(config)) return yield* effect
const source = (yield* config.value.entries()).findLast(
(entry): entry is Document =>
entry instanceof Document && entry.info.network?.client_certificate !== undefined,
)
const certificate = source?.info.network?.client_certificate
if (!source || !certificate) return yield* effect
// Config without a file (inline content, wellknown) resolves relative paths against the Location, like `{file:}`.
const directory = source.path
? path.dirname(source.path)
: Option.match(yield* Effect.serviceOption(Location.Service), {
onNone: () => global.home,
onSome: (location) => location.directory,
})
const resolve = (file: string) =>
file.startsWith("~/") ? path.join(global.home, file.slice(2)) : path.resolve(directory, file)
const tls = yield* Effect.all({
cert: fs.readFileString(resolve(certificate.cert)),
// A combined PEM file holds both the certificate and its key.
key: fs.readFileString(resolve(certificate.key ?? certificate.cert)),
}).pipe(
Effect.mapError(
(error) =>
new HttpClientError.HttpClientError({
reason: new HttpClientError.TransportError({
request,
description: `Could not read the configured client certificate: ${error.message}`,
}),
}),
),
)
const tls = yield* RequestExecutor.CurrentTls
if (!tls || !request.url.startsWith("https:")) return yield* effect
const init: BunFetchRequestInit = Option.getOrElse(
yield* Effect.serviceOption(FetchHttpClient.RequestInit),
() => ({}),
@@ -74,8 +35,8 @@ const withClientCertificate = Layer.effect(
return yield* effect.pipe(
Effect.provideService(FetchHttpClient.RequestInit, {
...init,
tls: { ...init.tls, ...tls, passphrase: certificate.passphrase },
// A followed redirect keeps the same TLS options, so it would present the certificate to whatever host the
tls: { ...init.tls, ...tls },
// A followed redirect keeps the TLS options, so it would present the certificate to whatever host the
// server names.
redirect: init.redirect === "manual" ? "manual" : "error",
} as BunFetchRequestInit),
@@ -88,7 +49,7 @@ const withClientCertificate = Layer.effect(
export const requestExecutor = makeGlobalNode({
service: RequestExecutor.Service,
layer: RequestExecutor.layer.pipe(Layer.provide(withoutBunTimeout), Layer.provide(withClientCertificate)),
deps: [httpClient, FSUtil.node, Global.node],
deps: [httpClient],
})
export const llmClient = makeGlobalNode({ service: LLMClient.Service, layer: LLMClient.layer, deps: [requestExecutor] })
+1 -1
View File
@@ -258,7 +258,7 @@ const resolveCatalogModel = Effect.fn("ModelResolver.resolveCatalogModel")(funct
...runtime.options,
...mergeTransport(runtime.options, {
timeout: { total: timeouts.timeout, headers: timeouts.headerTimeout, chunk: timeouts.chunkTimeout },
http: { encoding: Provider.encoding(configured) },
http: { encoding: Provider.encoding(configured), tls: Provider.tls(configured) },
}),
},
})
+8
View File
@@ -258,6 +258,14 @@ export function encoding(settings: Readonly<Record<string, unknown>>) {
return Option.getOrUndefined(decodeEncoding(settings.encoding))
}
const decodeTls = Schema.decodeUnknownOption(Provider.Tls)
/** Client certificate from provider settings. An empty `cert` or `key`, such as a missing `{file:}`, leaves it unset. */
export function tls(settings: Readonly<Record<string, unknown>>) {
const value = Option.getOrUndefined(decodeTls(settings.tls))
return value?.cert && value.key ? value : undefined
}
export function mergeOverlay(
base: Readonly<Record<string, unknown>> | undefined,
overlay: Readonly<Record<string, unknown>> | undefined,
+24 -23
View File
@@ -16653,29 +16653,6 @@
}
]
},
"network": {
"type": "object",
"properties": {
"client_certificate": {
"type": "object",
"properties": {
"cert": {
"type": "string",
"description": "Path to the PEM client certificate: absolute, `~/`, or relative to this configuration file"
},
"key": {
"type": "string"
},
"passphrase": {
"type": "string"
}
},
"required": ["cert"],
"additionalProperties": false
}
},
"additionalProperties": false
},
"providers": {
"type": "object",
"additionalProperties": {
@@ -17188,6 +17165,9 @@
},
"encoding": {
"$ref": "#/components/schemas/Provider.Encoding"
},
"tls": {
"$ref": "#/components/schemas/Provider.Tls"
}
},
"allOf": [
@@ -22022,6 +22002,9 @@
},
"encoding": {
"$ref": "#/components/schemas/Provider.Encoding"
},
"tls": {
"$ref": "#/components/schemas/Provider.Tls"
}
},
"allOf": [
@@ -22031,6 +22014,24 @@
}
]
},
"Provider.Tls": {
"type": "object",
"properties": {
"cert": {
"type": "string",
"description": "PEM client certificate, usually `{file:/path/to/client.pem}`"
},
"key": {
"type": "string",
"description": "PEM private key, usually `{file:/path/to/client.key}`"
},
"passphrase": {
"type": "string"
}
},
"required": ["cert", "key"],
"additionalProperties": false
},
"Provider.Transport": {
"type": "string",
"enum": ["http", "websocket"]
-4
View File
@@ -13,7 +13,6 @@ import { ConfigFormatter } from "./config/formatter.js"
import { ConfigLSP } from "./config/lsp.js"
import { ConfigMCP } from "./config/mcp.js"
import { ConfigModel } from "./config/model.js"
import { ConfigNetwork } from "./config/network.js"
import { ConfigPlugin } from "./config/plugin.js"
import { ConfigPolicy } from "./config/policy.js"
import { ConfigProvider } from "./config/provider.js"
@@ -113,9 +112,6 @@ export class Info extends Schema.Class<Info>("Config.Info")({
warming: ConfigWarming.Warming.pipe(optional).annotate({
description: "Keep recently active sessions warm with transient model requests (default: false)",
}),
network: ConfigNetwork.Info.pipe(optional).annotate({
description: "Network settings for outgoing requests",
}),
providers: Schema.Record(Schema.String, ConfigProvider.Info).pipe(optional),
experimental: ConfigExperimental.Info.pipe(optional),
}) {}
-23
View File
@@ -1,23 +0,0 @@
export * as ConfigNetwork from "./network.js"
import { Schema } from "effect"
import { optional } from "../schema.js"
export class ClientCertificate extends Schema.Class<ClientCertificate>("Config.Network.ClientCertificate")({
cert: Schema.String.annotate({
description: "Path to the PEM client certificate: absolute, `~/`, or relative to this configuration file",
}),
key: Schema.String.pipe(optional).annotate({
description:
"Path to the PEM private key: absolute, `~/`, or relative to this configuration file. Defaults to `cert`, for a file holding both",
}),
passphrase: Schema.String.pipe(optional).annotate({
description: "Passphrase for an encrypted private key. Use `{env:...}` or `{file:...}` to keep it out of the file",
}),
}) {}
export class Info extends Schema.Class<Info>("Config.Network")({
client_certificate: ClientCertificate.pipe(optional).annotate({
description: "Client certificate presented on model requests to servers that ask for one (mutual TLS)",
}),
}) {}
+9
View File
@@ -79,6 +79,14 @@ export type Encoding = typeof Encoding.Type
const Timeout = Schema.Union([Schema.Finite, Schema.Literal(false)]).pipe(optional)
/** Client certificate for gateways that require mutual TLS. Values are PEM text; use `{file:...}` to read a file. */
export const Tls = Schema.Struct({
cert: Schema.String.annotate({ description: "PEM client certificate, usually `{file:/path/to/client.pem}`" }),
key: Schema.String.annotate({ description: "PEM private key, usually `{file:/path/to/client.key}`" }),
passphrase: Schema.String.pipe(optional).annotate({ description: "Passphrase for an encrypted private key" }),
}).annotate({ identifier: "Provider.Tls" })
export type Tls = typeof Tls.Type
// The named fields are the settings OpenCode reads itself; every other key is a provider option for the provider package.
export const Settings = Schema.StructWithRest(
Schema.Struct({
@@ -89,6 +97,7 @@ export const Settings = Schema.StructWithRest(
cache: Cache.pipe(optional),
transport: Transport.pipe(optional),
encoding: Encoding.pipe(optional),
tls: Tls.pipe(optional),
}),
[Schema.Record(Schema.String, Schema.Any)],
).annotate({ identifier: "Provider.Settings" })
+16 -13
View File
@@ -94,27 +94,30 @@ Fix it in one of two ways:
## Client certificates
Set `network.client_certificate` when a model gateway requires mutual TLS. OpenCode presents the certificate on HTTPS
model requests, and the TLS handshake only sends it to servers that ask for one.
Set `settings.tls` on a provider whose gateway requires mutual TLS. Its model requests present the certificate, and the
TLS handshake only sends it to servers that ask for one.
```jsonc title="opencode.jsonc"
{
"network": {
"client_certificate": {
"cert": "/etc/company/client.pem",
"key": "/etc/company/client.key",
"passphrase": "{env:CLIENT_KEY_PASSPHRASE}",
"providers": {
"company": {
"package": "@opencode/ai/providers/openai-compatible",
"settings": {
"baseURL": "https://llm.company.example/v1",
"tls": {
"cert": "{file:/etc/company/client.pem}",
"key": "{file:/etc/company/client.key}",
"passphrase": "{env:CLIENT_KEY_PASSPHRASE}",
},
},
},
},
}
```
- `cert` and `key` are paths to PEM files: absolute, `~/`, or relative to the configuration file (or to the project for
config without a file, such as `OPENCODE_CONFIG_CONTENT`). They are read on each request, so a rotated certificate is
used without a restart.
- Leave out `key` when `cert` points to one PEM file holding both the certificate and the key.
- `passphrase` is only needed for an encrypted key. Use `{env:...}` or `{file:...}` to keep it out of the file.
- Model requests with a client certificate don't follow redirects, so the certificate isn't presented to another host.
- `cert` and `key` are PEM text. Use `{file:...}` to read them from files. A file that can't be read leaves `tls` unset.
- `passphrase` is only needed for an encrypted key.
- Requests with a client certificate don't follow redirects, so the certificate isn't presented to another host.
Only model requests present the certificate. Tools such as webfetch, remote MCP servers and plugin installs don't.