fix(core): keep the key passphrase out of config and validate certificate hosts

This commit is contained in:
Adam 2026-10-29 10:12:35 -05:00 • committed by Aiden Cline
parent a338e0751e
commit 383094c3c6
6 changed files with 62 additions and 35 deletions

View file

@ -2396,7 +2396,7 @@ export type ConfigEntry =
worktree?: ConfigWorktree
warming?: boolean | { prompt?: string; interval?: string; duration?: string }
network?: {
client_certificates?: Array<{ hosts: Array<string>; cert: string; key: string; passphrase?: string }>
client_certificates?: Array<{ hosts: Array<string>; cert: string; key: string; passphrase_file?: string }>
}
providers?: {
[x: string]: {

View file

@ -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<FSUtil.Service | AppProcess.Service>()
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<typeof globalThis.fetch>[0], init?: BunFetchRequestInit) =>
async (input: Parameters<typeof globalThis.fetch>[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.

View file

@ -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())),

View file

@ -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"
}
},

View file

@ -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<ClientCertificate>("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<ClientCertificate>("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",
}),
}) {}

View file

@ -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