diff --git a/packages/ai/src/route/executor-service.ts b/packages/ai/src/route/executor-service.ts index 20539b6635c..4eb33784d6e 100644 --- a/packages/ai/src/route/executor-service.ts +++ b/packages/ai/src/route/executor-service.ts @@ -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("@opencode/AI/RequestExecutor/CurrentTls", { + defaultValue: () => undefined, +}) export type Service = RequestExecutorService export const headerDetails = (headers: Headers.Headers) => diff --git a/packages/ai/src/route/executor.ts b/packages/ai/src/route/executor.ts index 11082ef4e81..c32299a7eb6 100644 --- a/packages/ai/src/route/executor.ts +++ b/packages/ai/src/route/executor.ts @@ -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) => diff --git a/packages/ai/src/route/transport/http.ts b/packages/ai/src/route/transport/http.ts index 7924bbf02b3..03129617def 100644 --- a/packages/ai/src/route/transport/http.ts +++ b/packages/ai/src/route/transport/http.ts @@ -110,6 +110,7 @@ export const httpJson = (input: HttpJsonInput): 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"), diff --git a/packages/ai/src/schema/options.ts b/packages/ai/src/schema/options.ts index f9d6bff13ef..48bb876901c 100644 --- a/packages/ai/src/schema/options.ts +++ b/packages/ai/src/schema/options.ts @@ -72,6 +72,15 @@ export interface HttpOptions { readonly body?: Record /** 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 item?.query)), body: mergeJsonRecords(...http.map((item) => item?.body)), encoding: last(http.map((item) => item?.encoding)), + tls: last(http.map((item) => item?.tls)), }), } } diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index b279c01e4cc..9ab6a0ac378 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -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 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 diff --git a/packages/core/src/aisdk.ts b/packages/core/src/aisdk.ts index 51c31c6dc98..4058f513f13 100644 --- a/packages/core/src/aisdk.ts +++ b/packages/core/src/aisdk.ts @@ -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[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 ( diff --git a/packages/core/src/config/normalize.ts b/packages/core/src/config/normalize.ts index c42f43af77e..bfe4f657769 100644 --- a/packages/core/src/config/normalize.ts +++ b/packages/core/src/config/normalize.ts @@ -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 diff --git a/packages/core/src/effect/app-node-platform.ts b/packages/core/src/effect/app-node-platform.ts index bcccd493a0b..ae4afdf5288 100644 --- a/packages/core/src/effect/app-node-platform.ts +++ b/packages/core/src/effect/app-node-platform.ts @@ -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] }) diff --git a/packages/core/src/model-resolver.ts b/packages/core/src/model-resolver.ts index 8e06c4762d0..861772959be 100644 --- a/packages/core/src/model-resolver.ts +++ b/packages/core/src/model-resolver.ts @@ -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) }, }), }, }) diff --git a/packages/core/src/provider.ts b/packages/core/src/provider.ts index dd75031544d..3ae497450b2 100644 --- a/packages/core/src/provider.ts +++ b/packages/core/src/provider.ts @@ -258,6 +258,14 @@ export function encoding(settings: Readonly>) { 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>) { + const value = Option.getOrUndefined(decodeTls(settings.tls)) + return value?.cert && value.key ? value : undefined +} + export function mergeOverlay( base: Readonly> | undefined, overlay: Readonly> | undefined, diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 7bfda8abfbb..58018fa6249 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -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"] diff --git a/packages/schema/src/config.ts b/packages/schema/src/config.ts index bb70767910c..e78cbae0f8e 100644 --- a/packages/schema/src/config.ts +++ b/packages/schema/src/config.ts @@ -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("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), }) {} diff --git a/packages/schema/src/config/network.ts b/packages/schema/src/config/network.ts deleted file mode 100644 index 1c044e76bd0..00000000000 --- a/packages/schema/src/config/network.ts +++ /dev/null @@ -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("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("Config.Network")({ - client_certificate: ClientCertificate.pipe(optional).annotate({ - description: "Client certificate presented on model requests to servers that ask for one (mutual TLS)", - }), -}) {} diff --git a/packages/schema/src/provider.ts b/packages/schema/src/provider.ts index 9985e7402cf..50669806558 100644 --- a/packages/schema/src/provider.ts +++ b/packages/schema/src/provider.ts @@ -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" }) diff --git a/services/site/src/docs/content/network.mdx b/services/site/src/docs/content/network.mdx index 05ab8c41f48..34e866e1a08 100644 --- a/services/site/src/docs/content/network.mdx +++ b/services/site/src/docs/content/network.mdx @@ -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.