provider: trust a self-signed server's certificate by fingerprint, for Remote magpie and any https address of your own (Zhangzhangi on X)

Zhangzhangi on X couldn't add a Remote magpie at a domain with a
self-signed certificate ("x509: "api.magpie.local" certificate is not
standards compliant") and asked for a skip-verification option. A
follow-up asked for the same on other self-signed hosts.

This adds a pin (trust on first use), not a blind skip. It is off by
default and kept per provider:
- Advanced → Server certificate → "Trust its certificate…" fetches the
  certificate the server shows (provider/peekcert) and lists its SHA-256,
  subject, issuer and expiry. "Trust this certificate" keeps the
  fingerprint as the provider's serverPin.
- From then on only that certificate is accepted (netproxy pinTLS:
  InsecureSkipVerify plus VerifyConnection comparing the leaf's DER
  SHA-256). Another one fails with PinMismatchError, saying the server
  showed a certificate other than the one trusted.
- The editor shows a red "Certificate not verified: only this one is
  accepted" with the fingerprint, and "Verify it again" drops the pin.
- The pin is set only on the provider's own hosts (provider.PinHosts):
  - every address of Remote magpie and of a provider added by URL;
  - for a preset (Ollama, LM Studio, OpenAI at your own box), only https
    addresses whose host is not one of the preset's or its regions' own
    hosts. A vendor's host never takes a pin.
  - Never for an account, Vertex or a subscription. Save refuses one
    elsewhere.
- The client certificate and Server CA still go only to the providers
  that took them before (TakesClientCert). A preset gets the pin alone.
- The editor's certificate rows (Client certificate and the new Server
  certificate) are drawn by a lazily imported tlscerts.js. The Client
  certificate row moved out of app.js with it, so the core scripts stay
  under TestCoreScriptBudget without a raise.

Run (Go 1.26.8):
- WSL magpie-desktop, before the rebase:
  - go test -tags nogui -count=1 ./internal/netproxy ./internal/provider
    ./internal/gui all ok;
  - GOOS=darwin -tags nogui vet of gui fails on traywindows_darwin_test.go's
    undefined trayImagePNG, the same at the base (a cgo-only helper).
- mote and mica, after the rebase on ab5824aee:
  - gofmt -l clean; node --check app.js;
  - go vet darwin (cgo), GOOS=linux -tags nogui, GOOS=windows: ok;
  - go test ./internal/netproxy ./internal/provider: ok.
