Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/client/src/promise/generated/types.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

116 changes: 116 additions & 0 deletions packages/core/src/client-certificate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
export * as ClientCertificate from "./client-certificate.js"

import path from "path"
import { Effect, Layer } from "effect"
import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http"
import type { Entry } from "@opencode/schema/config"
import { FSUtil } from "@opencode/util/fs-util"
import { Global } from "@opencode/util/global"
import { Config } from "./config.js"
import { WebSocketConstructor } from "./effect/websocket-constructor.js"
import { Wildcard } from "./util/wildcard.js"

export interface Rule {
readonly hosts: readonly string[]
readonly cert: string
readonly key: string
/** File holding the key's passphrase; read per request so the secret never enters a config document. */
readonly passphraseFile?: string
}

/**
* The rules from the highest-ranked config document that sets `network.client_certificates`. `Config` drops `network`
* from project documents, so a repository cannot choose where the machine's certificate is presented.
*/
export function rules(entries: readonly Entry[], global: Pick<Global.Interface, "config" | "home">) {
const source = entries.findLast(
(entry) => entry.type === "document" && entry.info.network?.client_certificates !== undefined,
)
if (source?.type !== "document") return []
const directory = source.path ? path.dirname(source.path) : global.config
const resolve = (file: string) =>
/^~[/\\]/.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(hostname),
cert: resolve(entry.cert),
key: resolve(entry.key),
passphraseFile: entry.passphrase_file === undefined ? undefined : resolve(entry.passphrase_file),
}),
)
}

/** The last rule naming the URL's host, like permission rules; plain-HTTP URLs never match. */
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 = hostname(target.hostname)
return rules.findLast((rule) => rule.hosts.some((pattern) => Wildcard.match(host, pattern)))
}

// `llm.example.` and `LLM.example` name the same host as `llm.example`, and `[0:0::1]` the same as `[::1]`.
const hostname = (host: string) =>
host.startsWith("[") && URL.canParse(`https://${host}`)
? new URL(`https://${host}`).hostname
: host.toLowerCase().replace(/\.$/, "")

/**
* 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.
* Rules come from the caller's Location `Config`, which every model request runs with.
*/
export const httpClientLayer = 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* () {
const config = yield* Effect.serviceOption(Config.Service)
if (config._tag === "None") return yield* effect
const rule = match(rules(yield* config.value.entries(), global), 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* 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 tls = yield* Effect.all({
cert: fs.readFileString(rule.cert),
key: fs.readFileString(rule.key),
passphrase: rule.passphraseFile
? fs.readFileString(rule.passphraseFile).pipe(Effect.map((text) => text.replace(/[\r\n]+$/, "")))
: Effect.succeed(undefined),
}).pipe(Effect.mapError((error) => fail(`Could not read the client certificate for ${host}: ${error.message}`)))
const fetch = yield* FetchHttpClient.Fetch
return yield* effect.pipe(
Effect.provideService(
FetchHttpClient.Fetch,
Object.assign(
(input: Parameters<typeof globalThis.fetch>[0], init?: BunFetchRequestInit) =>
fetch(input, {
...init,
tls: { ...init?.tls, ...tls },
// 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 },
),
),
)
}),
)
}),
)
17 changes: 15 additions & 2 deletions packages/core/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,8 +309,8 @@ export const layer = (options?: Options) =>
...(yield* loadWellknown().pipe(Effect.orDie)),
...globalSupplementary,
...explicit,
...direct,
...projectSupplementary,
...(yield* Effect.forEach(direct, withoutNetwork)),
...(yield* Effect.forEach(projectSupplementary, withoutNetwork)),
...content,
...managedSettings,
]
Expand Down Expand Up @@ -452,6 +452,19 @@ export const layer = (options?: Options) =>
}),
)

// `network` carries the machine's client certificates, so a repository's config must not choose where they are
// presented. Project documents drop it; every other source layers as usual.
const withoutNetwork = Effect.fnUntraced(function* (entry: Entry) {
if (entry.type !== "document" || entry.info.network === undefined) return entry
yield* Effect.logWarning("configuration normalization diagnostic", {
source: entry.path,
path: "$.network",
kind: "ignored",
action: "ignored network settings in project configuration",
})
return new Document({ ...entry, info: new Info({ ...entry.info, network: undefined }) })
})

export function configured(options?: Options) {
return makeLocationNode({
service: Service,
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/config/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ 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
Expand Down
7 changes: 5 additions & 2 deletions packages/core/src/effect/app-node-platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ 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 { FSUtil } from "@opencode/util/fs-util"
import { Global } from "@opencode/util/global"
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.
Expand All @@ -20,8 +23,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, FSUtil.node, Global.node],
})

export const llmClient = makeGlobalNode({ service: LLMClient.Service, layer: LLMClient.layer, deps: [requestExecutor] })
Expand Down
12 changes: 7 additions & 5 deletions packages/core/src/effect/websocket-constructor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
)
}
Expand Down
Loading
Loading