From 383094c3c63ab87f75b4077c667fbc2c03b4300a Mon Sep 17 00:00:00 2001 From: Adam <2363879+adamdotdevin@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:12:35 -0500 Subject: [PATCH] fix(core): keep the key passphrase out of config and validate certificate hosts --- .../client/src/promise/generated/types.ts | 2 +- packages/core/src/client-certificate.ts | 40 +++++++++++-------- packages/core/test/client-certificate.test.ts | 26 +++++++++--- packages/protocol/openapi.json | 4 +- packages/schema/src/config/network.ts | 11 +++-- services/www/src/docs/content/network.mdx | 14 ++++--- 6 files changed, 62 insertions(+), 35 deletions(-) diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index a4bb0b26738..4797a3bd830 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -2396,7 +2396,7 @@ export type ConfigEntry = worktree?: ConfigWorktree warming?: boolean | { prompt?: string; interval?: string; duration?: string } network?: { - client_certificates?: Array<{ hosts: Array; cert: string; key: string; passphrase?: string }> + client_certificates?: Array<{ hosts: Array; cert: string; key: string; passphrase_file?: string }> } providers?: { [x: string]: { diff --git a/packages/core/src/client-certificate.ts b/packages/core/src/client-certificate.ts index b17b83527cc..b22c46b460f 100644 --- a/packages/core/src/client-certificate.ts +++ b/packages/core/src/client-certificate.ts @@ -1,7 +1,7 @@ export * as ClientCertificate from "./client-certificate.js" import path from "path" -import { Context, Effect, Layer } from "effect" +import { Context, Duration, Effect, Exit, Layer } from "effect" import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http" import { makeGlobalNode } from "@opencode/util/effect/app-node" import { FSUtil } from "@opencode/util/fs-util" @@ -15,7 +15,8 @@ export interface Rule { readonly hosts: readonly string[] readonly cert: string readonly key: string - readonly passphrase?: string + /** File holding the key's passphrase; read per request so the secret never enters a config document. */ + readonly passphraseFile?: string } export interface Interface { @@ -36,16 +37,18 @@ export const layer = (options?: Options) => Effect.gen(function* () { const global = yield* Global.Service const context = yield* Effect.context() - const rules = yield* Effect.cachedWithTTL( - load(global, options?.system).pipe( - Effect.provide(context), - Effect.catch((error) => - Effect.logWarning("failed to load client certificates", { error }).pipe(Effect.as([])), - ), - ), - "1 minute", + // A failed load is retried on the next request instead of leaving the machine without certificates for a minute. + const rules = yield* Effect.cachedWithTTL(load(global, options?.system).pipe(Effect.provide(context)), (exit) => + Exit.isSuccess(exit) ? "1 minute" : Duration.zero, ) - return Service.of({ rules: () => rules }) + return Service.of({ + rules: () => + rules.pipe( + Effect.catch((error) => + Effect.logWarning("failed to load client certificates", { error }).pipe(Effect.as([])), + ), + ), + }) }), ) @@ -67,13 +70,13 @@ const load = Effect.fn("ClientCertificate.load")(function* (global: Global.Inter if (!source) return [] const directory = path.dirname(source.path ?? global.config) const resolve = (file: string) => - file.startsWith("~/") ? path.join(global.home, file.slice(2)) : path.resolve(directory, file) + /^~[/\\]/.test(file) ? path.join(global.home, file.slice(2)) : path.resolve(directory, file) return (source.info.network?.client_certificates ?? []).map( (entry): Rule => ({ - hosts: entry.hosts.map((host) => host.toLowerCase()), + hosts: entry.hosts.map(hostname), cert: resolve(entry.cert), key: resolve(entry.key), - passphrase: entry.passphrase, + passphraseFile: entry.passphrase_file === undefined ? undefined : resolve(entry.passphrase_file), }), ) }) @@ -83,10 +86,13 @@ export function match(rules: readonly Rule[], url: string) { if (!URL.canParse(url)) return const target = new URL(url) if (target.protocol !== "https:" && target.protocol !== "wss:") return - const host = target.hostname.toLowerCase() + const host = hostname(target.hostname) return rules.find((rule) => rule.hosts.some((pattern) => Wildcard.match(host, pattern))) } +// `llm.example.` and `LLM.example` name the same host as `llm.example`. +const hostname = (host: string) => host.toLowerCase().replace(/\.$/, "") + export function configured(options?: Options) { return makeGlobalNode({ service: Service, layer: layer(options), deps: [FSUtil.node, Global.node, AppProcess.node] }) } @@ -115,14 +121,14 @@ export const httpClientLayer = Layer.effect( Effect.provideService( FetchHttpClient.Fetch, Object.assign( - (input: Parameters[0], init?: BunFetchRequestInit) => + async (input: Parameters[0], init?: BunFetchRequestInit) => fetch(input, { ...init, tls: { ...init?.tls, cert: Bun.file(rule.cert), key: Bun.file(rule.key), - passphrase: rule.passphrase, + passphrase: rule.passphraseFile && (await Bun.file(rule.passphraseFile).text()).trim(), }, // 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. diff --git a/packages/core/test/client-certificate.test.ts b/packages/core/test/client-certificate.test.ts index a9e09b533ef..c4c14e4a882 100644 --- a/packages/core/test/client-certificate.test.ts +++ b/packages/core/test/client-certificate.test.ts @@ -1,7 +1,8 @@ import path from "path" import fs from "fs/promises" -import { afterAll, beforeAll, describe, expect } from "bun:test" -import { Effect, Layer } from "effect" +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 { ClientCertificate } from "@opencode/core/client-certificate" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" @@ -38,6 +39,7 @@ beforeAll(async () => { ...["-out", "client.pem", "-subj", "/CN=client", "-addext", "extendedKeyUsage=clientAuth"], ), ]) + await Bun.write(path.join(certs, "passphrase"), "secret\n") ca = await Bun.file(path.join(certs, "ca.pem")).text() server = Bun.serve({ hostname: "127.0.0.1", @@ -67,7 +69,9 @@ const write = (directory: string, config: unknown) => // The key is encrypted, so a request only succeeds when the passphrase reaches the TLS options too. const certificate = (hosts: string[]) => ({ network: { - client_certificates: [{ hosts, cert: "certs/client.pem", key: "certs/client.key", passphrase: "secret" }], + client_certificates: [ + { hosts, cert: "certs/client.pem", key: "certs/client.key", passphrase_file: "certs/passphrase" }, + ], }, }) @@ -88,6 +92,17 @@ const get = (host: string, pathname = "/") => }).pipe(Effect.provideService(FetchHttpClient.RequestInit, { tls: { ca } } as BunFetchRequestInit)) describe("ClientCertificate", () => { + test("accepts hostnames and rejects URLs, ports, and wildcard-only patterns", () => { + const valid = (host: string) => + Option.isSome( + Schema.decodeUnknownOption(ConfigNetwork.ClientCertificate)({ hosts: [host], cert: "c.pem", key: "k.pem" }), + ) + expect(["llm.corp.test", "*.corp.test", "llm-?.corp.test", "10.0.0.1", "[::1]"].filter(valid)).toHaveLength(5) + expect( + ["https://llm.corp.test", "llm.corp.test:8443", "llm.corp.test/v1", "*", "*.*", "::1"].filter(valid), + ).toEqual([]) + }) + itWithOpenSSL("presents the certificate to a matching host", () => Effect.gen(function* () { yield* write("system", certificate(["LOCALHOST"])) @@ -125,10 +140,11 @@ describe("ClientCertificate", () => { hosts: ["*.corp.test"], cert: path.resolve(root.path, "/etc/corp.pem"), key: path.join(root.path, "system", "corp.key"), - passphrase: undefined, + passphraseFile: undefined, }, ]) expect(ClientCertificate.match(rules, "https://api.corp.test/v1")).toBe(rules[0]) + expect(ClientCertificate.match(rules, "https://API.corp.test./v1")).toBe(rules[0]) expect(ClientCertificate.match(rules, "http://api.corp.test/v1")).toBeUndefined() expect(ClientCertificate.match(rules, "https://user.test/v1")).toBeUndefined() }).pipe(Effect.provide(layer())), @@ -146,7 +162,7 @@ describe("ClientCertificate", () => { hosts: ["user.test"], cert: path.join(root.path, "home", "user.pem"), key: path.join(root.path, "global", "user.key"), - passphrase: undefined, + passphraseFile: undefined, }, ]) }).pipe(Effect.provide(layer())), diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index dad3462e67e..45e44fb41bc 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -16667,7 +16667,7 @@ "type": "string" }, "minItems": 1, - "description": "Hostnames that receive this certificate. `*` and `?` wildcards match any characters" + "description": "Hostnames that receive this certificate, without scheme or port. `*` and `?` match any characters" }, "cert": { "type": "string" @@ -16675,7 +16675,7 @@ "key": { "type": "string" }, - "passphrase": { + "passphrase_file": { "type": "string" } }, diff --git a/packages/schema/src/config/network.ts b/packages/schema/src/config/network.ts index e63669794dc..2b12aea8ef9 100644 --- a/packages/schema/src/config/network.ts +++ b/packages/schema/src/config/network.ts @@ -5,9 +5,12 @@ import { optional } from "../schema.js" const NonEmpty = Schema.Trim.check(Schema.isNonEmpty()) +// A bare hostname or bracketed IPv6 address, never a URL or host:port, and not a pattern of wildcards alone. +const Host = Schema.Trim.check(Schema.isPattern(/^(?:(?=.*[a-z0-9])[a-z0-9*?.-]+|\[[0-9a-f:.]+\])$/i)) + export class ClientCertificate extends Schema.Class("Config.Network.ClientCertificate")({ - hosts: NonEmpty.pipe(Schema.Array, Schema.check(Schema.isMinLength(1))).annotate({ - description: "Hostnames that receive this certificate. `*` and `?` wildcards match any characters", + hosts: Host.pipe(Schema.Array, Schema.check(Schema.isMinLength(1))).annotate({ + description: "Hostnames that receive this certificate, without scheme or port. `*` and `?` match any characters", }), cert: NonEmpty.annotate({ description: "Path to the PEM client certificate, absolute, `~/`, or relative to this configuration file", @@ -15,8 +18,8 @@ export class ClientCertificate extends Schema.Class("Config.N key: NonEmpty.annotate({ description: "Path to the PEM private key, absolute, `~/`, or relative to this configuration file", }), - passphrase: Schema.String.pipe(optional).annotate({ - description: "Passphrase for an encrypted private key", + passphrase_file: NonEmpty.pipe(optional).annotate({ + description: "Path to a file holding the passphrase of an encrypted private key", }), }) {} diff --git a/services/www/src/docs/content/network.mdx b/services/www/src/docs/content/network.mdx index d6d72ad8253..654f5ca1936 100644 --- a/services/www/src/docs/content/network.mdx +++ b/services/www/src/docs/content/network.mdx @@ -87,18 +87,19 @@ requests and model catalogs, and to no other host. "hosts": ["llm.company.example", "*.ai.company.example"], "cert": "/etc/company/opencode-client.pem", "key": "/etc/company/opencode-client.key", - "passphrase": "{file:/etc/company/opencode-client.pass}", + "passphrase_file": "/etc/company/opencode-client.pass", }, ], }, } ``` -- `hosts` are matched against the request's hostname without the port. `*` and `?` are wildcards, so `*.company.example` - matches `llm.company.example` but not `company.example`. +- `hosts` are hostnames or bracketed IPv6 addresses, without a scheme, port, or path, matched against the request's + hostname. `*` and `?` are wildcards that also match dots, so `*.company.example` matches `llm.company.example` and + `a.b.company.example` but not `company.example`. Write internationalized domains in their ASCII (`xn--`) form. - `cert` and `key` are PEM files. Paths can be absolute, start with `~/`, or be relative to the configuration file. OpenCode reads the files for each request, so a rotated certificate applies without a restart. -- `passphrase` is only needed for an encrypted key. Use `{file:...}` or `{env:...}` to keep it out of the file. +- `passphrase_file` names a file holding the passphrase of an encrypted key. It is only needed for an encrypted key. - The first entry whose `hosts` match is used. This is a machine setting, so OpenCode reads it only from managed and global configuration: macOS managed preferences @@ -111,8 +112,9 @@ Requests that present a client certificate do not follow redirects, because a re 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). -Client certificates are not yet presented by remote MCP servers or by the WebSocket transport, and the Node.js build of -OpenCode fails requests to a matching host instead of sending them without the certificate. +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 +host instead of sending them without the certificate. ## Foreground