- mote, at the final tree: node --check app.js and tlscerts.js; go test
  ./internal/gui -run 'Budget|ServerPin|InsecureTLS|ClientCert|OnDemand|Lazy'
  ok (TestCoreScriptBudget under 1,533,802) at the base ab5824aee.
  Rebased on fe5a0cf6d, TestCoreScriptBudget is red, as it is on that
  main alone: main's core is 1,534,708 (16ed1a952 took it to 1,535,318);
  this change takes it to 1,534,484, 224 bytes less (#5918, commented).
  The rest of the run above passes at the pushed head.
- mica, GUI files at the final tree, both engines inside each file:
  - green: provider-server-pin (54), mtls-settings (16),
    provider-insecure-tls (60), provider-socket (60), provider-http1 (60),
    i18n-keys, i18n-en-no-cjk, editor-advanced-align, provider-advanced-fold
    (50);
  - old-webkit: headerpresets.js not loaded (#6030) and Safari 15's :has()
    (#5919), both on main too;
  - menu-scroll: 24 of 24 red on /api/update/using, the same alone at
    origin/main fe5a0cf6d (#5982, commented).
  - Earlier flakes of provider-http1 beside another session's suite:
    #6159.
- Broken by hand, each red:
  - presets never take a pin: TestServerPinSaveChecks,
    TestServerPinPresetAtOwnServer, TestServerPinNoVendorHost;
  - vendor hosts pinned (the own-host check dropped):
    TestServerPinNoVendorHost;
  - client cert and CA sent to presets: TestServerPinPresetAtOwnServer;
  - the pin never compared: TestPinOnlyThatCertificate,
    TestServerPinRemoteMagpie.
  Restored: both packages ok.

Not tried:
- a real self-signed domain from the macOS app (httptest servers with
  their own certificates only);
- the Responses WebSocket dial (read only: it takes the same netproxy
  transport);
- go test ./internal/cli and the whole GUI suite before the tag (the
  full Go suite runs after it, under suite.lock).
This commit is contained in:
yetone
2026-11-11 21:13:43 +08:00
parent fe5a0cf6d3
commit 8016205e3f
16 changed files with 1087 additions and 43 deletions
+16
View File
@@ -1029,6 +1029,22 @@ gateway calls on under mTLS (call the gateway's own port); there is no
`.p12` for a browser yet (`openssl pkcs12 -export -in client.pem -inkey
client-key.pem -out laptop.p12` makes one).
**A self-signed certificate.** A Remote magpie, a provider of your own,
or a preset pointed at a server of yours (Ollama or LM Studio on another
computer behind `https://`), on a domain whose certificate this computer
doesn't trust, such as a self-signed one, or one macOS calls "not
standards compliant", can be trusted as it is (Zhangzhangi on X): Advanced → Server certificate → Trust
its certificate… shows the certificate the server answers with, its
SHA-256 fingerprint, names and dates. Check the fingerprint against the
server's (`openssl x509 -in cert.pem -noout -fingerprint -sha256`) and
Trust it. From then on that provider's own host is taken with that one
certificate alone, its chain, name and dates unchecked, and any other
certificate is refused; the editor says so in red. A certificate renewed
later has to be trusted again. Verify it again takes the pin off. It is
off by default and kept for that provider alone. A preset's own vendor
addresses never take one: the row shows only for an `https://` address
at a host the preset doesn't name.
Caddy is the alternative that also gets the certificate for you: run
`relay.example.com { reverse_proxy 127.0.0.1:3425 }` with sharing on and a
gateway key per client. A proxy on this computer adds forwarding headers,
+1
View File
@@ -381,6 +381,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
- A streamed turn to the ChatGPT backend (POST `CodexBase`/responses with `"stream":true`) goes over the backend's WebSocket, as Codex's own client sends it, and comes back as the server-sent events the HTTP route answers with (`codexSocket` in [codex_socket.go](../../internal/gateway/codex_socket.go), first in the gateway's `upstreamTransport`, so Codex's own sign-in passed through and magpie's ChatGPT accounts both take it, through the proxy in force). On some networks a streamed HTTP reply from chatgpt.com is cut at about 120 s, before `response.completed`, while the WebSocket runs to the end (brickhao on Discord). The handshake carries the turn's headers with `OpenAI-Beta: responses_websockets=2026-02-06`, without `x-codex-turn-state` and the responses-lite header, which go in the message's `client_metadata` as Codex puts them; the message is the body with `"type":"response.create"` ahead of it (a zstd body is decoded first). `codex.rate_limits` and `codex.response.metadata`, read ahead of the reply, are also told as the `x-codex-*` and `x-codex-turn-state` headers the HTTP route carries; `responsesapi.websocket_timing` is dropped. An `error` frame ahead of the reply is that status with its error as the body; `websocket_connection_limit_reached`, a refused handshake or a body that isn't a streamed turn goes over HTTP instead, and a host that refused the handshake (other than 401, 429 or 5xx) is spoken HTTP for 10 minutes (`codexSocketShun`). A socket that ends, or won't take the message, before any frame of the reply was handed on (any close status, a dropped connection, a normal close with no reply) sends the same body over HTTP (`codexSocketEnded`): Lamrfu's long conversation was closed 1009 (message too big) by chatgpt.com and got a 502. A conversation's socket is kept between its turns, and a turn that carries on from the last goes on it as only its new input after `previous_response_id`, as Codex's own client sends it (`codexKept` in [codex_socket_keep.go](../../internal/gateway/codex_socket_keep.go); codex-rs `get_incremental_items`): rem_thank on X saw magpie send the whole conversation on a new socket every turn, which a long one meets as 1009. A socket is kept for a turn that names its conversation (`session-id` or `thread-id`, else `prompt_cache_key`) and ended `response.completed` with an id, keyed by the host, a digest of `Authorization` and `chatgpt-account-id`, the conversation's ids and the subagent headers (`codexKeepKey`), so another account's turn never finds it nor names its response; the next turn takes it out of the pool, so two turns at once each have a socket. It is let go after 10 minutes unused (`codexKeepIdle`), at 55 minutes from its handshake (`codexKeepAge`; the backend ends a connection at 60) and the oldest past 32 (`codexKeepMax`); the gateway's tests drain the pool in their cleanup (`codexKeepDrain`). The turn goes as a delta when every field but `input`, `client_metadata` and `stream_options` is as the last turn sent it, and its input begins with the last turn's input and then that turn's `response.output_item.done` items, each compared without its id, status, nulls, empty lists, annotations and logprobs (`codexSocketItem`); anything else goes whole on the kept socket. What is compared is the body as it goes, after masking and every translation, so a turn masked otherwise than the last goes whole. A kept socket that fails before the reply is handed on (closed while kept, the write fails, or an `error` frame first, such as `previous_response_not_found` or the connection limit) is closed and the turn goes whole on a new socket, and from there over HTTP as before (`errCodexSocketAgain`). A message at least as big as one a host closed 1009 goes to it over HTTP for 10 minutes (`codexTooBig`). A socket closed after the reply began reads as a cut stream (`io.ErrUnexpectedEOF`), and is not asked again. Codex speaks to magpie over its own WebSocket since #4058 ([A Responses WebSocket](gateway-routing.md#a-responses-websocket)), sending a turn as a delta after `previous_response_id`; magpie gives each turn the whole conversation before it goes on, and this leg cuts its own delta for the kept socket. The gateway's tests turn it off in TestMain (`codexSocketOff`); codex_socket_test's fakes speak it.
- A provider the user added may have its certificate left unchecked (`InsecureTLS`, the editor's Certificate row, #2383: a vLLM on the LAN, Ollama behind a self-signed cert, a company CA). Only one with a base URL of the user's own takes it (`TakesInsecureTLS`: no account, no preset, not Vertex, not a subscription's or plugin's id); `Save` refuses it on any other, and one written into providers.json by hand is ignored. `Provider.Via` then adds `netproxy.WithUncheckedTLS` with the hosts of its own base URLs (`UncheckedHosts`: Chat, Responses, Anthropic, Gemini, Decide), so every request made on its behalf through a `Dispatch` transport (the gateway's turns, count_tokens, models, test and detect, balance) skips the check for those hosts alone, on a transport kept apart for each (`route.unchecked`). A redirect or a models, balance or image URL on another host is checked, and `netproxy.With` drops the leave for a request made for another provider. An `https://` proxy would be dialled with the same TLS config, so its certificate would go unchecked too: such a request is refused (`ErrUncheckedOverHTTPSProxy`); an `http://` or `socks5://` proxy is taken. Backup, export and sync carry the field with the provider; an import link doesn't.
- A provider the user added may show a client certificate and trust a CA of its own (`ClientCert`, `ClientKey`, `ServerCA`: absolute PEM paths, a `~` taken as home, the editor's Client certificate rows under Advanced, shown while an address is `https://`; #5596, clxsh: Remote Magpie to a magpie or an Nginx asking for mTLS). It takes the same providers as `InsecureTLS` (`TakesClientCert`), and `Save` refuses half a pair, a pair that doesn't match and a CA file with no certificate (`netproxy.CheckClientCert`). `Provider.Via` adds `netproxy.WithClientCert` with the hosts of its own base URLs, so the gateway's turns, streaming, models and the connection test show the certificate to those hosts alone, on a transport kept apart for each (`clientRoute`), the gateway key still sent; another host, and a request made for another provider, never see it. Through an `https://` proxy such a request is refused (`ErrClientCertOverHTTPSProxy`). The route is keyed on the files' paths, mtimes and sizes, so a certificate renewed in place gets a new transport (`TestRemoteMagpieClientCert`, `TestClientCertSaveChecks`, the `clientcert_test.go` tests).
- The same providers may instead pin their server's certificate (`ServerPin`: the SHA-256 of its DER, lower-case hex; Zhangzhangi on X, a Remote magpie on a domain with a self-signed certificate macOS calls not standards compliant). Off by default, per provider. The editor's Advanced → Server certificate asks `POST /api/provider/peekcert`, which reaches the form's first `https://` address through its proxy and client certificate with the certificate unchecked (`Provider.PeekServerCert`) and shows its fingerprint, names, dates and why this computer doesn't take it (`x509.Verify` with the system roots); Trust keeps the pin, and the row then says in red that the certificate isn't verified. `Via` passes the pin to `netproxy.WithClientCert`, whose transport for those hosts skips the chain, name and date checks and refuses in `VerifyConnection` any leaf whose SHA-256 isn't the pin (`pinTLS`, `PinMismatchError`). The hosts it applies at are `PinHosts`: every endpoint of a provider that takes a client certificate, and of a preset's only the `https://` addresses at a host neither the preset nor its regions name (Zhangzhangi on X, "建议对别的自签名域名也生效": LM Studio or Ollama on another computer), never a subscription's, Vertex or a vendor's own host; a client certificate and Server CA still go only where `TakesClientCert` holds. `TakesServerPin` is in `/api/providers`, and the editor shows the row while the form has such an address (`pinAddrs` in app.js). `Save` refuses a pin that isn't 64 hex digits, or on a provider with no such address (`TestServerPinRemoteMagpie`, `TestServerPinSaveChecks`, `TestServerPinPresetAtOwnServer`, `TestServerPinNoVendorHost`, `TestPinOnlyThatCertificate`, `provider-server-pin.test.cjs`).
- A provider the user added may be held to HTTP/1.1 (`HTTP1`, the editor's "HTTP version" row under Advanced, shown while an address is `https://`; kepner_53726 on Discord: a company gateway whose HTTP/2 streams broke mid-reply with "tls: bad record MAC" while a plain Go client held). It takes the same providers as `InsecureTLS` (`TakesInsecureTLS`), and `Save` refuses it on any other. `Provider.Via` adds `netproxy.WithHTTP1` with the hosts of its own base URLs, so a request made on its behalf to one of those hosts goes through the `Dispatch` transport's HTTP/1.1 copy (`route.h1`); another host, and a request made for another provider (`netproxy.With` drops it), are offered HTTP/2 as before (`TestHTTP1AskedOnlyItsHost`, `TestHTTP1OwnProviderOnly`, `TestProviderSaveHTTP1`). Without it, a TLS record error read on an HTTP/2 reply (`recordError`: "bad record MAC", "received record with version …", an oversized record) moves that host:port to HTTP/1.1 for 6 hours (`h2BrokenFor`; see [Gateway routing](gateway-routing.md)).
- A provider the user added with a Responses address may send its turns over the Responses WebSocket, as the ChatGPT leg above does (`Socket`, #5781, faithleysath; matrix0487 on Discord; `magpie provider set <id> socket=auto|on|off`, the editor's WebSocket row under Advanced). It takes a provider with no account, an `http(s)://` Responses address and not Vertex (`TakesSocket`); the CLI refuses it on any other. `Provider.Via` puts the provider's Responses host and path in the request's context (`withSocket`), and `codexSocket` speaks the socket only to a POST to that host at `<Responses>/responses` (`SocketTurn`); a provider without `Socket` hides a value an outer context carried, so it never dials a socket (`TestResponsesProviderWithoutSocketNeverDials`). Everything after is the ChatGPT leg's: the fallback to HTTP on a refused handshake or a socket that ends before the reply, the kept socket and its delta (keyed by scheme, `Authorization`, `X-Api-Key` and `Api-Key` too), and a server-sent-events reply. `auto` speaks HTTP to a host for 10 minutes once it refused the handshake; `on` tries the socket every turn and never shuns. Routing, keys, limits, usage and masking are the HTTP route's, since the socket replaces only the transport.
- A provider the user added may be set never to rest for a limit (`LimitRestOff`, `limitRestOff`; the editor's Advanced fold, "Set it aside when out of quota or rate limited", ticked by default; zoecats on Discord: a local aggregator's "quota exhausted" while it switches upstreams). Off, a quota, credit or rate refusal and any 429 rest none of its keys and the next request is sent to it as usual (`restAfterMarked` in the gateway, see [gateway routing](gateway-routing.md)). The editor offers it only to a provider the user added (`custom`); a save that leaves it out keeps it (`TestProviderSaveLimitRestOff`, `provider-limit-rest.test.cjs`).
+8
View File
@@ -5243,3 +5243,11 @@ body .row.agent .ag-prefs .row.pref .who { display: block; }
.notices-text { grid-column: 1 / -1; min-width: 0; margin: 0; font: 11px/1.5 var(--code); white-space: pre-wrap; overflow-wrap: anywhere; }
.client-cert { display: grid; gap: 6px; min-width: 0; }
.client-cert input { width: 100%; min-width: 0; }
.server-pin { display: grid; gap: 6px; min-width: 0; justify-items: start; }
.server-pin .pin-fp { font: 11px/1.5 var(--code); overflow-wrap: anywhere; word-break: break-all; }
.server-pin .pin-off { display: flex; align-items: center; gap: 6px; color: var(--red); font-weight: 600; }
.server-pin .pin-off::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--red); flex: none; }
.server-pin .pin-seen { display: grid; gap: 4px; min-width: 0; }
.server-pin .hint.err { color: var(--red); overflow-wrap: anywhere; }
.server-pin .pin-acts { display: flex; flex-wrap: wrap; gap: 12px; }
.server-pin .pin-peek.busy { pointer-events: none; opacity: .6; }
+10 -19
View File
@@ -7922,7 +7922,7 @@ function advancedSet(d, p) {
!!d.proxyMode || Object.values(d.accountProxies || {}).some((x) => x?.mode) ||
[d.concurrency, d.maxAccounts, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) ||
!!d.rateWindows?.length ||
!!(d.searches || d.authHeader || d.passUserAgent === false || d.unredacted || d.countFree || d.billing || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.http1 || d.socket || d.imageFilesOff || d.passErrors || d.clientCert || d.serverCA) ||
!!(d.searches || d.authHeader || d.passUserAgent === false || d.unredacted || d.countFree || d.billing || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.http1 || d.socket || d.imageFilesOff || d.passErrors || d.clientCert || d.serverCA || d.serverPin) ||
!!d.fallback?.length || !!p?.balanceToken?.set;
}
function priceRateError(ed) {
@@ -8004,7 +8004,7 @@ function asTyped() {
for (const k of CERT_FIELDS) if (draft[k] != null) body[k] = draft[k].trim();
return body;
}
const CERT_FIELDS = ["clientCert", "clientKey", "serverCA"];
const CERT_FIELDS = ["clientCert", "clientKey", "serverCA", "serverPin"];
// proxyOfDraft is the draft's proxy as it is saved, or null when Custom
// has no address yet.
@@ -9233,7 +9233,7 @@ function baseAPIOf(p) {
// draftOf is a saved provider as its editor's form holds it.
function draftOf(p) {
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), passHeaders: (p.passHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], hiddenVideomakers: [...(p.hiddenVideomakers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, billing: p.billing || "", insecureTLS: !!p.insecureTLS, http1: !!p.http1, clientCert: p.clientCert || "", clientKey: p.clientKey || "", serverCA: p.serverCA || "", socket: p.socket || "", limitRestOff: !!p.limitRestOff, upstreamProviders: !!p.upstreamProviders, passErrors: !!p.passErrors, imageFilesOff: !!p.imageFilesOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: p.passUserAgent !== false, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", listOff: !!p.listOff, contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) };
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), passHeaders: (p.passHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], hiddenVideomakers: [...(p.hiddenVideomakers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, billing: p.billing || "", insecureTLS: !!p.insecureTLS, http1: !!p.http1, clientCert: p.clientCert || "", clientKey: p.clientKey || "", serverCA: p.serverCA || "", serverPin: p.serverPin || "", socket: p.socket || "", limitRestOff: !!p.limitRestOff, upstreamProviders: !!p.upstreamProviders, passErrors: !!p.passErrors, imageFilesOff: !!p.imageFilesOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: p.passUserAgent !== false, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", listOff: !!p.listOff, contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) };
}
// duplicateProvider opens the Add form on a copy of p, its key p's unless another is pasted (#268).
@@ -9392,6 +9392,7 @@ function drawEditor(p, presetID) {
let showLocal = () => {};
// the Certificate rows, shown over https:// (#2383, #5596)
let showTLS = () => {};
let pinBody = () => {};
// the Key header row, for a third-party Anthropic API
let showAuth = () => {};
// the Compaction row, for a Responses API (CarriesCompaction)
@@ -9852,23 +9853,12 @@ function drawEditor(p, presetID) {
ed.append(...row);
advIn.append(...hrow);
}
// a client certificate and server CA (#5596, mTLS)
// a client certificate and server CA (#5596, mTLS), and a self-signed
// server's certificate pinned (Zhangzhangi on X), in tlscerts.js
const certTakes = () => p ? !!p.takesClientCert : (custom || remote);
if (certTakes()) {
const box = el("div", "client-cert");
for (const [k, label, hold] of [["clientCert", t("Certificate"), "client.pem"], ["clientKey", t("Key"), "client-key.pem"], ["serverCA", t("Server CA"), "ca.pem"]]) {
const i = input(draft[k] || "", "~/magpie-laptop/" + hold);
i.className = "words cert-" + k;
i.setAttribute("aria-label", label);
i.oninput = () => { draft[k] = i.value; };
box.append(i);
}
const crow = field(t("Client certificate"), box, t("PEM files, for a server that asks for one (mTLS)"));
const was = showTLS;
showTLS = () => { was(); for (const e of crow) e.style.display = onHTTPS() ? "" : "none"; };
showTLS();
advIn.append(...crow);
}
const certAt = document.createComment("");
advIn.append(certAt);
import("./tlscerts.js").then(() => tlsCertRows({ p, pr, draft, at: certAt, certTakes, onHTTPS, addressOf, asTyped, show: (f) => { const was = showTLS; showTLS = () => { was(); f(); }; showTLS(); }, save: (f) => { pinBody = f; } }), statusErr);
// Responses over WebSocket (#5781): auto, or the CLI's on kept
const socketable = () => !p?.account && (p?.preset || pr?.id) !== "google-vertex" && /^\s*https?:\/\//i.test(addressOf("responses"));
{
@@ -10258,6 +10248,7 @@ function drawEditor(p, presetID) {
body.billing = draft.billing || "";
if (tlsTakes()) { body.insecureTLS = !!draft.insecureTLS && onHTTPS(); body.http1 = !!draft.http1 && onHTTPS(); }
if (certTakes()) for (const k of CERT_FIELDS) body[k] = onHTTPS() ? (draft[k] || "").trim() : "";
else pinBody(body);
if (socketable()) body.socket = draft.socket || "";
if (custom) body.limitRestOff = !!draft.limitRestOff;
if ((p?.preset || pr?.id) === "remote-magpie") body.upstreamProviders = !!draft.upstreamProviders;
+32
View File
@@ -4436,6 +4436,14 @@ const I18N = {
"Upload images once and send them by file id": "图片只上传一次,之后按文件 ID 发送",
"Off: an agent's images are sent inline on every turn.": "关闭后:智能体的图片每一轮都直接随请求发送。",
"Certificate": "证书",
"Server certificate": "服务器证书",
"Certificate not verified: only this one is accepted": "证书未验证:只接受这一张",
"Verify it again": "恢复验证",
"Trust its certificate…": "信任它的证书…",
"{subject}, issued by {issuer}, until {date}": "{subject},由 {issuer} 签发,有效至 {date}",
"This computer already trusts it: nothing to pin.": "这台电脑已经信任它,无需固定。",
"Trust this certificate": "信任这张证书",
"For your own server with a self-signed certificate. Check the fingerprint against the server's before you trust it; a certificate renewed later has to be trusted again.": "用于使用自签名证书的自有服务器。信任前请先和服务器上的指纹核对;证书之后更换的话需要重新信任。",
"Client certificate": "客户端证书",
"Server CA": "服务器 CA",
"PEM files, for a server that asks for one (mTLS)": "PEM 文件,用于要求客户端证书的服务器(mTLS)",
@@ -9485,6 +9493,14 @@ const I18N = {
"Upload images once and send them by file id": "圖片只上傳一次,之後按檔案 ID 傳送",
"Off: an agent's images are sent inline on every turn.": "關閉後:代理的圖片每一輪都直接隨請求傳送。",
"Certificate": "憑證",
"Server certificate": "伺服器憑證",
"Certificate not verified: only this one is accepted": "憑證未驗證:只接受這一張",
"Verify it again": "恢復驗證",
"Trust its certificate…": "信任它的憑證…",
"{subject}, issued by {issuer}, until {date}": "{subject},由 {issuer} 簽發,有效至 {date}",
"This computer already trusts it: nothing to pin.": "這台電腦已經信任它,無需固定。",
"Trust this certificate": "信任這張憑證",
"For your own server with a self-signed certificate. Check the fingerprint against the server's before you trust it; a certificate renewed later has to be trusted again.": "用於使用自簽憑證的自有伺服器。信任前請先與伺服器上的指紋核對;憑證之後更換的話需要重新信任。",
"Client certificate": "用戶端憑證",
"Server CA": "伺服器 CA",
"PEM files, for a server that asks for one (mTLS)": "PEM 檔案,用於要求用戶端憑證的伺服器(mTLS)",
@@ -14554,6 +14570,14 @@ const I18N = {
"Upload images once and send them by file id": "画像は一度だけアップロードし、以降はファイル ID で送る",
"Off: an agent's images are sent inline on every turn.": "オフ:エージェントの画像を毎ターンそのまま送ります。",
"Certificate": "証明書",
"Server certificate": "サーバー証明書",
"Certificate not verified: only this one is accepted": "証明書は検証されません:この 1 枚だけを受け入れます",
"Verify it again": "検証を戻す",
"Trust its certificate…": "この証明書を信頼…",
"{subject}, issued by {issuer}, until {date}": "{subject}、発行者 {issuer}、{date} まで有効",
"This computer already trusts it: nothing to pin.": "このコンピュータはすでに信頼しています。固定は不要です。",
"Trust this certificate": "この証明書を信頼",
"For your own server with a self-signed certificate. Check the fingerprint against the server's before you trust it; a certificate renewed later has to be trusted again.": "自己署名証明書を使う自分のサーバー用です。信頼する前にサーバー側のフィンガープリントと照合してください。証明書を更新したら、もう一度信頼する必要があります。",
"Client certificate": "クライアント証明書",
"Server CA": "サーバー CA",
"PEM files, for a server that asks for one (mTLS)": "PEM ファイル。クライアント証明書を求めるサーバー(mTLS)用",
@@ -19636,6 +19660,14 @@ const I18N = {
"Upload images once and send them by file id": "Bilder einmal hochladen und per Datei-ID senden",
"Off: an agent's images are sent inline on every turn.": "Aus: Die Bilder eines Agenten werden in jeder Runde direkt mitgeschickt.",
"Certificate": "Zertifikat",
"Server certificate": "Server-Zertifikat",
"Certificate not verified: only this one is accepted": "Zertifikat nicht geprüft: Nur dieses wird angenommen",
"Verify it again": "Wieder prüfen",
"Trust its certificate…": "Seinem Zertifikat vertrauen…",
"{subject}, issued by {issuer}, until {date}": "{subject}, ausgestellt von {issuer}, gültig bis {date}",
"This computer already trusts it: nothing to pin.": "Dieser Computer vertraut ihm bereits: Nichts festzulegen.",
"Trust this certificate": "Diesem Zertifikat vertrauen",
"For your own server with a self-signed certificate. Check the fingerprint against the server's before you trust it; a certificate renewed later has to be trusted again.": "Für einen eigenen Server mit selbstsigniertem Zertifikat. Vergleiche den Fingerabdruck vor dem Vertrauen mit dem des Servers; ein später erneuertes Zertifikat muss erneut bestätigt werden.",
"Client certificate": "Client-Zertifikat",
"Server CA": "Server-CA",
"PEM files, for a server that asks for one (mTLS)": "PEM-Dateien, für einen Server, der eines verlangt (mTLS)",
+91
View File
@@ -0,0 +1,91 @@
// A provider editor's certificate rows under Advanced, for an https://
// address: Client certificate (#5596, mTLS), and Server certificate
// (Zhangzhangi on X), the pin it trusts, shown as off, or the certificate
// the server shows, to trust after checking its fingerprint. app.js
// imports this when it draws the editor, so it weighs nothing on the core.
// colonHex is a SHA-256 pin as fingerprints are read: AB:CD:…
const colonHex = (h) => (String(h).toUpperCase().match(/../g) || []).join(":");
function drawPin(pin, draft, peek, seen) {
const again = (s) => drawPin(pin, draft, peek, s);
pin.replaceChildren();
if (draft.serverPin) {
const off = el("div", "pin-off", t("Certificate not verified: only this one is accepted"));
const fp = el("code", "pin-fp", colonHex(draft.serverPin));
const drop = el("button", "text action pin-drop", t("Verify it again"));
drop.onclick = (e) => { e.preventDefault(); draft.serverPin = ""; again(); };
pin.append(off, fp, drop);
return;
}
if (!seen) {
const go = el("button", "text action pin-peek", t("Trust its certificate…"));
go.onclick = async (e) => {
e.preventDefault();
go.classList.add("busy");
go.disabled = true;
try { again(await peek()); } catch (err) {
again();
pin.append(el("div", "hint err", err.message));
} finally { go.classList.remove("busy"); }
};
pin.append(go);
return;
}
const card = el("div", "pin-seen");
card.append(el("code", "pin-fp", colonHex(seen.sha256)));
const until = new Date(seen.notAfter).toLocaleDateString(intlLang(), { year: "numeric", month: "short", day: "numeric" });
card.append(el("div", "hint", t("{subject}, issued by {issuer}, until {date}", { subject: seen.subject || "—", issuer: seen.issuer || "—", date: until })));
if (seen.checks) card.append(el("div", "hint", t("This computer already trusts it: nothing to pin.")));
else card.append(el("div", "hint err", seen.why));
const acts = el("div", "pin-acts");
if (!seen.checks) {
const yes = el("button", "text action pin-trust", t("Trust this certificate"));
yes.onclick = (e) => { e.preventDefault(); draft.serverPin = seen.sha256; again(); };
acts.append(yes);
}
const no = el("button", "text action pin-cancel", t("Cancel"));
no.onclick = (e) => { e.preventDefault(); again(); };
acts.append(no);
card.append(acts);
pin.append(card);
}
// tlsCertRows draws the rows where app.js left at. Server certificate is
// for an https:// address at a host the user chose (provider.PinHosts):
// every one of theirs and Remote magpie's, and a preset's pointed at their
// own server, never the vendor's own hosts; save has the Save body carry
// the pin. The client certificate's fields are saved by app.js itself.
window.tlsCertRows = function ({ p, pr, draft, at, certTakes, onHTTPS, addressOf, asTyped, show, save }) {
if (!at.isConnected) return;
const rows = [];
const takes = certTakes() || (p ? !!p.takesServerPin || (!!p.preset && !p.account) : !!pr) && (p?.preset || pr?.id) !== "google-vertex";
if (takes) rows.push(pinRow({ p, pr, draft, certTakes, addressOf, asTyped, show, save }));
if (certTakes()) {
const box = el("div", "client-cert");
for (const [k, label, hold] of [["clientCert", t("Certificate"), "client.pem"], ["clientKey", t("Key"), "client-key.pem"], ["serverCA", t("Server CA"), "ca.pem"]]) {
const i = input(draft[k] || "", "~/magpie-laptop/" + hold);
i.className = "words cert-" + k;
i.setAttribute("aria-label", label);
i.oninput = () => { draft[k] = i.value; };
box.append(i);
}
const crow = field(t("Client certificate"), box, t("PEM files, for a server that asks for one (mTLS)"));
rows.push(crow);
show(() => { for (const e of crow) e.style.display = onHTTPS() ? "" : "none"; });
}
at.replaceWith(...rows.flat());
};
function pinRow({ p, pr, draft, certTakes, addressOf, asTyped, show, save }) {
const host = (u) => { try { return new URL(String(u).trim()).hostname.toLowerCase(); } catch { return ""; } };
const own = new Set([pr?.chat, pr?.responses, pr?.anthropic, pr?.decide, ...(pr?.regions || []).flatMap((r) => [r.chat, r.responses, r.anthropic])].filter(Boolean).map(host));
const addrs = () => {
const us = ["chat", "responses", "anthropic", "gemini", "decide"].map(addressOf).filter((u) => /^\s*https:\/\//i.test(u));
return certTakes() ? us : us.filter((u) => host(u) && !own.has(host(u)));
};
const pin = el("div", "server-pin");
drawPin(pin, draft, () => api("provider/peekcert", { ...asTyped(), id: p?.id || "", preset: draft.preset || "" }));
const row = field(t("Server certificate"), pin, t("For your own server with a self-signed certificate. Check the fingerprint against the server's before you trust it; a certificate renewed later has to be trusted again."));
show(() => { for (const e of row) e.style.display = addrs().length || draft.serverPin ? "" : "none"; });
save((body) => { if (addrs().length || draft.serverPin) body.serverPin = addrs().length ? (draft.serverPin || "").trim() : ""; });
return row;
}
+43 -8
View File
@@ -155,6 +155,12 @@ type providerJSON struct {
ClientKey string `json:"clientKey,omitempty"`
ServerCA string `json:"serverCA,omitempty"`
TakesClientCert bool `json:"takesClientCert,omitempty"`
// the server certificate its own hosts are taken with alone, their
// certificate otherwise unchecked (provider.ServerPin)
ServerPin string `json:"serverPin,omitempty"`
// TakesServerPin: an https:// address of the user's own to pin
// (provider.PinHosts), a preset's pointed at their own server too
TakesServerPin bool `json:"takesServerPin,omitempty"`
// its Responses turns over the Responses WebSocket (provider.Socket,
// #5781): auto, on or ""; TakesSocket: a provider of a key with a
// Responses URL
@@ -850,7 +856,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
ID: p.ID, Name: p.Name, Icon: p.Icon, IconFrom: p.IconFrom, Preset: p.Preset, Host: p.Host(),
Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(),
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountWindowAmounts: p.AccountWindowAmounts, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, Billing: p.Billing, BillingKind: p.BillingKind(), InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, ClientCert: tilde(p.ClientCert), ClientKey: tilde(p.ClientKey), ServerCA: tilde(p.ServerCA), TakesClientCert: p.TakesClientCert(), Socket: p.Socket, TakesSocket: p.TakesSocket(), LimitRestOff: p.LimitRestOff, UpstreamProviders: p.UpstreamProviders, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(),
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountWindowAmounts: p.AccountWindowAmounts, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, Billing: p.Billing, BillingKind: p.BillingKind(), InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, ClientCert: tilde(p.ClientCert), ClientKey: tilde(p.ClientKey), ServerCA: tilde(p.ServerCA), TakesClientCert: p.TakesClientCert(), ServerPin: p.ServerPin, TakesServerPin: p.TakesServerPin(), Socket: p.Socket, TakesSocket: p.TakesSocket(), LimitRestOff: p.LimitRestOff, UpstreamProviders: p.UpstreamProviders, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(),
Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)),
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, UseFirst: p.UseFirst, NoStandIn: p.NoStandIn, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate,
@@ -1665,6 +1671,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
ClientCert *string `json:"clientCert"`
ClientKey *string `json:"clientKey"`
ServerCA *string `json:"serverCA"`
// ServerPin is the SHA-256 of the server certificate its own
// hosts are taken with alone (provider.ServerPin), "" to check
// them as usual; a save that leaves it out keeps it
ServerPin *string `json:"serverPin"`
// HTTP1 is whether its own hosts are spoken HTTP/1.1 to; a
// save that leaves it out keeps it
HTTP1 *bool `json:"http1"`
@@ -2110,7 +2120,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
if req.InsecureTLS != nil {
in.InsecureTLS = *req.InsecureTLS
}
in = withCerts(in, nil, req.ClientCert, req.ClientKey, req.ServerCA)
in = withCerts(in, nil, req.ClientCert, req.ClientKey, req.ServerCA, req.ServerPin)
if req.HTTP1 != nil {
in.HTTP1 = *req.HTTP1
}
@@ -2161,7 +2171,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
} else if old != nil {
in.InsecureTLS = old.InsecureTLS
}
in = withCerts(in, old, req.ClientCert, req.ClientKey, req.ServerCA)
in = withCerts(in, old, req.ClientCert, req.ClientKey, req.ServerCA, req.ServerPin)
if req.HTTP1 != nil {
in.HTTP1 = *req.HTTP1
} else if old != nil {
@@ -2756,7 +2766,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
}
saved := *p
if req.Typed {
q := withCerts(typed(*p, in, req.Proxy, req.InsecureTLS, req.HTTP1), p, req.ClientCert, req.ClientKey, req.ServerCA)
q := withCerts(typed(*p, in, req.Proxy, req.InsecureTLS, req.HTTP1), p, req.ClientCert, req.ClientKey, req.ServerCA, req.ServerPin)
p = &q
}
if len(req.Test) > 0 {
@@ -2793,7 +2803,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
}
p = *saved
}
p = withCerts(typed(p, in, req.Proxy, req.InsecureTLS, req.HTTP1), &p, req.ClientCert, req.ClientKey, req.ServerCA)
p = withCerts(typed(p, in, req.Proxy, req.InsecureTLS, req.HTTP1), &p, req.ClientCert, req.ClientKey, req.ServerCA, req.ServerPin)
if strings.TrimSpace(in.Decide) != "" {
// a decision API is asked its smallest question, at
// POST …/systemone (#647)
@@ -2864,6 +2874,27 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
fail(rw, err)
return
}
case "peekcert":
// the certificate the form's HTTPS address shows, taken
// unchecked, for its editor to offer it to be trusted
// (provider.ServerPin, Zhangzhangi on X)
var p provider.Provider
if pr, err := provider.FromPreset(in.Preset); err == nil {
p = pr
}
if old, err := provider.Find(in.ID); err == nil && in.ID != "" {
p = *old
}
p = withCerts(typed(p, in, req.Proxy, req.InsecureTLS, req.HTTP1), &p, req.ClientCert, req.ClientKey, req.ServerCA, req.ServerPin)
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
seen, err := p.PeekServerCert(ctx)
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, seen)
return
case "list":
// the vendor's list for the form as it stands, nothing saved:
// the add form's Fetch models, picked from before the provider
@@ -2875,7 +2906,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
if p.Name == "" {
p.Name = cmp.Or(strings.TrimSpace(in.Name), "the vendor")
}
p = withCerts(typed(p, in, req.Proxy, req.InsecureTLS, req.HTTP1), &p, req.ClientCert, req.ClientKey, req.ServerCA)
p = withCerts(typed(p, in, req.Proxy, req.InsecureTLS, req.HTTP1), &p, req.ClientCert, req.ClientKey, req.ServerCA, req.ServerPin)
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
all, err := p.ListAll(ctx)
@@ -2919,7 +2950,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
defer cancel()
ask := *p
if req.Typed {
ask = withCerts(typed(*p, in, req.Proxy, req.InsecureTLS, req.HTTP1), p, req.ClientCert, req.ClientKey, req.ServerCA)
ask = withCerts(typed(*p, in, req.Proxy, req.InsecureTLS, req.HTTP1), p, req.ClientCert, req.ClientKey, req.ServerCA, req.ServerPin)
}
ms, dropped, err := ask.Refetch(ctx)
if err != nil {
@@ -3453,7 +3484,7 @@ func typed(p, in provider.Provider, proxy *string, insecureTLS, http1 *bool) pro
// or an unsaved test typed (#5596), each one left out kept from old (nil:
// none); a ~ is taken as home, as a save keeps it, so an unsaved test
// reads the same files.
func withCerts(p provider.Provider, old *provider.Provider, cert, key, ca *string) provider.Provider {
func withCerts(p provider.Provider, old *provider.Provider, cert, key, ca, pin *string) provider.Provider {
var kept provider.Provider
if old != nil {
kept = *old
@@ -3471,6 +3502,10 @@ func withCerts(p provider.Provider, old *provider.Provider, cert, key, ca *strin
p.ClientCert = pick(cert, kept.ClientCert)
p.ClientKey = pick(key, kept.ClientKey)
p.ServerCA = pick(ca, kept.ServerCA)
p.ServerPin = kept.ServerPin
if pin != nil {
p.ServerPin = strings.TrimSpace(*pin) // Save keeps it as netproxy.NormalPin has it, or says why
}
return p
}
+3 -2
View File
@@ -159,7 +159,8 @@ test("compat.js is the first of the page's own scripts", async () => {
// Export or Import opens, agentcompact.js when an agent sheet holds Long
// conversations, balfound.js when the editor draws a relay's balance
// with no Balance URL, passerrors.js when it draws a key provider's
// Errors, keybalance.js when it draws a key whose vendor tells no
// Errors, tlscerts.js when it draws the certificate rows,
// keybalance.js when it draws a key whose vendor tells no
// balance, modellimits.js when it draws a model's row, notices.js when
// About's Open-source licenses opens, videogen.js when Settings draws
// Image generation, provlinks.js when Settings' search first wants its
@@ -177,7 +178,7 @@ test("compat.js is the first of the page's own scripts", async () => {
// pipecheck.js when Settings draws Models;
// the checks above
// still read them
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
});
test("the styles hold up in Safari 15.0", async () => {
@@ -0,0 +1,261 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A Remote magpie (or a provider of the user's) at https:// with a
// self-signed certificate (Zhangzhangi on X): the editor's Advanced holds a
// Server certificate row. "Trust its certificate…" asks provider/peekcert,
// shows the fingerprint and why this computer refuses it, and "Trust this
// certificate" pins it; Save sends serverPin. A pinned one says in red that
// verification is off, and "Verify it again" clears it. A preset pointed at
// a server of the user's own takes one too (LM Studio at https://lms.box.lan,
// "建议对别的自签名域名也生效"), with no client certificate. None at http://
// or at a vendor's own address. Every language, 1100px and 420px, Chromium and WebKit; no
// backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const file = async (route, url) => {
const f = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(f)];
await route.fulfill({ body: await fs.readFile(f), contentType });
};
const boot = (route, lang) => route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
const SHA = "3f".repeat(16) + "a0".repeat(16);
const PINNED = "ab".repeat(32);
const colon = (h) => h.toUpperCase().match(/../g).join(":");
const WHY = 'x509: "api.magpie.local" certificate is not standards compliant';
const base = {
icon: "generic", chat: "", responses: "", anthropic: "", catalog: "",
models: [{ id: "m", name: "m", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "mk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "",
};
const remote = { ...base, id: "remote-magpie", name: "Remote magpie", preset: "remote-magpie", icon: "magpie", chat: "https://api.magpie.local:13003/v1", takesClientCert: true };
const own = { ...base, id: "box", name: "Own Box", chat: "https://box.example/v1", takesClientCert: true };
const pinned = { ...base, id: "pinned", name: "Pinned Box", chat: "https://pinned.example/v1", takesClientCert: true, serverPin: PINNED };
const plain = { ...base, id: "plain", name: "Plain Box", chat: "http://192.168.1.21:8000/v1", takesClientCert: true };
const lms = { ...base, id: "lmstudio", name: "LM Studio Box", preset: "lmstudio", icon: "lmstudio", chat: "https://lms.box.lan/v1", takesClientCert: false, takesServerPin: true };
const openai = { ...base, id: "openai", name: "OpenAI", preset: "openai", chat: "https://api.openai.example/v1", takesClientCert: false };
const en = {
row: "Server certificate",
hint: "For your own server with a self-signed certificate. Check the fingerprint against the server's before you trust it; a certificate renewed later has to be trusted again.",
peek: "Trust its certificate…",
trust: "Trust this certificate",
off: "Certificate not verified: only this one is accepted",
again: "Verify it again",
seen: "{subject}, issued by {issuer}, until {date}",
trusted: "This computer already trusts it: nothing to pin.",
};
function server(lang, posts, peek) {
const providers = {
providers: [remote, own, pinned, plain, lms, openai],
presets: [
{ id: "openai", name: "OpenAI", kind: "vendor", icon: "openai", chat: "https://api.openai.example/v1", added: true },
{ id: "remote-magpie", name: "Remote magpie", kind: "magpie", icon: "magpie", chat: "", added: true },
{ id: "lmstudio", name: "LM Studio", kind: "local", icon: "lmstudio", chat: "http://localhost:1234/v1", added: true },
],
excluded: [], gateway: { running: true, window: true },
};
return async (route) => {
const url = new URL(route.request().url());
const json = (data, status = 200) => route.fulfill({ json: data, status });
if (url.pathname === "/boot.js") return boot(route, lang);
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") {
const action = url.pathname.slice("/api/provider/".length);
posts.push({ action, body: route.request().postDataJSON() });
if (action === "peekcert") return peek.error ? json({ error: peek.error }, 400) : json(peek.seen);
return json(providers);
}
if (url.pathname.startsWith("/api/")) return json({});
await file(route, url);
};
}
async function open(browser, lang, name, width, peek = {}) {
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const posts = [];
await page.route("**/*", server(lang, posts, peek));
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: name }).first().click();
await page.locator(".editor .bar").waitFor();
const adv = page.locator(".editor details.advanced");
return { page, errors, posts, adv };
}
const words = (page, keys) => page.evaluate((ks) => Object.fromEntries(ks.map((k) => [k, t(k)])), keys);
async function save(page, posts) {
const n = posts.length;
const label = await page.evaluate(() => t("Save"));
await page.locator(".editor .bar").getByRole("button", { name: label, exact: true }).click();
for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50);
return posts.at(-1);
}
async function fits(page, box, width) {
const bad = await box.evaluate((b, width) => {
const out = [];
for (const e of b.querySelectorAll("button, code, .hint, .pin-off")) {
const r = e.getBoundingClientRect();
if (r.width === 0) continue;
if (r.right > width + 0.5) out.push(e.className + " " + r.right + ">" + width);
if (e.matches("button") && e.scrollWidth > e.clientWidth + 1) out.push("cut: " + e.textContent);
}
if (document.documentElement.scrollWidth > innerWidth) out.push("page scrolls sideways");
return out;
}, width);
assert.deepEqual(bad, []);
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a self-signed server certificate is trusted by fingerprint (Zhangzhangi on X)", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
await t.test("every language has the strings", async () => {
const { page } = await open(browser, "en", "Plain Box", 1100);
for (const lang of ["zh", "zh-TW", "ja", "de"]) {
const missing = await page.evaluate(([lang, keys]) => keys.filter((k) => !I18N[lang]?.[k] || I18N[lang][k] === k), [lang, Object.values(en)]);
assert.deepEqual(missing, [], lang);
}
await page.context().close();
});
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [1100, 420]) {
for (const name of ["Remote magpie", "Own Box"]) {
await t.test(`${lang} ${width}px ${name}: peek, trust, save`, async () => {
const seen = { host: "api.magpie.local:13003", sha256: SHA, subject: "api.magpie.local", issuer: "api.magpie.local", notAfter: "2027-11-10T00:00:00Z", checks: false, why: WHY };
const { page, errors, posts, adv } = await open(browser, lang, name, width, { seen });
const w = await words(page, Object.values(en));
if (lang !== "en") for (const s of Object.values(en)) assert.notEqual(w[s], s, `"${s}" has no ${lang} translation`);
assert.equal(await adv.evaluate((d) => d.open), false, "folded with nothing set");
await adv.locator(":scope > summary").click();
const box = page.locator(".editor .server-pin");
await box.waitFor();
assert.ok(await page.locator(".editor", { hasText: w[en.row] }).count() > 0);
assert.equal(await box.locator(".pin-off").count(), 0, "verified until asked");
await box.locator(".pin-peek").click();
const card = box.locator(".pin-seen");
await card.waitFor();
const peeked = posts.find((p) => p.action === "peekcert");
assert.equal(peeked.body.id, name === "Remote magpie" ? "remote-magpie" : "box");
assert.equal((await card.locator(".pin-fp").textContent()).trim(), colon(SHA));
assert.equal((await card.locator(".hint.err").textContent()).trim(), WHY);
await fits(page, box, width);
await card.locator(".pin-trust").click();
await box.locator(".pin-off").waitFor();
assert.equal((await box.locator(".pin-off").textContent()).trim(), w[en.off]);
const red = await box.locator(".pin-off").evaluate((e) => getComputedStyle(e).color);
assert.notEqual(red, "rgb(0, 0, 0)", "said in red, not plain text");
const border = await box.locator(".pin-off").evaluate((e) => getComputedStyle(e).borderLeftWidth);
assert(border === "0px" || border === "", "no left border accent: " + border);
assert.equal((await box.locator(".pin-fp").textContent()).trim(), colon(SHA));
await fits(page, box, width);
const saved = await save(page, posts);
assert.equal(saved.action, "save");
assert.equal(saved.body.serverPin, SHA);
assert.deepEqual(errors, []);
await page.context().close();
});
}
}
}
await t.test("a pinned one says so, and Verify it again clears it", async () => {
const { page, errors, posts, adv } = await open(browser, "zh", "Pinned Box", 420);
assert.equal(await adv.evaluate((d) => d.open), true, "opens with a pin set");
const box = page.locator(".editor .server-pin");
const w = await words(page, [en.off]);
assert.equal((await box.locator(".pin-off").textContent()).trim(), w[en.off]);
assert.equal((await box.locator(".pin-fp").textContent()).trim(), colon(PINNED));
await box.locator(".pin-drop").click();
await box.locator(".pin-peek").waitFor();
const saved = await save(page, posts);
assert.equal(saved.body.serverPin, "");
assert.deepEqual(errors, []);
await page.context().close();
});
await t.test("a certificate this computer trusts offers no pin", async () => {
const seen = { host: "box.example", sha256: SHA, subject: "box.example", issuer: "R11", notAfter: "2027-01-01T00:00:00Z", checks: true, why: "" };
const { page, errors, adv } = await open(browser, "en", "Own Box", 1100, { seen });
await adv.locator(":scope > summary").click();
const box = page.locator(".editor .server-pin");
await box.locator(".pin-peek").click();
await box.locator(".pin-seen").waitFor();
assert.equal(await box.locator(".pin-trust").count(), 0);
assert.ok((await box.locator(".pin-seen").textContent()).includes(en.trusted));
await box.locator(".pin-cancel").click();
await box.locator(".pin-peek").waitFor();
assert.deepEqual(errors, []);
await page.context().close();
});
await t.test("a server that can't be reached says why", async () => {
const { page, errors, adv } = await open(browser, "en", "Own Box", 1100, { error: "dial tcp: connection refused" });
await adv.locator(":scope > summary").click();
const box = page.locator(".editor .server-pin");
await box.locator(".pin-peek").click();
await box.locator(".hint.err").waitFor();
assert.ok((await box.locator(".hint.err").textContent()).includes("connection refused"));
assert.equal(await box.locator(".pin-peek").isEnabled(), true, "can ask again");
assert.deepEqual(errors, []);
await page.context().close();
});
await t.test("a preset at the user's own https server takes a pin, and no client certificate", async () => {
const seen = { host: "lms.box.lan", sha256: SHA, subject: "lms.box.lan", issuer: "lms.box.lan", notAfter: "2027-11-10T00:00:00Z", checks: false, why: WHY };
const { page, errors, posts, adv } = await open(browser, "zh", "LM Studio Box", 420, { seen });
await adv.locator(":scope > summary").click();
const box = page.locator(".editor .server-pin");
await box.waitFor();
assert.equal(await page.locator(".editor .client-cert").count(), 0, "a client certificate stays for a provider of the user's own");
await box.locator(".pin-peek").click();
await box.locator(".pin-trust").click();
await box.locator(".pin-off").waitFor();
await fits(page, box, 420);
const saved = await save(page, posts);
assert.equal(saved.body.serverPin, SHA);
assert.equal("clientCert" in saved.body, false);
assert.deepEqual(errors, []);
await page.context().close();
});
await t.test("none at http:// or at a vendor's own address", async () => {
{
const { page, errors, adv } = await open(browser, "en", "Plain Box", 1100);
await adv.locator(":scope > summary").click();
assert.equal(await page.locator(".editor .server-pin").isVisible(), false, "none at http://");
assert.deepEqual(errors, []);
await page.context().close();
}
{
const { page, errors, posts, adv } = await open(browser, "en", "OpenAI", 1100);
await adv.locator(":scope > summary").click();
assert.equal(await page.locator(".editor .server-pin").isVisible(), false, "none at the vendor's own address");
const saved = await save(page, posts);
assert.equal("serverPin" in saved.body, false, "a preset's Save sends none");
assert.deepEqual(errors, []);
await page.context().close();
}
});
});
}
+85 -7
View File
@@ -1,9 +1,12 @@
package netproxy
import (
"cmp"
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"errors"
"fmt"
"net/http"
@@ -22,8 +25,8 @@ type clientCertKey struct{}
// the server, and the PEM CA its server's certificate may also be signed
// by (a magpie's own, `magpie mtls`), at the hosts of its own base URLs.
type clientCert struct {
cert, key, ca string
hosts map[string]bool
cert, key, ca, pin string
hosts map[string]bool
}
// WithClientCert is ctx for requests made on behalf of a provider that
@@ -37,12 +40,18 @@ type clientCert struct {
// — is sent without them, and an https:// proxy is refused for it, as the
// proxy's TLS would be dialled with them (clientTLS). With (a request
// made for another provider) drops it.
func WithClientCert(ctx context.Context, cert, key, ca string, bases ...string) context.Context {
c := clientCert{cert: strings.TrimSpace(cert), key: strings.TrimSpace(key), ca: strings.TrimSpace(ca), hosts: map[string]bool{}}
//
// pin, the SHA-256 of a server certificate the user trusted as it is
// (Zhangzhangi on X: a magpie at home on a domain of its own with a
// self-signed certificate), has the certificate's chain and name left
// unchecked at those hosts, and the handshake refused unless the
// server's own certificate is that one (pinTLS).
func WithClientCert(ctx context.Context, cert, key, ca, pin string, bases ...string) context.Context {
c := clientCert{cert: strings.TrimSpace(cert), key: strings.TrimSpace(key), ca: strings.TrimSpace(ca), pin: NormalPin(pin), hosts: map[string]bool{}}
if c.cert == "" || c.key == "" {
c.cert, c.key = "", ""
}
if c.cert == "" && c.ca == "" {
if c.cert == "" && c.ca == "" && c.pin == "" {
return ctx
}
for _, b := range bases {
@@ -68,7 +77,8 @@ func clientCertOf(ctx context.Context) *clientCert {
// clientRoute is the route's name for req's own TLS identity
// (WithClientCert), "" when it has none: the files, and when each was
// last changed, so a certificate renewed in place is dialled with anew.
// last changed, so a certificate renewed in place is dialled with anew,
// and the pinned server certificate.
func clientRoute(req *http.Request) string {
c := clientCertOf(req.Context())
if c == nil || req.URL == nil || !strings.EqualFold(req.URL.Scheme, "https") || !c.hosts[hostKey(req.URL)] {
@@ -84,6 +94,7 @@ func clientRoute(req *http.Request) string {
}
b.WriteByte(0)
}
b.WriteString(c.pin)
return b.String()
}
@@ -106,7 +117,7 @@ func clientTLS(t *http.Transport, route string) {
f, _, _ := strings.Cut(parts[i], "\x01")
return f
}
cert, key, ca := file(0), file(1), file(2)
cert, key, ca, pin := file(0), file(1), file(2), file(3)
if t.TLSClientConfig == nil {
t.TLSClientConfig = &tls.Config{}
}
@@ -127,6 +138,9 @@ func clientTLS(t *http.Transport, route string) {
return pair, perr
}
}
if pin != "" {
pinTLS(cfg, pin)
}
if ca != "" {
pool, err := caPool(ca)
if err != nil {
@@ -147,6 +161,10 @@ func clientTLS(t *http.Transport, route string) {
}
}
// CAPool is caPool for a caller outside: the system's roots with the
// PEM file ca's beside them.
func CAPool(ca string) (*x509.CertPool, error) { return caPool(ca) }
// caPool is the system's roots with the CA in the PEM file ca beside
// them: a server signed by either is taken.
func caPool(ca string) (*x509.CertPool, error) {
@@ -192,3 +210,63 @@ func CheckClientCert(cert, key, ca string) error {
}
return nil
}
// pinTLS has cfg take the server certificate whose SHA-256 is pin, and
// no other: its chain, its name and its dates aren't checked (a
// self-signed one, or one macOS calls not standards compliant), and any
// other certificate fails the handshake, a CA's that checks included.
func pinTLS(cfg *tls.Config, pin string) {
cfg.InsecureSkipVerify = true
cfg.VerifyConnection = func(cs tls.ConnectionState) error {
if len(cs.PeerCertificates) == 0 {
return errors.New("the server showed no certificate")
}
if got := CertSHA256(cs.PeerCertificates[0]); got != pin {
return &PinMismatchError{Host: cmp.Or(cs.ServerName, "the server"), Got: got, Want: pin}
}
return nil
}
}
// PinMismatchError is why a server whose certificate was pinned isn't
// spoken to: it showed another one.
type PinMismatchError struct{ Host, Got, Want string }
func (e *PinMismatchError) Error() string {
return fmt.Sprintf("%s showed a certificate other than the one trusted (SHA-256 %s, trusted %s): if the server's certificate was renewed, trust the new one in its editor; if not, another machine may be answering at its address", e.Host, ColonHex(e.Got), ColonHex(e.Want))
}
// CertSHA256 is c's fingerprint as a pin is kept: the SHA-256 of its DER,
// in lower-case hex.
func CertSHA256(c *x509.Certificate) string {
h := sha256.Sum256(c.Raw)
return hex.EncodeToString(h[:])
}
// NormalPin is a typed SHA-256 fingerprint as a pin is kept: lower-case
// hex, its colons, spaces and a "sha256:" before it taken out; "" for
// one that isn't 64 hex digits.
func NormalPin(s string) string {
s = strings.ToLower(strings.TrimSpace(s))
s = strings.TrimPrefix(strings.TrimPrefix(s, "sha256:"), "sha256/")
s = strings.NewReplacer(":", "", " ", "", "-", "").Replace(s)
if len(s) != 64 {
return ""
}
if _, err := hex.DecodeString(s); err != nil {
return ""
}
return s
}
// ColonHex is a pin as people read fingerprints: AB:CD:….
func ColonHex(pin string) string {
var b strings.Builder
for i := 0; i+1 < len(pin); i += 2 {
if i > 0 {
b.WriteByte(':')
}
b.WriteString(strings.ToUpper(pin[i : i+2]))
}
return b.String()
}
+4 -4
View File
@@ -98,7 +98,7 @@ func TestClientCertOnlyItsHost(t *testing.T) {
t.Cleanup(d.CloseIdleConnections)
c := &http.Client{Transport: d}
bg := context.Background()
mine := WithClientCert(bg, cert, key, ca, own.URL+"/v1")
mine := WithClientCert(bg, cert, key, ca, "", own.URL+"/v1")
if _, err := body(t, c, bg, own.URL); !certRefused(err) {
t.Fatalf("without them: want a certificate error, got %v", err)
@@ -115,7 +115,7 @@ func TestClientCertOnlyItsHost(t *testing.T) {
if _, err := body(t, c, With(mine, ""), own.URL); !certRefused(err) {
t.Fatalf("a request made for another provider: want a certificate error, got %v", err)
}
if _, err := body(t, c, WithClientCert(bg, cert, key, ca, "http://"+strings.TrimPrefix(own.URL, "https://")), own.URL); !certRefused(err) {
if _, err := body(t, c, WithClientCert(bg, cert, key, ca, "", "http://"+strings.TrimPrefix(own.URL, "https://")), own.URL); !certRefused(err) {
t.Fatalf("an http:// base: want a certificate error, got %v", err)
}
}
@@ -131,7 +131,7 @@ func TestServerCAAlone(t *testing.T) {
d := Dispatch(&http.Transport{Proxy: Func}).(*dispatch)
t.Cleanup(d.CloseIdleConnections)
c := &http.Client{Transport: d}
ctx := WithClientCert(context.Background(), "", "", ca, lenient.URL, strict.URL)
ctx := WithClientCert(context.Background(), "", "", ca, "", lenient.URL, strict.URL)
if got, err := body(t, c, ctx, lenient.URL); err != nil || got != "none" {
t.Fatalf("CA alone: %q, %v", got, err)
}
@@ -148,7 +148,7 @@ func TestClientCertRenewedInPlace(t *testing.T) {
cert, key, ca := device(t, st, "old")
d := Dispatch(&http.Transport{Proxy: Func, DisableKeepAlives: true}).(*dispatch)
c := &http.Client{Transport: d}
ctx := WithClientCert(context.Background(), cert, key, ca, s.URL)
ctx := WithClientCert(context.Background(), cert, key, ca, "", s.URL)
if got, _ := body(t, c, ctx, s.URL); got != "old" {
t.Fatalf("got %q", got)
}
+123
View File
@@ -0,0 +1,123 @@
package netproxy
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"errors"
"io"
"log"
"math/big"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/mtls"
)
func pinServer(t *testing.T, answer string) *httptest.Server {
t.Helper()
s := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, answer) }))
s.Config.ErrorLog = log.New(io.Discard, "", 0)
s.TLS = &tls.Config{Certificates: []tls.Certificate{freshCert(t)}}
s.StartTLS()
t.Cleanup(s.Close)
return s
}
// A pinned server certificate (Zhangzhangi on X) is taken at the hosts it
// is given for, unchecked otherwise: another host is checked as before,
// another certificate at a pinned host is refused, a certificate a
// trusted CA signed included, and a request made for another provider
// (With) doesn't carry the pin.
func TestPinOnlyThatCertificate(t *testing.T) {
own := pinServer(t, "own")
other := pinServer(t, "other")
d := Dispatch(&http.Transport{Proxy: Func, ForceAttemptHTTP2: true}).(*dispatch)
t.Cleanup(d.CloseIdleConnections)
c := &http.Client{Transport: d}
bg := context.Background()
pin := CertSHA256(own.Certificate())
if _, err := body(t, c, bg, own.URL); !certRefused(err) {
t.Fatalf("not pinned: %v", err)
}
ctx := WithClientCert(bg, "", "", "", ColonHex(pin), own.URL+"/v1")
if got, err := body(t, c, ctx, own.URL+"/v1/models"); err != nil || got != "own" {
t.Fatalf("pinned: %q, %v", got, err)
}
if _, err := body(t, c, ctx, other.URL); !certRefused(err) {
t.Fatalf("another host under the same ctx: %v", err)
}
if _, err := body(t, c, With(ctx, ""), own.URL); !certRefused(err) {
t.Fatalf("made for another provider: %v", err)
}
var mis *PinMismatchError
wrong := WithClientCert(bg, "", "", "", pin, other.URL)
if _, err := body(t, c, wrong, other.URL); !errors.As(err, &mis) || mis.Got != CertSHA256(other.Certificate()) {
t.Fatalf("another certificate at a pinned host: %v", err)
}
// a server the given CA signs, pinned to another certificate: the pin
// wins over the CA
st := mtls.Store{Dir: t.TempDir()}
signed := mtlsServer(t, st, false, nil)
_, _, ca := device(t, st, "x")
if _, err := body(t, c, WithClientCert(bg, "", "", ca, "", signed.URL), signed.URL); err != nil {
t.Fatalf("CA alone: %v", err)
}
if _, err := body(t, c, WithClientCert(bg, "", "", ca, pin, signed.URL), signed.URL); !errors.As(err, &mis) {
t.Fatalf("CA and another pin: %v", err)
}
}
func TestNormalPin(t *testing.T) {
h := strings.Repeat("0a", 32)
for in, want := range map[string]string{
h: h,
strings.ToUpper(h): h,
ColonHex(h): h,
"sha256:" + ColonHex(h): h,
" " + strings.ToUpper(h) + "\n": h,
"abcd": "",
strings.Repeat("zz", 32): "",
"": "",
} {
if got := NormalPin(in); got != want {
t.Errorf("NormalPin(%q) = %q, want %q", in, got, want)
}
}
}
// freshCert is a self-signed certificate of its own for 127.0.0.1:
// httptest's servers all show one built-in certificate, so a server that
// must show another needs this.
func freshCert(t *testing.T) tls.Certificate {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(time.Now().UnixNano()),
Subject: pkix.Name{CommonName: "api.magpie.local"},
DNSNames: []string{"api.magpie.local"},
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}
}
+126
View File
@@ -1,10 +1,18 @@
package provider
import (
"context"
"crypto/x509"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/yetone/magpie/internal/netproxy"
)
// TakesInsecureTLS is whether the provider may have its certificate left
@@ -24,6 +32,48 @@ func (p Provider) TakesClientCert() bool {
return p.Account == nil && (p.Preset == "" || p.IsRemoteMagpie()) && !p.IsVertex() && hasEndpoint(p) && !subscriptionID(p.ID)
}
// PinHosts are the base URLs a trusted server certificate (ServerPin) is
// taken at: every endpoint of a provider that takes a client certificate
// (TakesClientCert), and of a preset's only the https:// addresses the user
// gave it at a host of their own (Ollama on another computer, an Azure
// resource), never the vendor's own hosts (Zhangzhangi on X). None for a
// subscription's or a plugin's account.
func (p Provider) PinHosts() []string {
if p.TakesClientCert() {
return p.UncheckedHosts()
}
if p.Account != nil || p.Preset == "" || p.IsVertex() || subscriptionID(p.ID) {
return nil
}
pr := Preset(p.Preset)
if pr == nil {
return nil
}
own := map[string]bool{}
for _, u := range []string{pr.Chat, pr.Responses, pr.Anthropic, pr.Decide} {
own[pinName(u)] = true
}
for _, r := range pr.Regions {
for _, u := range []string{r.Chat, r.Responses, r.Anthropic} {
own[pinName(u)] = true
}
}
var out []string
for _, u := range p.UncheckedHosts() {
if h := pinName(u); h != "" && !own[h] && strings.HasPrefix(strings.ToLower(strings.TrimSpace(u)), "https://") {
out = append(out, u)
}
}
return out
}
// TakesServerPin is whether the provider may trust a server certificate
// of its own by fingerprint (ServerPin): it has an address PinHosts takes.
func (p Provider) TakesServerPin() bool { return len(p.PinHosts()) > 0 }
// pinName is u's host name as PinHosts compares them.
func pinName(u string) string { return strings.ToLower(hostnameOf(strings.TrimSpace(u))) }
// UncheckedHosts are the base URLs whose host's certificate is taken as it
// is when the provider has InsecureTLS: its own endpoints, never a models,
// balance or image URL elsewhere.
@@ -57,3 +107,79 @@ func CertPath(p string) (string, error) {
}
return filepath.Clean(p), nil
}
// ServerCertSeen is the certificate a provider's HTTPS host shows, as its
// editor offers it to be trusted (ServerPin).
type ServerCertSeen struct {
// Host is the host:port asked
Host string `json:"host"`
// SHA256 is its fingerprint as ServerPin keeps it
SHA256 string `json:"sha256"`
// Subject and Issuer are the names it is issued to and by; Names its
// DNS names and addresses
Subject string `json:"subject"`
Issuer string `json:"issuer"`
Names []string `json:"names,omitempty"`
// NotBefore and NotAfter are when it is good from and until
NotBefore time.Time `json:"notBefore"`
NotAfter time.Time `json:"notAfter"`
// Checks is whether this computer would take it without a pin: then
// there's nothing to trust; Why is why not
Checks bool `json:"checks"`
Why string `json:"why,omitempty"`
}
// PeekServerCert is the certificate p's first HTTPS base URL shows,
// asked through p's own proxy (and with its client certificate, when the
// server asks for one) with the certificate taken unchecked, so the user
// can see its fingerprint before trusting it (trust on first use). Its
// pin, if it has one, plays no part.
func (p Provider) PeekServerCert(ctx context.Context) (ServerCertSeen, error) {
var base *url.URL
for _, h := range p.PinHosts() {
if u, err := url.Parse(strings.TrimSpace(h)); err == nil && strings.EqualFold(u.Scheme, "https") && u.Hostname() != "" {
base = u
break
}
}
if base == nil {
return ServerCertSeen{}, errors.New("it has no https:// address: there's no certificate to trust")
}
p.ServerPin = ""
ctx = netproxy.WithUncheckedTLS(p.Via(ctx), base.String())
req, err := http.NewRequestWithContext(ctx, http.MethodGet, base.String(), nil)
if err != nil {
return ServerCertSeen{}, err
}
c := &http.Client{Transport: http.DefaultClient.Transport, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
res, err := c.Do(req)
if err != nil {
return ServerCertSeen{}, err
}
res.Body.Close()
if res.TLS == nil || len(res.TLS.PeerCertificates) == 0 {
return ServerCertSeen{}, errors.New("it answered without a certificate")
}
leaf := res.TLS.PeerCertificates[0]
seen := ServerCertSeen{Host: base.Host, SHA256: netproxy.CertSHA256(leaf), Subject: leaf.Subject.String(), Issuer: leaf.Issuer.String(), Names: leaf.DNSNames, NotBefore: leaf.NotBefore, NotAfter: leaf.NotAfter}
for _, ip := range leaf.IPAddresses {
seen.Names = append(seen.Names, ip.String())
}
mid := x509.NewCertPool()
for _, c := range res.TLS.PeerCertificates[1:] {
mid.AddCert(c)
}
opts := x509.VerifyOptions{DNSName: base.Hostname(), Intermediates: mid}
if p.ServerCA != "" {
// a server its own CA signs is checked already: nothing to pin
if pool, err := netproxy.CAPool(p.ServerCA); err == nil {
opts.Roots = pool
}
}
if _, err := leaf.Verify(opts); err != nil {
seen.Why = err.Error()
} else {
seen.Checks = true
}
return seen, nil
}
+17
View File
@@ -498,6 +498,15 @@ type Provider struct {
ClientKey string `json:"clientKey,omitempty"`
ServerCA string `json:"serverCA,omitempty"`
// ServerPin is the SHA-256 (lower-case hex) of the one server
// certificate its own HTTPS hosts are taken with, trusted as it is
// (Zhangzhangi on X: a magpie at home on a domain of its own with a
// self-signed certificate, which macOS calls not standards
// compliant): the certificate's chain, name and dates aren't checked
// there, and any other certificate is refused. "" checks them as
// usual. Taken where TakesClientCert is; see Via and PeekServerCert.
ServerPin string `json:"serverPin,omitempty"`
// Proxy is the proxy magpie's requests to this provider go through
// (#237: Codex through one, a vendor at home without): "" follows
// the global one (Settings' Proxy, the environment's, the system's),
@@ -1293,6 +1302,14 @@ func Save(p Provider) error {
if p.HTTP1 && !p.TakesInsecureTLS() {
return fmt.Errorf("%s is a preset's: only a provider you added with your own base URL can be held to HTTP/1.1", p.Name)
}
if v := strings.TrimSpace(p.ServerPin); v != "" {
if p.ServerPin = netproxy.NormalPin(v); p.ServerPin == "" {
return fmt.Errorf("%s: %q isn't a certificate's SHA-256 fingerprint (64 hex digits)", p.ID, v)
}
if !p.TakesServerPin() {
return fmt.Errorf("%s: a trusted server certificate is only for an https:// address of your own: a provider you added with a base URL of its own, Remote magpie, or a preset you pointed at your own server", p.ID)
}
}
if p.ClientCert != "" || p.ClientKey != "" || p.ServerCA != "" {
if !p.TakesClientCert() {
return fmt.Errorf("%s: a client certificate or server CA is only for a provider you added with a base URL of its own, or Remote magpie", p.ID)
+11 -3
View File
@@ -15,7 +15,9 @@ import (
// Via is ctx for requests made on the provider's behalf: they go through
// its own proxy (ProxyChoice), or the global one when it has none. A
// provider the user added and asked not to have its certificate checked
// (InsecureTLS) has its own hosts' taken as they are, no other host's;
// (InsecureTLS) has its own hosts' taken as they are, no other host's,
// and one whose server certificate the user trusted (ServerPin) has them
// taken with that certificate alone;
// one asked to be spoken HTTP/1.1 to (HTTP1) is, at its own hosts alone;
// one whose turns go over the Responses WebSocket (Socket) has them go
// there, at its Responses URL alone (SocketTurn).
@@ -27,8 +29,14 @@ func (p Provider) Via(ctx context.Context) context.Context {
if p.HTTP1 && p.TakesInsecureTLS() {
ctx = netproxy.WithHTTP1(ctx, p.UncheckedHosts()...)
}
if (p.ClientCert != "" || p.ServerCA != "") && p.TakesClientCert() {
ctx = netproxy.WithClientCert(ctx, p.ClientCert, p.ClientKey, p.ServerCA, p.UncheckedHosts()...)
cert, key, ca := p.ClientCert, p.ClientKey, p.ServerCA
if !p.TakesClientCert() {
cert, key, ca = "", "", ""
}
if cert != "" || ca != "" || p.ServerPin != "" {
if hosts := p.PinHosts(); len(hosts) > 0 {
ctx = netproxy.WithClientCert(ctx, cert, key, ca, p.ServerPin, hosts...)
}
}
return withSocket(ctx, p)
}
+256
View File
@@ -0,0 +1,256 @@
package provider
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"io"
"log"
"math/big"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/netproxy"
)
// Zhangzhangi on X: a Remote magpie on a domain of its own with a
// self-signed certificate. Its editor peeks at the certificate, the user
// trusts it (ServerPin), and then its models and its test go through;
// before, both fail on the certificate. A pin of another certificate is
// refused at the handshake, and another server at the same pin too.
func TestServerPinRemoteMagpie(t *testing.T) {
azureHome(t)
dialsOut(t)
srv := selfSignedVendor(t)
other := freshVendor(t)
ctx := context.Background()
if err := Save(Provider{ID: "home", Preset: RemoteMagpiePreset, Key: "remote-key", Chat: srv.URL}); err != nil {
t.Fatal(err)
}
p, _ := Find("home")
if _, err := p.List(ctx); !certError(err) {
t.Fatalf("not pinned: want a certificate error, got %v", err)
}
if rs := p.Test(ctx); len(rs) == 0 || rs[0].OK {
t.Fatalf("its test not pinned: %+v", rs)
}
seen, err := p.PeekServerCert(ctx)
if err != nil {
t.Fatal(err)
}
if want := netproxy.CertSHA256(srv.Certificate()); seen.SHA256 != want {
t.Fatalf("peeked %s, the server's is %s", seen.SHA256, want)
}
if seen.Checks || seen.Why == "" {
t.Fatalf("a self-signed certificate checks? %+v", seen)
}
p.ServerPin = netproxy.ColonHex(seen.SHA256) // as people copy it
if err := Save(*p); err != nil {
t.Fatal(err)
}
p, _ = Find("home")
if p.ServerPin != seen.SHA256 {
t.Fatalf("pin kept as %q", p.ServerPin)
}
if ms, err := p.List(ctx); err != nil || len(ms) != 1 {
t.Fatalf("pinned: %v %v", ms, err)
}
if rs := p.Test(ctx); len(rs) == 0 || !rs[0].OK {
t.Fatalf("its test pinned: %+v", rs)
}
// the same pin, another server answering at the provider's address
moved := *p
for _, f := range []*string{&moved.Chat, &moved.Responses, &moved.Anthropic, &moved.Gemini, &moved.Catalog, &moved.Decide, &moved.ModelsURL} {
*f = strings.ReplaceAll(*f, srv.URL, other.URL)
}
const other1 = "showed a certificate other than the one trusted"
if _, err := moved.List(ctx); err == nil || !strings.Contains(err.Error(), other1) {
t.Fatalf("another certificate at a pinned host: %v", err)
}
// a pin of another certificate
p.ServerPin = netproxy.CertSHA256(other.Certificate())
if err := Save(*p); err != nil {
t.Fatal(err)
}
p, _ = Find("home")
if _, err := p.List(ctx); err == nil || !strings.Contains(err.Error(), other1) || !strings.Contains(err.Error(), "trust the new one") {
t.Fatalf("pinned to another certificate: %v", err)
}
// taken off: checked as before
p.ServerPin = ""
if err := Save(*p); err != nil {
t.Fatal(err)
}
p, _ = Find("home")
if _, err := p.List(ctx); !certError(err) || strings.Contains(err.Error(), other1) {
t.Fatalf("pin taken off: %v", err)
}
}
// What Save refuses: a pin that isn't a SHA-256, and one on a preset's
// provider that takes no certificate of its own.
func TestServerPinSaveChecks(t *testing.T) {
azureHome(t)
good := strings.Repeat("ab", 32)
for name, c := range map[string]struct {
p Provider
ok bool
}{
"own": {Provider{ID: "home", Name: "Home", Chat: "https://home.example/v1", Key: "k", Models: []string{"m"}, ServerPin: good}, true},
"colons": {Provider{ID: "home2", Name: "Home2", Chat: "https://home2.example/v1", Key: "k", Models: []string{"m"}, ServerPin: "SHA256:" + netproxy.ColonHex(good)}, true},
"short": {Provider{ID: "home3", Name: "Home3", Chat: "https://home3.example/v1", Key: "k", Models: []string{"m"}, ServerPin: "abcd"}, false},
"not hex": {Provider{ID: "home4", Name: "Home4", Chat: "https://home4.example/v1", Key: "k", Models: []string{"m"}, ServerPin: strings.Repeat("zz", 32)}, false},
"a preset's": {Provider{ID: "openrouter", Preset: "openrouter", Key: "k", ServerPin: good}, false},
"a preset at home": {Provider{ID: "lmstudio", Preset: "lmstudio", Chat: "https://box.lan:1234/v1", ServerPin: good}, true},
} {
err := Save(c.p)
if (err == nil) != c.ok {
t.Errorf("%s: %v", name, err)
}
if c.ok {
if p, _ := Find(c.p.ID); p == nil || p.ServerPin != good {
t.Errorf("%s: kept as %+v", name, p)
}
}
}
}
// A preset pointed at a server of the user's own (LM Studio on another
// computer behind https) trusts its certificate by fingerprint too
// (Zhangzhangi on X: 建议对别的自签名域名也生效), with no client
// certificate sent there.
func TestServerPinPresetAtOwnServer(t *testing.T) {
azureHome(t)
dialsOut(t)
srv := selfSignedVendor(t)
ctx := context.Background()
if err := Save(Provider{ID: "lmstudio", Preset: "lmstudio", Chat: srv.URL + "/v1"}); err != nil {
t.Fatal(err)
}
p, _ := Find("lmstudio")
if !p.TakesServerPin() || len(p.PinHosts()) != 1 {
t.Fatalf("a preset at the user's own https host takes no pin: %v", p.PinHosts())
}
if _, err := p.List(ctx); !certError(err) {
t.Fatalf("not pinned: want a certificate error, got %v", err)
}
seen, err := p.PeekServerCert(ctx)
if err != nil {
t.Fatal(err)
}
p.ServerPin = seen.SHA256
if err := Save(*p); err != nil {
t.Fatal(err)
}
p, _ = Find("lmstudio")
if ms, err := p.List(ctx); err != nil || len(ms) != 1 {
t.Fatalf("pinned preset: %v %v", ms, err)
}
// a client certificate stays one for a provider that takes it
p.ClientCert, p.ServerCA = "/nowhere/client.pem", "/nowhere/ca.pem"
if _, err := p.List(ctx); err != nil {
t.Fatalf("a preset's client certificate was sent: %v", err)
}
}
// Every preset at the vendor's own addresses, its regions' too, takes no
// pin: a vendor's host is never trusted by a fingerprint.
func TestServerPinNoVendorHost(t *testing.T) {
for _, pr := range Presets() {
ps := []Provider{{Preset: pr.ID, Chat: pr.Chat, Responses: pr.Responses, Anthropic: pr.Anthropic, Decide: pr.Decide}}
for _, r := range pr.Regions {
ps = append(ps, Provider{Preset: pr.ID, Chat: r.Chat, Responses: r.Responses, Anthropic: r.Anthropic})
}
for _, p := range ps {
if p.IsRemoteMagpie() {
continue
}
if hs := p.PinHosts(); len(hs) > 0 {
t.Errorf("%s pins its vendor's %v", pr.ID, hs)
}
}
}
if (Provider{Preset: "openai", Chat: "http://box.lan/v1"}).TakesServerPin() {
t.Error("an http:// address has no certificate to pin")
}
if !(Provider{Preset: "openai", Chat: "https://box.lan/v1"}).TakesServerPin() {
t.Error("a preset at the user's own https host takes no pin")
}
}
// A server signed by the provider's own Server CA checks already, so the
// peek offers nothing to pin.
func TestServerPinPeekTakesItsCA(t *testing.T) {
azureHome(t)
dialsOut(t)
srv := selfSignedVendor(t)
ca := filepath.Join(t.TempDir(), "ca.pem")
if err := os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}), 0o600); err != nil {
t.Fatal(err)
}
p := Provider{ID: "home", Preset: RemoteMagpiePreset, Key: "remote-key", Chat: srv.URL}
seen, err := p.PeekServerCert(context.Background())
if err != nil || seen.Checks {
t.Fatalf("without its CA: %+v %v", seen, err)
}
p.ServerCA = ca
if seen, err = p.PeekServerCert(context.Background()); err != nil || !seen.Checks || seen.Why != "" {
t.Fatalf("with its CA: %+v %v", seen, err)
}
}
// freshCert is a self-signed certificate of its own for 127.0.0.1:
// httptest's servers all show one built-in certificate, so a server that
// must show another needs this.
func freshCert(t *testing.T) tls.Certificate {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(time.Now().UnixNano()),
Subject: pkix.Name{CommonName: "api.magpie.local"},
DNSNames: []string{"api.magpie.local"},
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}
}
// freshVendor is selfSignedVendor with a certificate of its own.
func freshVendor(t *testing.T) *httptest.Server {
t.Helper()
s := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"data":[{"id":"qwen3-32b"}]}`)
}))
s.Config.ErrorLog = log.New(io.Discard, "", 0)
s.TLS = &tls.Config{Certificates: []tls.Certificate{freshCert(t)}}
s.StartTLS()
t.Cleanup(s.Close)
return s
}