diff --git a/docs/reference.md b/docs/reference.md index e6f4c349a..9d2c165cf 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -950,6 +950,35 @@ since no certificate for the server's name covers loopback. A container or a WSL distro calling through its NAT address is another computer, and uses `https://`. Gateway keys, sharing and allowed addresses work as over HTTP. +**Client certificates (mTLS).** A magpie open to the internet can also +ask every other computer for a client certificate it issued itself +(hhdaxia on X, #5596), so a stolen gateway key alone gets nowhere. Turn on +Settings → Network and sharing → Require a client certificate (or `magpie +mtls on`). magpie makes its own CA in `~/.config/magpie/mtls`; with no +`--tls-cert` it serves other computers `https://` with a certificate that +CA signs, so they need its `ca.pem`. Issue each device a certificate under +Client certificates (or `magpie mtls issue laptop`): `client.pem`, +`client-key.pem` and `ca.pem` are saved to Downloads/magpie-laptop, and the +key is kept nowhere else. Issuing the same name again, or Revoke (`magpie +mtls revoke laptop`), refuses the old one at once, on connections already +open too. A request from another computer without a good certificate is +refused 403 (or at the handshake), with a gateway key or without. This +computer, and a WSL distro's agent with its key, are answered as before, +over plain `http://127.0.0.1` too. A page open from another computer can't +turn it on without a certificate, nor revoke or reissue its own. + +On the other computer, give a Remote magpie (or any provider of your own at +an `https://` address, such as one behind an Nginx that checks client +certificates) the three files under Advanced → Client certificate. They are +shown only to that provider's own host. curl takes them as `--cert +client.pem --key client-key.pem --cacert ca.pem`. Not covered yet: a proxy +or tunnel in front of magpie can't pass a certificate on, so with mTLS on +its requests are refused unless it checks certificates itself and +`MAGPIE_TRUST_PROXY=1` is set; `magpie web`'s page port doesn't hand +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). + 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, @@ -3485,6 +3514,7 @@ magpie web # the app's window in a browser (WSL, a server o # (behind a reverse proxy, MAGPIE_WEB_URL=https:// prints the link through it) magpie serve # the gateway alone, no window; --web[=host:port] serves the page too, from the same process # --tls-cert --tls-key : https:// for other computers (see HTTPS under sharing) +magpie mtls # other computers need a client certificate magpie issued: on, off, issue , revoke , list magpie daemon install # run magpie serve as a service (systemd, launchd); --web, --lan, --addr serve the page too; --tls-cert/--tls-key, --no-tls magpie ls # list every agent and its current settings magpie claude opus # set a model (agent names accept prefixes: cc, oc, gem …) diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 5f7a86cff..9a5ec5136 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -29,6 +29,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-` (`TokenFor`). `agentOf` tells which agent asked, first by token, then by User-Agent. A Codex turn that names itself Claude Code is Codex's: OpenAI's Codex plugin for Claude Code (/codex:rescue, /codex:review) runs `codex app-server` with clientInfo "Claude Code", which Codex sends as its originator and User-Agent, and only Codex's turn headers (`x-codex-window-id`, `x-codex-turn-metadata`) tell it apart from Claude Code's own requests (`codexForClaudeCode`); an app that runs Codex as its own engine under its own name (Lody) stays that app. VS Code's Agents window runs `codex app-server` as `vscode_agent_host`, its originator and User-Agent: its calls are counted under VS Code (`vscodeAgentHostUA` in [`vscode.go`](../../internal/agent/vscode.go)), and its turns are Codex's for every Codex rule (`fromCodex`, `hostedCodex`), so one of Codex's own models asked there goes on Codex's sign-in (`codexOwnOffMagpie`) rather than 404; only Codex's own names (`codexNamed`) are kept as Codex's shape for a test asked as Codex (`TestVSCodeAgentHostIsCodex`, `TestVSCodeAgentHostOwnModelGoesOnSignIn`, `TestVSCodeAgentHostNotCodexTestShape`). Claude Science, whose User-Agent is the Anthropic SDK's, is told by its client's `X-Anthropic-Surface: operon` (`isClaudeScience`). It is listed every model as `claude-magpie-` (`scienceModels`; its picker keeps only a `claude-` id whose name isn't a lower-case slug), and a Claude id magpie doesn't serve (its default before a pick, its haiku side tasks) goes to the model its last turn with tools was on, else the first it is listed (`scienceTurn`, kept in `claude-science.model`). | [`gateway.go`](../../internal/gateway/gateway.go) | | WSL under NAT | On Windows, while the gateway listens on loopback alone, `serveWSL` also serves it, in plain HTTP, at each address Windows has on a WSL network (`WSLNets`: the `vEthernet (WSL…)` adapters, looked for every 10s, since WSL's VM brings its adapter up and down). That is where a distro in NAT networking reaches Windows, and what `place` writes into its agents (zaidu259434 on X: Codex in WSL failed with sharing off). A distro in bridged networking is a peer on the LAN, and its default route is the LAN's router, not Windows: `wslrun.HostAt` takes Windows' address on the bridge's adapter (`vEthernet (WSL_Bridge_Switch)`), the one whose network holds that route (ecalpal_ on Discord). `lanGuard` takes a request there as this computer's (`fromWSL`) only when it arrives at that address, from inside that network, with the WSL key: `WSLKey`, a `wsl-` secret in magpie's folder (`wsl-key`, 0600), optionally followed by `-`. It becomes a loopback request carrying `magpie` or `magpie-` (`asFromLoopback`). A client that can only send its own key (Claude Science in WSL, which sends its Claude sign-in) puts the WSL key first in the path instead, `//v1/…`: `takeWSLPathKey` takes it off before `fromWSL` judges the request, and the request goes on without it. Anything else there, a Docker Desktop container on the same network included, is judged as another machine's. Windows' firewall still decides whether WSL gets in: WSL's network is a Public one. | [`wsl.go`](../../internal/gateway/wsl.go) | | TLS | `--tls-cert`/`--tls-key` (`MAGPIE_TLS_CERT`, `MAGPIE_TLS_KEY`) make `ListenAndServe`, `Relisten` (both through `Server.listen`) and `magpie web`'s page (`ServeTLS`) wrap the listener in `tlsListener`. A connection from another computer is `tls.Server` at once, so its plain HTTP gets net/http's 400. One from this computer (`fromThisComputer`: loopback, or a peer address equal to the local one) is sniffed on its own goroutine, 10s at most (`sniffWait`), and 0x16 makes it TLS, so `URL()`, the agents, MCP servers, `ServedBy` and the healthcheck keep `http://127.0.0.1`. `certFiles.get` reloads the pair when either file's mtime or size changes; a pair that doesn't load keeps the one served (logged once per change). `tlsConfig` refuses half a pair or files that don't load before binding. HTTP/1.1 only over TLS (hijack, Codex's websocket). `Scheme()` gives the scheme of `LANURLs`, a scheme-less `MAGPIE_PUBLIC_URL` and the page's network links. Host and Origin checks (`foreignPage`, `rebound`) don't depend on the scheme. | [`tls.go`](../../internal/gateway/tls.go), [`lan.go`](../../internal/gateway/lan.go) | +| mTLS | With Settings → Network and sharing → Require a client certificate on (settings `MTLS`, `magpie mtls on`; hhdaxia on X, #5596), other computers reach the gateway and `magpie web`'s page only over TLS with a client certificate magpie's own CA (`internal/mtls`, `MTLSStore`: `ca.pem`, `ca-key.pem`, `clients.json` under the settings folder) issued and hasn't revoked. `tlsServer.config(strict)` is asked per connection, so the switch needs no relisten: without `--tls-cert` it serves a certificate the CA signs in memory for this computer's names, addresses and the SNI name (`ownServerCert`, made again when they or the CA change, or after a day), and with mTLS on even without `--tls-cert` the listener serves TLS. A peer that isn't this computer or a WSL distro (`fromWSLNet`) is asked `RequireAndVerifyClientCert` and its handshake ended when `VerifyConnection`'s `Admits` fails. The guards (`lanGuard`, and `ClientCertGuard` on the page) then refuse 403 every request `NeedsClientCert` names: plain HTTP, a proxy's or tunnel's on loopback (`proxied`, unless `MAGPIE_TRUST_PROXY=1` says the proxy checks certificates itself), the page port (`viaPagePort`), a connection made before the switch, a certificate revoked since its handshake. This computer (`local`, `ownAddress`) and a WSL agent with the WSL key (`fromWSL`) are answered as before. The Settings routes (`internal/gui/mtls.go`) never let a page from another computer shut itself out: without a certificate it can't turn mTLS on, and it can't revoke or issue again the certificate it came with (`pageCert`, `errOwnCert`). Not handled: a `.p12` for browsers, and a proxy that can't check certificates itself. `TestMTLSOtherComputerHandshake`, `TestMTLSGuardEveryRoute`, `TestMTLSThisComputerAndProxies`, `TestMTLSToggleWithoutRelisten`, `TestMTLSRevokeMidConnection`, `TestClientCertGuardPage`, `TestSettingsMTLSPageLockout`. | [`mtls.go`](../../internal/gateway/mtls.go), [`tls.go`](../../internal/gateway/tls.go), [`internal/mtls`](../../internal/mtls/mtls.go) | | HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), Ollama's `GET /api/version`, `GET /api/tags` and `POST /api/show` (`ollama.go`, for a client that takes a custom endpoint only as an Ollama server: Visual Studio's and VS Code's Copilot, wani on Discord; the list is `catalogFor`'s, so a key's models alone, `/api/show` tells `capabilities` (`completion`, `tools`, `vision` from `Images`, `thinking` from `Thinks`) and `model_info` with `general.architecture` `magpie`, `general.basename`, `magpie.context_length` (32768, VS Code's own default, when the window isn't known, since VS Code would take a 0) and the `general.parameter_count` and `magpie.embedding_length` the ollama CLI before 0.7 reads unchecked; a name ending `:latest`, as the ollama CLI asks, is the bare id unless a model is really called that (`ollamaName`); the client then chats on `/v1/chat/completions`, or on Ollama's own `POST /api/chat` and `POST /api/generate` (`ollama_chat.go`, Zed's Ollama provider, super_lalalalala on Discord), which `ollamaChatBody` turns into a `/v1/chat/completions` body handed to the same `handle(provider.Chat)` on a clone of the request, so they are routed, held to a key's models and counted as it is: `messages` with `images` (base64, its type sniffed, as data-URL parts; a tool message's in a user message after it), an assistant's `thinking` as `reasoning_content` and its `tool_calls` given ids where Ollama sent none, a tool result matched to its call by `tool_call_id`, else `tool_name`, else in order (one with no call is a 400), `tools`, `format` (`json` or a schema), `think` (a level is `reasoning_effort`), and `options`' `temperature`, `top_p`, `seed`, `stop`, the two penalties and a positive `num_predict` as `max_tokens` (`num_ctx`, `top_k` and the rest of Ollama's own are dropped); `ollamaWriter` turns the reply into Ollama's NDJSON lines (streamed unless `stream:false`, then one object), tool calls with their `arguments` as an object and an `id`, and a last `done` line with `done_reason` and the token counts, and an error into `{"error":"…"}` with the status `/v1` would give; a request with no messages or prompt is answered `done_reason:"load"`, as Ollama does to warm a model), `/mcp/{name}`, `/mcp/magpie/web-search`, `/mcp/magpie/vision` and `/mcp/magpie/image` with its `/mcp/magpie/image/files/{name}` (magpie's own web search, image recognition and image generation as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/magpie/heap` (`heapProfile`, [`heap.go`](../../internal/gateway/heap.go), for `magpie heap`) is held tighter than the rest by `heapRefused` in the handler itself, so it holds where `Handler` is served without `lanGuard` too: only a loopback caller that isn't proxied (`local`), carries no browser mark (`fromBrowser`) and names a loopback `Host` (`loopbackHost`) gets the profile; a gateway key never lets anything else in. `/v1/magpie/cpu` (`cpuProfile`, [`cpu.go`](../../internal/gateway/cpu.go), for `magpie cpu`) records a CPU profile for `?seconds=` (30, from 5 to 120) and is held to the same callers by `cpuRefused`, which shares `profileRefused` with `heapRefused`; one profile records at a time (`cpuRecording`), a second is answered 409, and a caller that hangs up stops it. `/v1/magpie/goroutines` (`goroutineDump`, [`goroutines.go`](../../internal/gateway/goroutines.go), for `magpie goroutines`, #3362) answers every goroutine's stack and wait as text (`runtime/pprof`'s `goroutine` profile at debug 2) to the same callers, through `goroutinesRefused`, and is answered ahead of everything below (`dumpFirst`, around `Handler`'s wrappers and around `lanGuard` in `Front`), since it is asked for while magpie hangs: the allow list reads settings.json under its lock, and `holdCatalog` takes `provider.Hold`'s and `filememo`'s, so a stuck holder of any of them would hold the dump too; a caller `goroutinesRefused` lets in is one those let in anyway, and any other goes through them as before (`TestGoroutineDumpAnswersWhileRequestsWait`). `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, in the mode its `settings.external_web_access` says (#5018; a ChatGPT account then searches by the same backend search, see [Which providers search for another model](#which-providers-search-for-another-model)), and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A WebSocket upgrade on `/v1/responses`, `/responses` or the Codex backend's `/responses` is Responses over a WebSocket, as Codex speaks it (below, [A Responses WebSocket](#a-responses-websocket)); one on another Codex backend path is answered 426, and a plain GET on `/v1/responses` 405. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. A browser sends a preflight without credentials, so a listed origin's preflight from another computer is let past `lanGuard`'s key check to be answered here (#4931, ggbdpq: a page on another machine got 401 to its preflight and never sent the keyed request); `lanGuard` hands on only an `OPTIONS` with `Access-Control-Request-Method` whose origin is listed (`corsAllowed`). Any other origin's preflight still meets the key check: `corsGuard` passes some unlisted origins on (loopback names, the request's own origin, other schemes), and Codex's backend relay would serve their `OPTIONS` on the user's sign-in (`TestCORSPreflightFromLANReachesNothing`). It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost` but not a subdomain of it, which WebKit asks the DNS for (#2256), a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`, this computer's own, never brought by a sync or restore: see [sync and backup](sync-backup.md#what-stays-on-each-computer); the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`), and its port hands the gateway's client routes (`ClientPath`) to `Server.Front`, the same lanGuard-over-Handler the gateway's listener serves, each marked by `FromPagePort` so `local` is false for it (`viaPagePort`; `lanGuard` refuses it 403 while magpie isn't shared, saying to call the gateway's own address, and asks a gateway key otherwise): a raw TCP forward or a proxy with no forwarding header reaches that port from loopback, so no request there counts as an agent here (`TestClientPathCoversHandler` fails when a route Handler adds is in neither `ClientPath` nor its list of routes that stay on the gateway's port). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`ollama.go`](../../internal/gateway/ollama.go), [`ollama_chat.go`](../../internal/gateway/ollama_chat.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | | Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id; the user's own groups only while the `groups` plugin is on, [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider — in a WSL distro, the distro's own, of the ones running now — for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key; a memory call first waits beside the turn it was started with, through `codexLeads`, see the side turns below), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id the asking agent's own subscription in magpie serves (a provider whose `Account.Agent` is the agent: Codex's ChatGPT accounts for Codex, Claude's for Claude Code) goes to that subscription first, found groups on or off (`ownFirst`, `provider.OwnRoute`; freefcw on X: Codex's bare `gpt-6-astra` went to Devin through `auto-gpt-6-astra`, whose soonest-renewing member came first, and with found groups off to the first provider in the order). Not for a group the user made or changed by that name, a found group magpie set one of the agent's fields to (`SetToGroup`, `agent.SetToGroup` over the agent's applied record, #750's bare spelling included), a gateway key held to some models, or a client magpie doesn't know as an agent; an auto stand-in and `agent.Reseat` prefer the agent's own subscription the same way (`AutoStandInFor`, `sameModel`). Otherwise a bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api): with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, an agent with a subscription of its own in magpie is refused it with a 400 naming the providers' ids and `magpie group auto on` (`provider.OffSpread`, `offSpreadRefused`): off, magpie picks no vendor for it. Any other client still gets the first provider in the Providers order that exposes it (`Resolve`), with no fallback. A provider the user keeps out of found groups (Routing's "Leave out a provider", `provider.SetAutoGroupSkip`, `autoGroupSkip` in providers.json; chenxiang0010 on Discord) is in none of them, so a model one other provider serves is no group; the groups the user made or changed keep it. A request still naming a found group that took away goes to its model from a provider not kept out (`AutoStandIn`), and an agent set to it is moved there (`agent.Reseat`). magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | | A found group's two ids | A group magpie found is listed (`/v1/models`, the catalog, the lists written into agents, the pickers, the CLI and TUI) as `auto/`: the model's id as a vendor spells it, dots kept and with no vendor prefix (`auto/claude-opus-5.5`; `provider.Group.Ref`, `spelledIn`), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). The spelling is the one models.dev gives the model most (`catalog.Spelling`, its `normal` index: `glm-5.3-flash` whether the members serve `glm-5-3-flash`, Ark's dated id or `glm-5.3-flash`), so it no longer follows the order the providers were added in; for a model models.dev doesn't know, the first member's spelling it lists, else the first member's. The group's name comes from the same choice (`autoGroups`): the name models.dev gives that spelling (`catalog.NameOf`), else a vendor's own name for it, else the spelling itself; they were picked apart, a name of `glm-5-3-flash` beside `auto/glm-5.3-flash` (XYenon on Discord, `TestFoundGroupIDAndNameAreOneSpelling`). A found group the user changed keeps the name they saved. Every spelling it was listed by before is still the group (`CanonicalRef`), and `PublicRef` takes one to the spelling now. Its old id `group/auto-` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/` (with `:level` or `[1m]`) back to it with `provider.CanonicalRef` before key limits, routing, affinity and the usage log see the request, and the request body is rewritten to it, so both ids count as one group. A gateway key naming either id, `group/*` or `auto/*` passes for both (`allows` in `key_models.go`). `SaveGroup` stores a member, rule or classifier picked as `auto/` by the old id. An agent field magpie set to `group/auto-`, or to an `auto/` spelt otherwise than the group is listed now, moves to `auto/` on the next `SyncCatalog` (`agent.renameFoundGroups`, `TestFoundGroupMovedOffAnOldSpelling`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays, and is still served. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/`. An agent's hidden, picked and ordered models saved by the old id hold for the new one (`PublicRef` in `visible.go`), and a bare model id still reaches its found group (`bareTarget`). Claude Code is given a dotted Claude version dashed, so it may send `auto/claude-sonnet-4-5`: that is the same group, and `Reseat` still moves an agent off it once the group is gone (`samePick`). `auto` is no provider id: `Save` and `Rename` refuse it for a new provider, and a plugin's `auto` is `auto-plugin` (`PluginID`). A provider of the user's saved as `auto` before keeps its models: while it exists, `auto/` is its model and found groups list as `group/auto-` (`autoRefsOn`). Hand-made groups stay `group/`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.go) | diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 27831864e..9eb1da04f 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -347,6 +347,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. - Every request to the ChatGPT backend (`CodexBase`'s host) goes over HTTP/1.1, as Codex itself speaks to it: each transport [`netproxy.Dispatch`](../../internal/netproxy/netproxy.go) makes (`http.DefaultClient`'s, the gateway's) sends a request `netproxy.HTTP1` names through an HTTP/1.1 copy of itself whose TLS hello offers no h2, and the provider package sets `HTTP1` to `codexBackend` ([codex_http1.go](../../internal/provider/codex_http1.go)). That covers the gateway's turns, the models list, the warm-up, the allowance, its resets and spending one, through the proxy in force, an account's own included. Every other vendor is still offered HTTP/2, except a provider held to HTTP/1.1 (`HTTP1`, below), a host whose HTTP/2 broke on a TLS record error, and the requests of a download trying again after its transfer broke off (`netproxy.OverHTTP1`, `AgainOverHTTP1`, `BrokeOff`: magpie's update, from where it stopped, the masking model's files, Bun, Claude Code and the Grok CLI; biubiu8802 on X: a proxy cut every HTTP/2 stream of the update part way, "unexpected EOF", while it carried HTTP/1.1 whole; `TestDownloadBrokenOverHTTP2TriesHTTP1`, `TestAgainOverHTTP1`). - 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). - 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 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` (`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`). diff --git a/internal/cli/daemon_cli.go b/internal/cli/daemon_cli.go index 02b6eed64..838be4c6b 100644 --- a/internal/cli/daemon_cli.go +++ b/internal/cli/daemon_cli.go @@ -141,7 +141,7 @@ func daemonCmd(args []string) error { if err != nil { return err } - if noTLS && gateway.TLSOn() { + if c, _ := gateway.TLSFiles(); noTLS && c != "" { return errors.New("magpie daemon install: --no-tls and a certificate both") } args = append([]string{"install"}, rest...) diff --git a/internal/cli/help_cli.go b/internal/cli/help_cli.go index 40fce110a..8bbe33064 100644 --- a/internal/cli/help_cli.go +++ b/internal/cli/help_cli.go @@ -54,6 +54,8 @@ func helpFor(args []string) string { return quotaUsage case "statusline": return statuslineUsage + case "mtls": + return mtlsUsage case "heap": return heapUsage case "cpu": diff --git a/internal/cli/help_cli_test.go b/internal/cli/help_cli_test.go index 8162eddf6..5e70fb58a 100644 --- a/internal/cli/help_cli_test.go +++ b/internal/cli/help_cli_test.go @@ -129,7 +129,7 @@ func runCommands(t *testing.T) []string { if len(cmds) < 40 { t.Fatalf("read %d commands from run's switch: %v", len(cmds), cmds) } - return append(cmds, "healthcheck", "heap", "cpu", "goroutines") + return append(cmds, "healthcheck", "heap", "cpu", "goroutines", "mtls") } func types(ix *ast.IndexExpr) string { diff --git a/internal/cli/main.go b/internal/cli/main.go index b229983f2..6f83876b1 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -131,6 +131,8 @@ const usage = `magpie — one place to pick every agent's model magpie daemon web [on|off] [--lan] [--addr host:port] the service's page: its link, or turn it on or off magpie healthcheck exit 0 when the gateway answers (a container's HEALTHCHECK) + magpie mtls [on|off|issue |list|revoke ] + require a client certificate magpie issued from other computers (mTLS) magpie heap [] a Go heap profile of the running magpie, with its memory numbers, for a report of it using too much memory magpie cpu [] [--seconds N] a Go CPU profile of the running magpie over 30s (5..120) while you use it, for a report of it using too much CPU magpie goroutines [] every goroutine of the running magpie, its stack and how long it waited, for a report of it stuck at something @@ -349,6 +351,11 @@ func run(args []string) error { // the running magpie's heap profile: asks it, and moves nothing here return heapCmd(args[1:]) } + if len(args) > 0 && args[0] == "mtls" { + // magpie's CA and the client certificates it issued: nothing + // else is read or moved + return mtlsCmd(args[1:]) + } if len(args) > 0 && args[0] == "cpu" { // the running magpie's CPU profile: asks it, and moves nothing here return cpuCmd(args[1:]) diff --git a/internal/cli/mtls_cli.go b/internal/cli/mtls_cli.go new file mode 100644 index 000000000..e0f66ae0d --- /dev/null +++ b/internal/cli/mtls_cli.go @@ -0,0 +1,155 @@ +package cli + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/mtls" + "github.com/yetone/magpie/internal/settings" +) + +const mtlsUsage = `usage: magpie mtls [on|off|issue [--out ]|list|revoke ] + other computers reach this magpie only with a client certificate it issued (mTLS; + hhdaxia on X, #5596). On, the gateway and magpie web's page are served over https:// + to them with magpie's own CA (or the --tls-cert one), and a request without a good + certificate is refused, a gateway key or not. This computer, and a WSL distro's agent + with its key, are answered as before. + magpie mtls whether it is on, and the certificates issued + magpie mtls on|off require a client certificate from other computers, or stop + magpie mtls issue a certificate for one device: client.pem, client-key.pem and + ca.pem in Downloads/magpie- (or --out ). Give the + device all three; the key is not kept here. Issuing a name + again revokes the one before. + magpie mtls revoke refuses that device's certificate from now on + In Remote magpie (or a provider) on the other computer, set Client certificate, Client key + and Server CA to the three files. curl: --cert client.pem --key client-key.pem --cacert ca.pem.` + +func mtlsCmd(args []string) error { + st := gateway.MTLSStore() + if len(args) == 0 || args[0] == "list" || args[0] == "status" { + return mtlsList(st) + } + switch args[0] { + case "on", "off": + on := args[0] == "on" + if on { + if _, _, err := st.CA(); err != nil { + return err + } + } + if err := settings.SetMTLS(on); err != nil { + return err + } + if !on { + fmt.Println("mTLS off: other computers are answered as before (a gateway key, while shared)") + return nil + } + fmt.Println("mTLS on: other computers need a client certificate magpie issued; this computer is answered as before") + if l, _ := st.List(); len(l) == 0 { + fmt.Println("no certificate issued yet: magpie mtls issue ") + } + return nil + case "issue": + rest, out, err := outFlag(args[1:]) + if err != nil { + return err + } + if len(rest) != 1 { + return errors.New("usage: magpie mtls issue [--out ]") + } + iss, err := st.Issue(rest[0]) + if err != nil { + return err + } + if out == "" { + out = downloadsDir() + } + dir, err := mtls.Export(iss, out) + if err != nil { + return err + } + fmt.Printf("issued %q (serial %s, valid until %s)\n", iss.Name, iss.Serial, iss.Expires.Format("2006-01-02")) + fmt.Println(" " + dir + string(filepath.Separator) + " client.pem, client-key.pem, ca.pem") + if !gateway.MTLSOn() { + fmt.Println("mTLS is off: magpie mtls on to require it") + } + return nil + case "revoke": + if len(args) != 2 { + return errors.New("usage: magpie mtls revoke ") + } + n, err := st.Revoke(args[1]) + if err != nil { + return err + } + if n == 0 { + return fmt.Errorf("no certificate issued to %q that isn't revoked already", args[1]) + } + fmt.Printf("revoked %d certificate(s) for %q\n", n, args[1]) + return nil + } + return fmt.Errorf("magpie mtls: unknown %q\n%s", args[0], mtlsUsage) +} + +func mtlsList(st mtls.Store) error { + state := "off" + if gateway.MTLSOn() { + state = "on" + } + fmt.Println("mTLS " + state) + l, err := st.List() + if err != nil { + return err + } + now := time.Now() + for _, c := range l { + why := "valid until " + c.Expires.Format("2006-01-02") + switch { + case !c.Revoked.IsZero(): + why = "revoked " + c.Revoked.Format("2006-01-02") + case !c.Good(now): + why = "ran out " + c.Expires.Format("2006-01-02") + } + fmt.Printf(" %-24s %s issued %s · %s\n", c.Name, c.Serial, c.Issued.Format("2006-01-02"), why) + } + return nil +} + +// outFlag takes --out (or --out=) out of args. +func outFlag(args []string) (rest []string, out string, err error) { + for i := 0; i < len(args); i++ { + switch a := args[i]; { + case a == "--out": + if i+1 >= len(args) { + return nil, "", errors.New("--out takes a folder") + } + i++ + out = args[i] + case strings.HasPrefix(a, "--out="): + out = strings.TrimPrefix(a, "--out=") + case strings.HasPrefix(a, "-"): + return nil, "", fmt.Errorf("unknown flag %s", a) + default: + rest = append(rest, a) + } + } + return rest, out, nil +} + +// downloadsDir is the Downloads folder the system keeps, else +// home/Downloads, else this folder. +func downloadsDir() string { + home, _ := os.UserHomeDir() + for _, d := range []string{appdir.Downloads(), filepath.Join(home, "Downloads")} { + if fi, err := os.Stat(d); d != "" && err == nil && fi.IsDir() { + return d + } + } + return "." +} diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index d01676401..d893f38b5 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -202,6 +202,9 @@ var cliForRoute = map[string]string{ "GET /api/groups": "magpie groups", "POST /api/groups/{action}": "magpie group", "GET /api/import/{id}": "magpie import", + "POST /api/settings/mtls": "magpie mtls on", + "POST /api/settings/mtls/issue": "magpie mtls issue", + "POST /api/settings/mtls/revoke": "magpie mtls revoke", "GET /api/library": "magpie library", "POST /api/library/{what}/{action}": "magpie library", "GET /api/plugins": "magpie plugin", diff --git a/internal/cli/tls_cli.go b/internal/cli/tls_cli.go index cb5209e8f..4959a57a5 100644 --- a/internal/cli/tls_cli.go +++ b/internal/cli/tls_cli.go @@ -43,9 +43,15 @@ func tlsLine() string { return "" } cert, _ := gateway.TLSFiles() + if cert == "" { + cert = "magpie's own CA (mTLS)" + } s := muted.Render(" TLS ") + " " + cert if sum := gateway.TLSSummary(); sum != "" { s += muted.Render(" · " + sum) } + if gateway.MTLSOn() { + s += "\n" + muted.Render(" other computers show a client certificate magpie issued (magpie mtls)") + } return s + "\n" + muted.Render(" https:// from other computers, read again when the files change; this computer may call plain http://") } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 4f2eccbde..99bd23c55 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6,7 +6,6 @@ import ( "cmp" "context" "crypto/sha256" - "crypto/tls" "encoding/hex" "encoding/json" "errors" @@ -570,7 +569,7 @@ type Server struct { // sockets are the Responses WebSockets being served (responses_ws.go) sockets clientSockets // what it serves other computers TLS with, nil without (tls.go) - tls *tls.Config + tls *tlsServer // the images described for models that can't see them (vision.go); // completed inline descriptions also survive a restart (vision_cache.go) sightMu sync.Mutex @@ -781,7 +780,7 @@ var WhileServing []func(context.Context) func (s *Server) ListenAndServe(ctx context.Context) error { migrateLANKeyBestEffort() ScopeOwnBrowserKey() - cfg, err := tlsConfig() + cfg, err := serverTLS() if err != nil { return err } diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index e5f407b35..3a66bce14 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -554,6 +554,12 @@ func (s *Server) Relisten() error { // including a stale named key. func lanGuard(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // with mTLS on, another machine's request needs magpie's client + // certificate before anything else is looked at, a callback's + // token and a gateway key included (mtls.go) + if refuseWithoutClientCert(w, r) { + return + } if ownCallback(r) { next.ServeHTTP(w, r) return diff --git a/internal/gateway/mtls.go b/internal/gateway/mtls.go new file mode 100644 index 000000000..a71c9ae05 --- /dev/null +++ b/internal/gateway/mtls.go @@ -0,0 +1,267 @@ +package gateway + +import ( + "crypto/tls" + "crypto/x509" + "errors" + "log" + "net" + "net/http" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/mtls" + "github.com/yetone/magpie/internal/settings" +) + +// mTLS (hhdaxia on X, #5596): with Settings → Network and sharing → +// Require a client certificate on (settings MTLS, `magpie mtls on`), other +// computers reach the gateway and magpie web's page only over TLS, showing +// a client certificate magpie's own CA issued (`magpie mtls issue`) and +// hasn't revoked: +// +// - the TLS listener (tlsListener) asks every peer that isn't this +// computer, and isn't a WSL distro's, for one, and ends the handshake +// of a peer without a good one before any HTTP is read; +// - the guards (lanGuard, ClientCertGuard) refuse 403 every request from +// another machine that came without a verified one: a proxy's or +// tunnel's on loopback (proxied), magpie web's page port, the WSL +// listener's plain HTTP from a peer that isn't WSL's, a connection +// made before the switch was turned on, or a certificate revoked +// since its connection's handshake. +// +// This computer — loopback, and this computer calling its own address — +// and a WSL distro's agent with the WSL key (fromWSL) are answered as +// before, over plain HTTP too. Without --tls-cert the server certificate +// is the CA's own, made in memory for the names the client dials +// (ownServerCert); with --tls-cert it is that one, and the CA is used for +// the client certificates alone. + +// MTLSOn: other computers need a client certificate magpie issued. +func MTLSOn() bool { return settings.Shared().MTLS } + +// MTLSStore is where magpie's CA and the client certificates it issued are +// kept. +func MTLSStore() mtls.Store { return mtls.Store{Dir: filepath.Join(settings.Dir(), "mtls")} } + +// clientCertAdmitted: r came over TLS with a client certificate magpie's +// CA verified at the handshake, which is still on the issued list. +func clientCertAdmitted(r *http.Request) bool { + if r.TLS == nil || len(r.TLS.VerifiedChains) == 0 || len(r.TLS.PeerCertificates) == 0 { + return false + } + return MTLSStore().Admits(r.TLS.PeerCertificates[0]) == nil +} + +// ownAddress: r is this computer calling one of its own addresses (the +// kernel answers it without the network), not through a proxy. +func ownAddress(r *http.Request) bool { + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return false + } + ip := net.ParseIP(host) + la, _ := r.Context().Value(http.LocalAddrContextKey).(net.Addr) + tcp, ok := la.(*net.TCPAddr) + return ip != nil && ok && tcp.IP.Equal(ip) && !proxied(r) && !viaPagePort(r) +} + +// mtlsRefuses says why r, with mTLS on, is refused: "" when it is let +// through (mTLS off, a good certificate, or from this computer or WSL). +// Whether r would be let through is asked first, so this computer's own +// requests never wait on settings.json for the switch. +func mtlsRefuses(r *http.Request) string { + why := NeedsClientCert(r) + if why == "" || !MTLSOn() { + return "" + } + return why +} + +// NeedsClientCert is why r would be refused with mTLS on, "" when it +// would be let through: the page turning it on is asked, so it never +// shuts out the computer it is open on. +func NeedsClientCert(r *http.Request) string { + if clientCertAdmitted(r) || local(r) || ownAddress(r) || fromWSL(takeWSLPathKey(r)) { + return "" + } + why := "magpie asks other computers for a client certificate it issued (Settings → Network and sharing → Require a client certificate), and this request came without a good one" + switch { + case r.TLS == nil && proxied(r): + why += ": it came through a proxy or tunnel, which can't pass a certificate on; reach magpie directly over https://, or have the proxy check client certificates itself and set MAGPIE_TRUST_PROXY=1" + case r.TLS == nil: + why += ": it came over plain HTTP; call magpie at https://" + case len(r.TLS.PeerCertificates) > 0: + why += ": the certificate shown was revoked or isn't one this magpie issued" + default: + why += ": issue one with `magpie mtls issue ` and give it to the client" + } + return why +} + +// refuseWithoutClientCert answers a gateway request mtlsRefuses, in the +// error shape agents show; true when it did. +func refuseWithoutClientCert(w http.ResponseWriter, r *http.Request) bool { + why := mtlsRefuses(r) + if why == "" { + return false + } + log.Printf("refused %s %s from %s: no good client certificate", r.Method, r.URL.Path, r.RemoteAddr) + http.Error(w, why, http.StatusForbidden) + return true +} + +// ClientCertGuard refuses a request mtlsRefuses, for a server other than +// the gateway's own (magpie web's page). +func ClientCertGuard(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if refuseWithoutClientCert(w, r) { + return + } + next.ServeHTTP(w, r) + }) +} + +// tlsServer is what a listener serves TLS with: the files --tls-cert +// names, or with mTLS on and none named, a certificate magpie's CA signs. +// It is asked for each connection, so turning mTLS on or off takes effect +// for the next one without listening again. +type tlsServer struct { + files *certFiles // nil without --tls-cert +} + +// config is the TLS config for a connection, nil to serve it plain HTTP +// (no --tls-cert and mTLS off). strict asks for a client certificate and +// ends a handshake without one, for a peer that isn't this computer or a +// WSL distro. +func (t *tlsServer) config(strict bool) *tls.Config { + on := MTLSOn() + if t == nil || (t.files == nil && !on) { + return nil + } + cfg := &tls.Config{ + MinVersion: tls.VersionTLS12, + // HTTP/1.1 alone, as over plain HTTP: Codex's websocket and the + // streams' handling hijack the connection + NextProtos: []string{"http/1.1"}, + } + if t.files != nil { + cfg.GetCertificate = t.files.get + } else { + cfg.GetCertificate = ownServerCert + } + if !on { + return cfg + } + st := MTLSStore() + pool, err := mtlsPool(st) + if err != nil { + log.Printf("mTLS: magpie's CA can't be read (%v): no client certificate is taken", err) + pool = x509.NewCertPool() + } + cfg.ClientCAs = pool + cfg.ClientAuth = tls.VerifyClientCertIfGiven + if strict { + cfg.ClientAuth = tls.RequireAndVerifyClientCert + } + cfg.VerifyConnection = func(cs tls.ConnectionState) error { + if len(cs.PeerCertificates) == 0 { + return nil // judged by the guards, for a lenient peer + } + return st.Admits(cs.PeerCertificates[0]) + } + return cfg +} + +var poolCache struct { + sync.Mutex + path string + stamp fileStamp + pool *x509.CertPool +} + +// mtlsPool is the store's CA as a pool, read again when ca.pem changes. +func mtlsPool(st mtls.Store) (*x509.CertPool, error) { + poolCache.Lock() + defer poolCache.Unlock() + now := stampOf(st.CAFile()) + if poolCache.pool != nil && poolCache.path == st.CAFile() && poolCache.stamp == now && now != (fileStamp{}) { + return poolCache.pool, nil + } + p, err := st.Pool() + if err != nil { + return nil, err + } + poolCache.path, poolCache.stamp, poolCache.pool = st.CAFile(), stampOf(st.CAFile()), p + return p, nil +} + +var ownCerts struct { + sync.Mutex + key string + stamp fileStamp + made time.Time + cert *tls.Certificate +} + +// ownServerCert is a server certificate magpie's CA signs for this +// computer's names and addresses and the name the client dialled (a DDNS +// or Tailscale name): only a client given the CA trusts it, so the name a +// client asks for is the one it gets. Made in memory, and again when the +// names, the addresses or the CA change, or after a day. +func ownServerCert(hello *tls.ClientHelloInfo) (*tls.Certificate, error) { + names := []string{"localhost"} + if h, err := os.Hostname(); err == nil && h != "" { + h = strings.TrimSuffix(strings.ToLower(h), ".") + names = append(names, h) + if !strings.Contains(h, ".") { + names = append(names, h+".local") + } + } + if hello != nil && hello.ServerName != "" && net.ParseIP(hello.ServerName) == nil { + names = append(names, strings.ToLower(hello.ServerName)) + } + slices.Sort(names) + names = slices.Compact(names) + ips := []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback} + if addrs, err := net.InterfaceAddrs(); err == nil { + for _, a := range addrs { + if n, ok := a.(*net.IPNet); ok && !n.IP.IsLoopback() { + ips = append(ips, n.IP) + } + } + } + var key strings.Builder + key.WriteString(strings.Join(names, ",")) + for _, ip := range ips { + key.WriteString("|" + ip.String()) + } + st := MTLSStore() + ownCerts.Lock() + defer ownCerts.Unlock() + stamp := stampOf(st.CAFile()) + if ownCerts.cert != nil && ownCerts.key == key.String() && ownCerts.stamp == stamp && time.Since(ownCerts.made) < 24*time.Hour { + return ownCerts.cert, nil + } + c, err := st.ServerCert(names, ips) + if err != nil { + return nil, errors.New("mTLS: magpie's CA can't sign a server certificate: " + err.Error()) + } + ownCerts.key, ownCerts.stamp, ownCerts.made, ownCerts.cert = key.String(), stampOf(st.CAFile()), time.Now(), &c + return &c, nil +} + +// fromWSLNet: c's peer is on one of WSL's networks, at the address +// Windows has there (a distro's agent, judged by its key in fromWSL). +func fromWSLNet(c net.Conn) bool { + r, ok := c.RemoteAddr().(*net.TCPAddr) + l, ok2 := c.LocalAddr().(*net.TCPAddr) + if !ok || !ok2 { + return false + } + return slices.ContainsFunc(WSLNets(), func(n *net.IPNet) bool { return n.IP.Equal(l.IP) && n.Contains(r.IP) }) +} diff --git a/internal/gateway/mtls_test.go b/internal/gateway/mtls_test.go new file mode 100644 index 000000000..af5a6a0ba --- /dev/null +++ b/internal/gateway/mtls_test.go @@ -0,0 +1,359 @@ +package gateway + +import ( + "bufio" + "crypto/tls" + "crypto/x509" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/mtls" + "github.com/yetone/magpie/internal/settings" +) + +// mtlsHome is a sandbox HOME with magpie shared, a gateway key, and mTLS +// on or off; it returns the key. +func mtlsHome(t *testing.T, on bool) string { + t.Helper() + fresh(t) + t.Setenv("MAGPIE_ADDR", "0.0.0.0:3499") + t.Setenv(AllowIPsEnv, "") + t.Setenv(TLSCertEnv, "") + t.Setenv(TLSKeyEnv, "") + key, err := access.Update("add-key", access.Change{Name: "Laptop"}) + if err != nil { + t.Fatal(err) + } + if _, _, err := MTLSStore().CA(); err != nil { + t.Fatal(err) + } + setMTLS(t, on) + return key +} + +func setMTLS(t *testing.T, on bool) { + t.Helper() + if err := settings.SetMTLS(on); err != nil { + t.Fatal(err) + } + if MTLSOn() != on { + t.Fatalf("MTLSOn() = %v after SetMTLS(%v)", !on, on) + } +} + +// issued is a client certificate of st's for name, as a TLS client +// shows it. +func issued(t *testing.T, st mtls.Store, name string) tls.Certificate { + t.Helper() + iss, err := st.Issue(name) + if err != nil { + t.Fatal(err) + } + c, err := tls.X509KeyPair(iss.Cert, iss.Key) + if err != nil { + t.Fatal(err) + } + return c +} + +// mtlsClient trusts magpie's CA for the server and shows cert (none when +// nil); keepAlive keeps one connection for every request. +func mtlsClient(t *testing.T, cert *tls.Certificate, keepAlive bool) *http.Client { + t.Helper() + pool, err := MTLSStore().Pool() + if err != nil { + t.Fatal(err) + } + cfg := &tls.Config{RootCAs: pool} + if cert != nil { + cfg.Certificates = []tls.Certificate{*cert} + } + tr := &http.Transport{TLSClientConfig: cfg, DisableKeepAlives: !keepAlive} + t.Cleanup(tr.CloseIdleConnections) + return &http.Client{Timeout: 5 * time.Second, Transport: tr} +} + +// asFrom has every request look, to the guards, as if it came from addr: +// the listener judges the connection (fromThisComputer), the guards the +// request, as a WSL distro's or a connection made before mTLS was turned +// on is let through the first and judged by the second. +func asFrom(addr string, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.RemoteAddr = addr + next.ServeHTTP(w, r) + }) +} + +// serveMTLSGateway serves the guard over a stub on a listener that sees +// its peers as another computer's (other) or this one's, each request as +// from remote ("" keeps the real loopback peer). +func serveMTLSGateway(t *testing.T, other bool, remote string) string { + t.Helper() + was := fromThisComputer + fromThisComputer = func(net.Conn) bool { return !other } + t.Cleanup(func() { fromThisComputer = was }) + srvTLS, err := serverTLS() + if err != nil { + t.Fatal(err) + } + s := New() + s.tls = srvTLS + ln, err := s.listen("127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + var h http.Handler = lanGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, "served "+r.URL.Path) + })) + if remote != "" { + h = asFrom(remote, h) + } + srv := &http.Server{Handler: h, ReadHeaderTimeout: 5 * time.Second} + done := make(chan struct{}) + go func() { defer close(done); srv.Serve(ln) }() + t.Cleanup(func() { srv.Close(); <-done }) + return ln.Addr().String() +} + +func mcall(t *testing.T, c *http.Client, method, url, key string, header ...string) (int, string, error) { + t.Helper() + req, _ := http.NewRequest(method, url, strings.NewReader("{}")) + if key != "" { + req.Header.Set("Authorization", "Bearer "+key) + } + for i := 0; i+1 < len(header); i += 2 { + req.Header.Set(header[i], header[i+1]) + } + res, err := c.Do(req) + if err != nil { + return 0, "", err + } + defer res.Body.Close() + b, _ := io.ReadAll(res.Body) + return res.StatusCode, string(b), nil +} + +// the routes a remote agent calls, each refused the same without a +// certificate (a restriction covers every route that reaches the thing) +var mtlsRoutes = [][2]string{ + {"GET", "/v1/models"}, + {"POST", "/v1/chat/completions"}, + {"POST", "/v1/messages"}, + {"POST", "/v1/responses"}, + {"GET", "/v1/magpie/quotas"}, + {"POST", "/backend-api/codex/responses"}, + {"GET", "/api/state"}, + {"GET", "/"}, +} + +// Another computer's connection (#5596, hhdaxia on X): with mTLS on, the +// handshake ends without a client certificate magpie issued — none, one +// another CA signed, one revoked, or plain HTTP — before any HTTP is +// read; one with a good certificate and the gateway key is answered. +func TestMTLSOtherComputerHandshake(t *testing.T) { + key := mtlsHome(t, true) + st := MTLSStore() + addr := serveMTLSGateway(t, true, "") + good := issued(t, st, "laptop") + foreign := issued(t, mtls.Store{Dir: t.TempDir()}, "laptop") + revoked := issued(t, st, "old phone") + if _, err := st.Revoke("old phone"); err != nil { + t.Fatal(err) + } + + for name, c := range map[string]*http.Client{ + "no certificate": mtlsClient(t, nil, false), + "another CA's": mtlsClient(t, &foreign, false), + "a revoked one": mtlsClient(t, &revoked, false), + "plain HTTP": plain, + } { + scheme := "https://" + if strings.HasPrefix(name, "plain") { + scheme = "http://" + } + code, body, err := mcall(t, c, "GET", scheme+addr+"/v1/models", key) + if err == nil && (code < 400 || strings.Contains(body, "served")) { + t.Errorf("%s: %d %s, want the connection refused", name, code, body) + } + } + c := mtlsClient(t, &good, false) + for _, rt := range mtlsRoutes { + code, body, err := mcall(t, c, rt[0], "https://"+addr+rt[1], key) + if err != nil || code != 200 || body != "served "+rt[1] { + t.Errorf("good certificate, %s %s: %d %q %v", rt[0], rt[1], code, body, err) + } + } +} + +// The guards judge each request: one from another machine that reached +// the gateway through a lenient listener (a WSL network's, a connection +// made before mTLS was turned on) is refused on every route without a +// good certificate, the gateway key notwithstanding; with one it still +// needs the key. +func TestMTLSGuardEveryRoute(t *testing.T) { + key := mtlsHome(t, true) + st := MTLSStore() + addr := serveMTLSGateway(t, false, "192.168.1.9:5000") + good := issued(t, st, "laptop") + foreign := issued(t, mtls.Store{Dir: t.TempDir()}, "x") + + for _, rt := range mtlsRoutes { + for name, c := range map[string]*http.Client{ + "plain HTTP": plain, + "no certificate": mtlsClient(t, nil, false), + } { + scheme := "https://" + if c == plain { + scheme = "http://" + } + code, body, err := mcall(t, c, rt[0], scheme+addr+rt[1], key) + if err != nil || code != http.StatusForbidden || !strings.Contains(body, "client certificate") { + t.Errorf("%s %s, %s: %d %q %v, want 403 saying why", rt[0], rt[1], name, code, body, err) + } + } + // another CA's: the lenient handshake verifies a certificate if + // given, and refuses one that doesn't verify + if code, body, err := mcall(t, mtlsClient(t, &foreign, false), rt[0], "https://"+addr+rt[1], key); err == nil && (code != http.StatusForbidden || strings.Contains(body, "served")) { + t.Errorf("%s %s, another CA's: %d %q", rt[0], rt[1], code, body) + } + c := mtlsClient(t, &good, false) + if code, body, err := mcall(t, c, rt[0], "https://"+addr+rt[1], key); err != nil || code != 200 || body != "served "+rt[1] { + t.Errorf("%s %s, good certificate and key: %d %q %v", rt[0], rt[1], code, body, err) + } + } + if code, body, _ := mcall(t, mtlsClient(t, &good, false), "POST", "https://"+addr+"/v1/messages", ""); code != http.StatusUnauthorized && code != http.StatusForbidden || strings.Contains(body, "served") { + t.Errorf("good certificate without the key: %d %q, want it refused", code, body) + } +} + +// This computer is answered as before, over plain HTTP and without a +// key; a request through a proxy or tunnel on loopback is another +// machine's, and is refused without a certificate even with the key, +// unless MAGPIE_TRUST_PROXY says the proxy checks its clients. +func TestMTLSThisComputerAndProxies(t *testing.T) { + key := mtlsHome(t, true) + addr := serveMTLSGateway(t, false, "") + if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", ""); err != nil || code != 200 { + t.Fatalf("loopback, plain: %d %q %v", code, body, err) + } + if code, body, err := mcall(t, mtlsClient(t, nil, false), "GET", "https://"+addr+"/v1/models", ""); err != nil || code != 200 { + t.Fatalf("loopback, TLS without a certificate: %d %q %v", code, body, err) + } + for _, h := range []string{"X-Forwarded-For", "Cf-Connecting-IP", "Forwarded"} { + code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key, h, "203.0.113.5") + if err != nil || code != http.StatusForbidden || !strings.Contains(body, "proxy") { + t.Errorf("proxied (%s) with key: %d %q %v", h, code, body, err) + } + } + code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key, PagePortHeader, "1") + if err != nil || code != http.StatusForbidden || !strings.Contains(body, "client certificate") { + t.Errorf("magpie web's page port with key: %d %q %v", code, body, err) + } + t.Setenv("MAGPIE_TRUST_PROXY", "1") + if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", "", "X-Forwarded-For", "203.0.113.5"); err != nil || code != 200 { + t.Errorf("a trusted proxy: %d %q %v", code, body, err) + } +} + +// Turning mTLS on or off takes effect at the next connection, without +// listening again: off, another computer is answered over plain HTTP with +// its key, as before; on, plain HTTP is refused and a certificate is +// asked for; off again, plain HTTP is answered. +func TestMTLSToggleWithoutRelisten(t *testing.T) { + key := mtlsHome(t, false) + addr := serveMTLSGateway(t, true, "") + good := issued(t, MTLSStore(), "laptop") + if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err != nil || code != 200 { + t.Fatalf("off: %d %q %v", code, body, err) + } + setMTLS(t, true) + if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err == nil && code < 400 { + t.Fatalf("on, plain: %d %q, want it refused", code, body) + } + if code, body, err := mcall(t, mtlsClient(t, &good, false), "GET", "https://"+addr+"/v1/models", key); err != nil || code != 200 { + t.Fatalf("on, certificate: %d %q %v", code, body, err) + } + setMTLS(t, false) + if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err != nil || code != 200 { + t.Fatalf("off again: %d %q %v", code, body, err) + } +} + +// A certificate revoked while its connection stays open is refused at +// the connection's next request, not only its next handshake. +func TestMTLSRevokeMidConnection(t *testing.T) { + key := mtlsHome(t, true) + st := MTLSStore() + addr := serveMTLSGateway(t, false, "192.168.1.9:5000") + good := issued(t, st, "laptop") + pool, _ := st.Pool() + conn, err := tls.Dial("tcp", addr, &tls.Config{RootCAs: pool, Certificates: []tls.Certificate{good}, ServerName: "localhost"}) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + br := bufio.NewReader(conn) + ask := func() (int, string) { + t.Helper() + io.WriteString(conn, "GET /v1/models HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer "+key+"\r\n\r\n") + res, err := http.ReadResponse(br, nil) + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(res.Body) + res.Body.Close() + return res.StatusCode, string(b) + } + if code, body := ask(); code != 200 { + t.Fatalf("before: %d %q", code, body) + } + if _, err := st.Revoke("laptop"); err != nil { + t.Fatal(err) + } + if code, body := ask(); code != http.StatusForbidden || !strings.Contains(body, "revoked") { + t.Fatalf("after revoke, same connection: %d %q", code, body) + } +} + +// magpie web's page refuses another machine's request without a good +// certificate (ClientCertGuard), and serves this computer's. +func TestClientCertGuardPage(t *testing.T) { + mtlsHome(t, true) + good := issued(t, MTLSStore(), "laptop") + leaf, _ := x509.ParseCertificate(good.Certificate[0]) + h := ClientCertGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "page") })) + call := func(from string, cs *tls.ConnectionState) int { + r := httptest.NewRequest("GET", "/", nil) + r.RemoteAddr, r.TLS = from, cs + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code + } + verified := &tls.ConnectionState{PeerCertificates: []*x509.Certificate{leaf}, VerifiedChains: [][]*x509.Certificate{{leaf}}} + unverified := &tls.ConnectionState{PeerCertificates: []*x509.Certificate{leaf}} + for _, c := range []struct { + from string + cs *tls.ConnectionState + want int + }{ + {"127.0.0.1:5000", nil, 200}, + {"192.168.1.9:5000", nil, 403}, + {"192.168.1.9:5000", &tls.ConnectionState{}, 403}, + {"192.168.1.9:5000", unverified, 403}, + {"192.168.1.9:5000", verified, 200}, + } { + if got := call(c.from, c.cs); got != c.want { + t.Errorf("%s %v: %d, want %d", c.from, c.cs != nil, got, c.want) + } + } + setMTLS(t, false) + if got := call("192.168.1.9:5000", nil); got != 200 { + t.Errorf("mTLS off: %d", got) + } +} diff --git a/internal/gateway/tls.go b/internal/gateway/tls.go index d5c23eca1..e118f777a 100644 --- a/internal/gateway/tls.go +++ b/internal/gateway/tls.go @@ -39,10 +39,11 @@ func TLSFiles() (cert, key string) { return strings.TrimSpace(os.Getenv(TLSCertEnv)), strings.TrimSpace(os.Getenv(TLSKeyEnv)) } -// TLSOn: the gateway serves other computers over HTTPS. +// TLSOn: the gateway serves other computers over HTTPS: with the files +// set, or with mTLS on (mtls.go). func TLSOn() bool { c, k := TLSFiles() - return c != "" && k != "" + return c != "" && k != "" || MTLSOn() } // Scheme is the gateway's scheme for other computers: https with TLS on. @@ -102,7 +103,16 @@ func TLSSummary() string { if !TLSOn() { return "" } - c, err := tls.LoadX509KeyPair(TLSFiles()) + var c tls.Certificate + var err error + if cf, kf := TLSFiles(); cf != "" && kf != "" { + c, err = tls.LoadX509KeyPair(cf, kf) + } else { + var own *tls.Certificate + if own, err = ownServerCert(nil); own != nil { + c = *own + } + } if err != nil || len(c.Certificate) == 0 { return "" } @@ -168,36 +178,44 @@ func (f *certFiles) get(*tls.ClientHelloInfo) (*tls.Certificate, error) { return f.served, nil } -// tlsConfig is the server's config for the files set, nil with TLS off. -func tlsConfig() (*tls.Config, error) { +// tlsConfig is the server's TLS for the files set, nil with none set. +func tlsConfig() (*tlsServer, error) { if err := CheckTLS(); err != nil { return nil, err } - if !TLSOn() { + cert, key := TLSFiles() + if cert == "" || key == "" { return nil, nil } - cert, key := TLSFiles() f := &certFiles{cert: cert, key: key} if _, err := f.get(nil); err != nil { return nil, err } - return &tls.Config{ - GetCertificate: f.get, - MinVersion: tls.VersionTLS12, - // HTTP/1.1 alone, as over plain HTTP: Codex's websocket and the - // streams' handling hijack the connection - NextProtos: []string{"http/1.1"}, - }, nil + return &tlsServer{files: f}, nil } -// ServeTLS wraps ln to serve TLS, with plain HTTP for this computer's own -// connections, when the files are set; ln as it is otherwise. +// serverTLS is what a listener serves with: the files set, or nothing +// until mTLS is turned on (tlsServer.config asks on each connection). +func serverTLS() (*tlsServer, error) { + t, err := tlsConfig() + if err != nil { + return nil, err + } + if t == nil { + t = &tlsServer{} + } + return t, nil +} + +// ServeTLS wraps ln to serve TLS to other computers, with plain HTTP for +// this computer's own connections, when the files are set or mTLS is on, +// as each connection comes. func ServeTLS(ln net.Listener) (net.Listener, error) { - cfg, err := tlsConfig() - if err != nil || cfg == nil { + t, err := serverTLS() + if err != nil { return ln, err } - return newTLSListener(ln, cfg), nil + return newTLSListener(ln, t), nil } // fromThisComputer: the connection's peer is this computer — loopback, or @@ -228,7 +246,7 @@ const sniffWait = 10 * time.Second // holds up the next. type tlsListener struct { net.Listener - cfg *tls.Config + serve *tlsServer conns chan net.Conn done chan struct{} stopped chan struct{} @@ -236,8 +254,8 @@ type tlsListener struct { once sync.Once } -func newTLSListener(ln net.Listener, cfg *tls.Config) *tlsListener { - l := &tlsListener{Listener: ln, cfg: cfg, conns: make(chan net.Conn), done: make(chan struct{}), stopped: make(chan struct{})} +func newTLSListener(ln net.Listener, serve *tlsServer) *tlsListener { + l := &tlsListener{Listener: ln, serve: serve, conns: make(chan net.Conn), done: make(chan struct{}), stopped: make(chan struct{})} go l.accept() return l } @@ -262,14 +280,31 @@ func (l *tlsListener) accept() { } wait = 0 if !fromThisComputer(c) { - l.hand(tls.Server(c, l.cfg)) + // a WSL distro's agent may call over plain HTTP, and shows no + // client certificate: the guards judge it by its key + wsl := fromWSLNet(c) + cfg := l.serve.config(!wsl) + // (with --tls-cert alone, as before: TLS, and nothing asked) + switch { + case cfg == nil: + l.taken(c) + case wsl && MTLSOn(): + go l.sniff(c, cfg) + default: + l.taken(tls.Server(c, cfg)) + } continue } - go l.sniff(c) + cfg := l.serve.config(false) + if cfg == nil { + l.taken(c) + continue + } + go l.sniff(c, cfg) } } -func (l *tlsListener) sniff(c net.Conn) { +func (l *tlsListener) sniff(c net.Conn, cfg *tls.Config) { c.SetReadDeadline(time.Now().Add(sniffWait)) first := make([]byte, 1) if _, err := io.ReadFull(c, first); err != nil { @@ -279,7 +314,7 @@ func (l *tlsListener) sniff(c net.Conn) { c.SetReadDeadline(time.Time{}) p := &peeked{Conn: c, r: io.MultiReader(bytes.NewReader(first), c)} if first[0] == 0x16 { // a TLS record of type handshake - l.hand(tls.Server(p, l.cfg)) + l.hand(tls.Server(p, cfg)) return } l.hand(p) @@ -293,14 +328,31 @@ func (l *tlsListener) hand(c net.Conn) { } } +// taken hands the server a connection the listener's own Accept returned, +// as a bare listener's Accept would, even when Close came while it was +// being taken: the server's Accept waits for the loop to stop, so a +// connection taken just before the end began (a handover's) is served, +// not reset. It waits a second at most for a server no longer accepting. +func (l *tlsListener) taken(c net.Conn) { + select { + case l.conns <- c: + case <-l.done: + select { + case l.conns <- c: + case <-time.After(time.Second): + c.Close() + } + } +} + +// Accept returns the next connection, and an error only once the loop +// taking them has stopped (Close ends it), so none it took is lost. func (l *tlsListener) Accept() (net.Conn, error) { select { case c := <-l.conns: return c, nil case <-l.stopped: return nil, l.err - case <-l.done: - return nil, net.ErrClosed } } diff --git a/internal/gui/api.go b/internal/gui/api.go index 185c1d4a1..a8b8f23b2 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -418,6 +418,12 @@ type settingsJSON struct { AllowIPsEnv string `json:"allowIPsEnv,omitempty"` AllowIPsFromEnv []string `json:"allowIPsFromEnv,omitempty"` OnNetwork bool `json:"onNetwork,omitempty"` + // the client certificates issued and still good (mtls.go), while + // other computers can reach magpie or mTLS is on; MTLSSaved: the + // folder the one just issued was saved to + MTLSCerts []mtlsCert `json:"mtlsCerts,omitempty"` + MTLSErr string `json:"mtlsError,omitempty"` + MTLSSaved string `json:"mtlsSaved,omitempty"` // Dir is the data folder beside a portable magpie (#508) Portable bool `json:"portable,omitempty"` // Log is the log the desktop app writes (applog), as shown; "" for a @@ -815,6 +821,9 @@ func settingsState() settingsJSON { if list, env := gateway.AllowIPs(); env { s.AllowIPsEnv, s.AllowIPsFromEnv = os.Getenv(gateway.AllowIPsEnv), list } + if s.LAN || s.OnNetwork || s.MTLS { + s.MTLSCerts, s.MTLSErr = mtlsCerts() + } if s.LAN || gateway.OnNetwork() { s.PublicURL = gateway.PublicURL() s.PublicKind = gateway.URLKind(s.PublicURL) @@ -1496,6 +1505,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { sessionManageRoutes(mux, w) backupRoutes(mux, w) dataFolderRoutes(mux, w) + mtlsRoutes(mux, w) uninstallRoutes(mux, w) archiveRoutes(mux) libraryRoutes(mux, w) diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 35a259838..526c7a2de 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -5060,3 +5060,5 @@ body .row.agent .ag-prefs .row.pref .who { display: block; } .sess-tools .led-rename { flex: none; width: 180px; height: 26px; padding: 0 8px; border-radius: 7px; font-size: 12px; } /* Settings › About › Open-source licenses: the notices, as written */ .notices-text { 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; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index a9b36e92e..b4368ac52 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -8005,7 +8005,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.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.http1 || d.socket || d.imageFilesOff || d.passErrors) || + !!(d.searches || d.authHeader || d.passUserAgent === false || d.unredacted || d.countFree || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.http1 || d.socket || d.imageFilesOff || d.passErrors || d.clientCert || d.serverCA) || !!d.fallback?.length || !!p?.balanceToken?.set; } function priceRateError(ed) { @@ -8080,8 +8080,11 @@ function asTyped() { // provider of the user's own body.insecureTLS = !!draft.insecureTLS; body.http1 = !!draft.http1; + // a client certificate typed (#5596) is tried as it would be saved + for (const k of CERT_FIELDS) if (draft[k] != null) body[k] = draft[k].trim(); return body; } +const CERT_FIELDS = ["clientCert", "clientKey", "serverCA"]; // proxyOfDraft is the draft's proxy as it is saved, or null when Custom // has no address yet. @@ -8110,12 +8113,8 @@ const KEY_PROXY_HINT = "Each key can go through a proxy of its own; Provider's p function keyProxyPicker(p) { return proxyLines((p?.keyList || []).map((k) => ({ k: k.id, name: k.name || k.masked, key: k.id, info: k })), KEY_PROXY_HINT, true); } -// proxyLines: a line for each account or key. A provider's keys fold as -// its Accounts list folds them (keyFold): past KEYS_FOLD, the first -// KEYS_FIRST and those with a proxy of their own, or, opened, those the -// filter matches, KEYS_PAGE at most. A line for each of a thousand keys -// took the editor a minute to open, five thousand three (@NetRozee on X). -// A key not drawn keeps the proxy it has: only a line picked in changes it. +// proxyLines: a line for each account or key, keys folded as keyFold +// does (@NetRozee on X); a key not drawn keeps its proxy. function proxyLines(items, hint, foldKeys) { if (items.length < 2) return null; draft.accountProxies = draft.accountProxies || {}; @@ -9298,7 +9297,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, insecureTLS: !!p.insecureTLS, http1: !!p.http1, socket: p.socket || "", limitRestOff: !!p.limitRestOff, 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, insecureTLS: !!p.insecureTLS, http1: !!p.http1, clientCert: p.clientCert || "", clientKey: p.clientKey || "", serverCA: p.serverCA || "", socket: p.socket || "", limitRestOff: !!p.limitRestOff, 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). @@ -9329,11 +9328,9 @@ function renderEditor(p, presetID) { function drawEditor(p, presetID) { const pr = presetID ? providers.presets.find((x) => x.id === presetID) : p?.preset ? providers.presets.find((x) => x.id === p.preset) : null; const isNew = !p, custom = !pr && !p?.account, decides = !!(p?.decide || pr?.decide); - // a preset already added is added again only through "Add another": one - // more provider of it, under a name and id of its own + // a preset added again only through "Add another" const another = isNew && !!pr?.added; - // an editor opened afresh has Model settings folded: it stayed open in - // every editor after, until magpie was restarted (Hu9956, #868) + // Model settings folded afresh (#868) if (!draft) naming = unpickedShown = picksLeft = null; draft = draft || (p ? draftOf(p) @@ -9457,14 +9454,11 @@ function drawEditor(p, presetID) { // the Redaction row, shown while every address is on this computer or // the local network let showLocal = () => {}; - // the Certificate row, shown while a provider of the user's own has an - // https:// address (#2383) + // the Certificate rows, shown over https:// (#2383, #5596) let showTLS = () => {}; - // the Key header row, shown while the provider has a third-party - // Anthropic API, which is sent its key in both headers by default + // the Key header row, for a third-party Anthropic API let showAuth = () => {}; - // the Compaction row, shown while the provider has a Responses API - // (Provider.CarriesCompaction): Codex's own compaction can go only there + // the Compaction row, for a Responses API (CarriesCompaction) let showCompaction = () => {}; let showSocket = () => {}; const carriesCompaction = () => !!((draft.responses ?? (isNew && pr ? pr.responses : "")) || "").trim(); @@ -9520,9 +9514,7 @@ function drawEditor(p, presetID) { }; const urlWrap = el("div", "stack"); urlWrap.append(seg, url); - // the APIs that answered a detection, taken for the provider: their - // URLs set, one that wasn't found there (404, 405) cleared, and the - // base URL's protocol one of those that answered + // the APIs a detection found: URLs set, a 404/405 one cleared const useDetected = (rs) => { carried = null; for (const x of rs) { @@ -9664,9 +9656,7 @@ function drawEditor(p, presetID) { return ed; } - // a vendor reached at the user's own resource (Azure OpenAI): no URL of - // the preset's, the one the resource is at is typed or pasted here, and - // magpie puts it on the API the preset speaks when it is saved + // a vendor at the user's own resource (Azure OpenAI): its URL typed here let endpoint = null; if (pr?.endpoint) { if (draft.chat === undefined) { draft.chat = p?.chat || ""; draft.responses = p?.responses || ""; } @@ -9680,8 +9670,7 @@ function drawEditor(p, presetID) { // (provider.AtAddress); shown first, never folded (mengxiangziyou on X) let address = null, addressField = null; if (pr?.kind === "local") { - // a saved provider's URLs (or a duplicate's) start it; a new one's are - // the preset's, sent as none unless moved, so the gateway takes them + // a saved provider's URLs start it; a new one's are the preset's const own = draft.chat !== undefined; // oMLX's decision API (#1641) is the same server's, and moves with it draft.addressFrom ??= { chat: draft.chat ?? pr.chat ?? "", responses: draft.responses ?? pr.responses ?? "", anthropic: draft.anthropic ?? pr.anthropic ?? "", decide: draft.decide ?? (p?.decide || pr.decide || "") }; @@ -9690,8 +9679,7 @@ function drawEditor(p, presetID) { address = input(draft.address, originOf(pr)); address.inputMode = "url"; address.classList.add("address"); - // the Jev endpoint field shows where the decision API moved to, until - // one is typed there + // the Jev endpoint field follows the decision API until typed address.oninput = () => { draft.address = address.value; refreshEndpoints(); @@ -9909,6 +9897,23 @@ function drawEditor(p, presetID) { ed.append(...row); advIn.append(...hrow); } + // a client certificate and server CA (#5596, mTLS) + 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); + } // 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")); { @@ -10102,8 +10107,7 @@ function drawEditor(p, presetID) { ed.append(...field(t("Models"), pick.box, t("Optional: Fetch models to pick from the vendor's list, or type ids; none picked, magpie asks for the list after saving."))); } - // Jev's endpoint can be the one its gateway's docs give — Cloudflare's - // names the account, …/accounts//ai/run — in place of the preset's + // Jev's endpoint may be its gateway's own (Cloudflare's …/ai/run) if (decides && !custom && (p?.preset || pr?.id) !== "remote-magpie") { if (draft.decide === undefined) draft.decide = p?.decide || pr?.decide || ""; const du = input((address && movedURLs(draft)?.decide) || draft.decide, pr?.decide || "https://…", "url"); @@ -10144,9 +10148,7 @@ function drawEditor(p, presetID) { refreshEndpoints = () => { const base = p || pr || {}; const src = { chat: draft.chat || base.chat || "", responses: draft.responses || base.responses || "", anthropic: draft.anthropic || base.anthropic || "", decide: (pr && !pr.decide ? draft.decide ?? base.decide : base.decide) || "" }; - // Vertex AI's is the address its project and location make, shown - // with its Test once a project is typed, saved one or not: with none - // there is nowhere to ask + // Vertex AI's, from its project and location, once one is typed if (vertex) { src.gemini = vertexBase(draft.vertex); for (const x of row) x.hidden = !src.gemini; @@ -10299,6 +10301,7 @@ function drawEditor(p, presetID) { body.unredacted = !!draft.unredacted; body.countFree = !!draft.countFree; 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() : ""; if (socketable()) body.socket = draft.socket || ""; if (custom) body.limitRestOff = !!draft.limitRestOff; if (p?.takesImageFiles) body.imageFilesOff = !!draft.imageFilesOff; @@ -20080,6 +20083,7 @@ function renderSettings() { renderBareIds(s); renderLAN(s); renderAllow(s); + renderMTLS(s); renderCORS(s); renderSync(); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index a89884e48..7941e2351 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2715,6 +2715,16 @@ const I18N = { "Web page origin": "网页来源", "Web pages that may call magpie": "允许调用 magpie 的网页", "Allowed addresses": "允许的地址", + "Require a client certificate": "要求客户端证书", + "Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "其他电脑只能经 HTTPS、凭这里签发的证书连到 magpie,有网关密钥也不行;本机始终可以", + "Client certificates": "客户端证书", + "Saved to Downloads for the device: the certificate, its key and magpie’s CA": "为设备保存到「下载」:证书、私钥和 magpie 的 CA", + "Device name": "设备名称", + "Issue": "签发", + "Revoke": "吊销", + "This page is open from another computer without a certificate, so turning this on would shut it out: turn it on from the computer magpie runs on": "这个页面是从另一台电脑打开的,且没有证书,开启后会把它挡在外面:请在运行 magpie 的电脑上开启", + "This page uses that certificate, so it would be shut out: do this from another device, or from the computer magpie runs on": "这个页面用的正是这张证书,操作后会把它挡在外面:请在另一台设备或运行 magpie 的电脑上操作", + "A name can’t hold / \\ : * ? \" < > |": "名称不能含有 / \\ : * ? \" < > |", "On the internet": "在公网上", "An internet address: only the addresses under Allowed addresses get in": "公网地址:只有「允许的地址」里的地址能连入", "An internet address: anyone online can reach magpie here with a gateway key. To keep it to this network, list its range under Allowed addresses": "公网地址:互联网上任何人凭网关密钥都能在这里连到 magpie。只想让这个局域网连入,请在「允许的地址」里填上它的网段", @@ -4253,6 +4263,9 @@ const I18N = { "Upload images once and send them by file id": "图片只上传一次,之后按文件 ID 发送", "Off: an agent's images are sent inline on every turn.": "关闭后:智能体的图片每一轮都直接随请求发送。", "Certificate": "证书", + "Client certificate": "客户端证书", + "Server CA": "服务器 CA", + "PEM files, for a server that asks for one (mTLS)": "PEM 文件,用于要求客户端证书的服务器(mTLS)", "For your own server with a self-signed certificate or one from your company's CA. magpie then can't tell it from another machine answering at its address: turn it on only on a network you trust.": "用于你自己的服务器,证书是自签名的或来自公司内部 CA。开启后 magpie 无法分辨应答的是它本身还是同一地址上的另一台机器:只在你信任的网络中开启。", "HTTP/1.1 only": "仅 HTTP/1.1", "Send Responses turns over WebSocket": "通过 WebSocket 发送 Responses 请求", @@ -7576,6 +7589,16 @@ const I18N = { "Web page origin": "網頁來源", "Web pages that may call magpie": "允許呼叫 magpie 的網頁", "Allowed addresses": "允許的位址", + "Require a client certificate": "要求用戶端憑證", + "Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "其他電腦只能經 HTTPS、憑這裡簽發的憑證連到 magpie,有閘道金鑰也不行;本機始終可以", + "Client certificates": "用戶端憑證", + "Saved to Downloads for the device: the certificate, its key and magpie’s CA": "為裝置儲存到「下載」:憑證、私鑰和 magpie 的 CA", + "Device name": "裝置名稱", + "Issue": "簽發", + "Revoke": "撤銷", + "This page is open from another computer without a certificate, so turning this on would shut it out: turn it on from the computer magpie runs on": "這個頁面是從另一台電腦開啟的,且沒有憑證,開啟後會把它擋在外面:請在執行 magpie 的電腦上開啟", + "This page uses that certificate, so it would be shut out: do this from another device, or from the computer magpie runs on": "這個頁面用的正是這張憑證,操作後會把它擋在外面:請在另一台裝置或執行 magpie 的電腦上操作", + "A name can’t hold / \\ : * ? \" < > |": "名稱不能含有 / \\ : * ? \" < > |", "On the internet": "在網際網路上", "An internet address: only the addresses under Allowed addresses get in": "公網位址:只有「允許的位址」裡的位址能連入", "An internet address: anyone online can reach magpie here with a gateway key. To keep it to this network, list its range under Allowed addresses": "公網位址:網際網路上任何人憑閘道金鑰都能在這裡連到 magpie。只想讓這個區域網連入,請在「允許的位址」裡填上它的網段", @@ -9095,6 +9118,9 @@ const I18N = { "Upload images once and send them by file id": "圖片只上傳一次,之後按檔案 ID 傳送", "Off: an agent's images are sent inline on every turn.": "關閉後:代理的圖片每一輪都直接隨請求傳送。", "Certificate": "憑證", + "Client certificate": "用戶端憑證", + "Server CA": "伺服器 CA", + "PEM files, for a server that asks for one (mTLS)": "PEM 檔案,用於要求用戶端憑證的伺服器(mTLS)", "For your own server with a self-signed certificate or one from your company's CA. magpie then can't tell it from another machine answering at its address: turn it on only on a network you trust.": "用於你自己的伺服器,憑證是自簽的或來自公司內部 CA。開啟後 magpie 無法分辨應答的是它本身還是同一位址上的另一台機器:只在你信任的網路中開啟。", "HTTP/1.1 only": "僅 HTTP/1.1", "Send Responses turns over WebSocket": "透過 WebSocket 傳送 Responses 請求", @@ -12415,6 +12441,16 @@ const I18N = { "Web page origin": "Web ページのオリジン", "Web pages that may call magpie": "magpie を呼び出せる Web ページ", "Allowed addresses": "許可するアドレス", + "Require a client certificate": "クライアント証明書を必須にする", + "Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "他のコンピューターは、ここで発行した証明書を持って HTTPS でのみ magpie に接続できます。ゲートウェイキーがあっても同じです。このコンピューターは常に接続できます", + "Client certificates": "クライアント証明書", + "Saved to Downloads for the device: the certificate, its key and magpie’s CA": "デバイス用に「ダウンロード」へ保存:証明書、その鍵、magpie の CA", + "Device name": "デバイス名", + "Issue": "発行", + "Revoke": "失効", + "This page is open from another computer without a certificate, so turning this on would shut it out: turn it on from the computer magpie runs on": "このページは証明書なしで別のコンピューターから開かれているため、オンにするとこのページが締め出されます:magpie が動いているコンピューターでオンにしてください", + "This page uses that certificate, so it would be shut out: do this from another device, or from the computer magpie runs on": "このページはその証明書を使っているため、締め出されます:別のデバイスか、magpie が動いているコンピューターから操作してください", + "A name can’t hold / \\ : * ? \" < > |": "名前に / \\ : * ? \" < > | は使えません", "On the internet": "インターネット上", "An internet address: only the addresses under Allowed addresses get in": "インターネット上のアドレス:「許可するアドレス」にあるアドレスだけが接続できます", "An internet address: anyone online can reach magpie here with a gateway key. To keep it to this network, list its range under Allowed addresses": "インターネット上のアドレス:ゲートウェイキーがあれば、インターネット上の誰でもここから magpie に接続できます。このネットワークだけにするには、その範囲を「許可するアドレス」に追加してください", @@ -13953,6 +13989,9 @@ const I18N = { "Upload images once and send them by file id": "画像は一度だけアップロードし、以降はファイル ID で送る", "Off: an agent's images are sent inline on every turn.": "オフ:エージェントの画像を毎ターンそのまま送ります。", "Certificate": "証明書", + "Client certificate": "クライアント証明書", + "Server CA": "サーバー CA", + "PEM files, for a server that asks for one (mTLS)": "PEM ファイル。クライアント証明書を求めるサーバー(mTLS)用", "For your own server with a self-signed certificate or one from your company's CA. magpie then can't tell it from another machine answering at its address: turn it on only on a network you trust.": "自己署名証明書や社内 CA の証明書を使う自分のサーバー向けです。オンにすると、magpie はそのアドレスで応答しているのが本物か別のマシンかを見分けられません。信頼できるネットワークでのみオンにしてください。", "HTTP/1.1 only": "HTTP/1.1 のみ", "Send Responses turns over WebSocket": "Responses のリクエストを WebSocket で送る", @@ -17285,6 +17324,16 @@ const I18N = { "Web page origin": "Herkunft der Webseite", "Web pages that may call magpie": "Webseiten, die magpie aufrufen dürfen", "Allowed addresses": "Erlaubte Adressen", + "Require a client certificate": "Client-Zertifikat verlangen", + "Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "Andere Computer erreichen magpie nur über HTTPS mit einem hier ausgestellten Zertifikat, auch mit Gateway-Schlüssel; dieser Computer immer", + "Client certificates": "Client-Zertifikate", + "Saved to Downloads for the device: the certificate, its key and magpie’s CA": "Für das Gerät in „Downloads“ gespeichert: das Zertifikat, sein Schlüssel und magpies CA", + "Device name": "Gerätename", + "Issue": "Ausstellen", + "Revoke": "Widerrufen", + "This page is open from another computer without a certificate, so turning this on would shut it out: turn it on from the computer magpie runs on": "Diese Seite ist ohne Zertifikat von einem anderen Computer geöffnet, Einschalten würde sie aussperren: schalte es auf dem Computer ein, auf dem magpie läuft", + "This page uses that certificate, so it would be shut out: do this from another device, or from the computer magpie runs on": "Diese Seite nutzt dieses Zertifikat und würde ausgesperrt: tu das von einem anderen Gerät aus oder auf dem Computer, auf dem magpie läuft", + "A name can’t hold / \\ : * ? \" < > |": "Ein Name darf / \\ : * ? \" < > | nicht enthalten", "On the internet": "Im Internet", "An internet address: only the addresses under Allowed addresses get in": "Eine Internetadresse: Nur die Adressen unter „Erlaubte Adressen“ kommen herein", "An internet address: anyone online can reach magpie here with a gateway key. To keep it to this network, list its range under Allowed addresses": "Eine Internetadresse: Jeder im Internet erreicht magpie hier mit einem Gateway-Schlüssel. Um es auf dieses Netzwerk zu beschränken, trage seinen Bereich unter „Erlaubte Adressen“ ein", @@ -18826,6 +18875,9 @@ 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", + "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)", "For your own server with a self-signed certificate or one from your company's CA. magpie then can't tell it from another machine answering at its address: turn it on only on a network you trust.": "Für Ihren eigenen Server mit selbstsigniertem Zertifikat oder einem Ihrer Firmen-CA. magpie kann ihn dann nicht von einem anderen Rechner unterscheiden, der unter seiner Adresse antwortet: nur in einem Netzwerk einschalten, dem Sie vertrauen.", "HTTP/1.1 only": "Nur HTTP/1.1", "Send Responses turns over WebSocket": "Responses-Anfragen über WebSocket senden", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 1f6d93e47..ff5ceb045 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -357,6 +357,7 @@
Local network
+
Web pages
Browser access
diff --git a/internal/gui/assets/plugins/gateway/settings.js b/internal/gui/assets/plugins/gateway/settings.js index dedc48606..231de8439 100644 --- a/internal/gui/assets/plugins/gateway/settings.js +++ b/internal/gui/assets/plugins/gateway/settings.js @@ -279,6 +279,72 @@ function renderAllow(s) { } } +// renderMTLS: client certificates (mTLS; hhdaxia on X, #5596), under +// Allowed addresses. On, other computers reach magpie over https:// only +// with a certificate issued here, a gateway key or not; this computer +// always can. A device's certificate is issued by name and saved to +// Downloads (client.pem, client-key.pem, ca.pem), one row each to revoke. +let mtlsDraft = { value: "", err: "" }; +function mtlsSays(m) { + if (/^this page is open from another computer/.test(m)) return t("This page is open from another computer without a certificate, so turning this on would shut it out: turn it on from the computer magpie runs on"); + if (/^this page came with that certificate/.test(m)) return t("This page uses that certificate, so it would be shut out: do this from another device, or from the computer magpie runs on"); + if (/a name can.t hold/.test(m)) return t("A name can’t hold / \\ : * ? \" < > |"); + return t(m); +} +function renderMTLS(s) { + const box = $("#mtlsList"); + if (!box) return; + box.replaceChildren(); + if (!s.lan && !s.onNetwork && !s.mtls) return; + const d = mtlsDraft; + const post = (what, body, done) => writingPrefs(api("settings/mtls" + what, body)) + .then((ns) => { + prefs = ns; d.err = ""; done?.(); renderSettings(); + if (ns.mtlsSaved) status(t("Saved to {path}", { path: ns.mtlsSaved }), "ok", 4000); + }) + .catch((e) => { d.err = mtlsSays(e.message); status(d.err, "err"); renderSettings(); }); + const row = (cls, name, sub, ...tools) => { + const r = el("div", "row pref " + cls); + const who = el("div", "who"); + who.append(el("div", "name", name)); + if (sub) who.append(sub instanceof Node ? sub : el("div", "sub", sub)); + const val = el("div", "val"); + val.append(...tools); + r.append(who, val); + box.append(r); + return r; + }; + row("mtls-row", t("Require a client certificate"), + d.err ? el("div", "sub err", d.err) : t("Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can"), + segs([["off", t("Off")], ["on", t("On")]], s.mtls ? "on" : "off", (v) => post("", { on: v === "on" }))); + const field = input(d.value, t("Device name")); + field.className = "words rule-match mtls-name"; + field.setAttribute("aria-label", t("Device name")); + field.autocomplete = "off"; + field.spellcheck = false; + const issue = el("button", "text", t("Issue")); + issue.type = "button"; + issue.onclick = () => { + d.value = field.value.trim(); + if (!d.value) return field.focus(); + post("/issue", { name: d.value }, () => { d.value = ""; }); + }; + field.oninput = () => { d.value = field.value; }; + field.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") issue.onclick(); }; + const add = el("div", "val rule-add"); + add.append(field, issue); + const r = row("rule-row mtls-issue", t("Client certificates"), + s.mtlsError ? el("div", "sub err", t(s.mtlsError)) : t("Saved to Downloads for the device: the certificate, its key and magpie’s CA")); + r.querySelector(".val").replaceWith(add); + for (const c of s.mtlsCerts || []) { + const until = new Date(c.expires).toLocaleDateString(intlLang(), { year: "numeric", month: "short", day: "numeric" }); + const x = el("button", "text", t("Revoke")); + x.type = "button"; + x.onclick = () => post("/revoke", { serial: c.serial }); + row("mtls-cert", c.name, t("Until {date}", { date: until }), x); + } +} + // renderLAN: the gateway shared on the local network, for agents on other // machines. Gateway keys and connection examples live together in Gateway. let lanSelectedURL = "", lanProtocol = "openai"; diff --git a/internal/gui/mtls.go b/internal/gui/mtls.go new file mode 100644 index 000000000..d88fd2259 --- /dev/null +++ b/internal/gui/mtls.go @@ -0,0 +1,124 @@ +package gui + +import ( + "crypto/x509" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/mtls" + "github.com/yetone/magpie/internal/settings" +) + +// mtlsCert is a client certificate magpie issued (hhdaxia on X, #5596), +// for Settings → Network and sharing: one still good, the newest last. +type mtlsCert struct { + Name string `json:"name"` + Serial string `json:"serial"` + Expires time.Time `json:"expires"` +} + +// mtlsCerts: the certificates still good, and the list's error when it +// can't be read (then none is admitted either). +func mtlsCerts() ([]mtlsCert, string) { + l, err := gateway.MTLSStore().List() + if err != nil { + return nil, err.Error() + } + out := []mtlsCert{} + now := time.Now() + for _, c := range l { + if c.Good(now) { + out = append(out, mtlsCert{Name: c.Name, Serial: c.Serial, Expires: c.Expires}) + } + } + return out, "" +} + +// pageCert is the client certificate a browser page came with (magpie +// web, or the app's page, opened from another computer): revoking it, or +// issuing its name again, would shut that page out at its next request. +func pageCert(w Windows, r *http.Request) *x509.Certificate { + if !isWeb(w) || r.TLS == nil || len(r.TLS.PeerCertificates) == 0 { + return nil + } + return r.TLS.PeerCertificates[0] +} + +var errOwnCert = errors.New("this page came with that certificate, so it would be shut out: do this from another device, or from the computer magpie runs on") + +func mtlsRoutes(mux *http.ServeMux, w Windows) { + // on or off: on makes the CA first. A page open from another computer + // without a certificate this magpie issued can't turn it on, which + // would shut that page out at its next request. + mux.HandleFunc("POST /api/settings/mtls", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ On bool } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if in.On { + if isWeb(w) && gateway.NeedsClientCert(r) != "" { + fail(rw, errors.New("this page is open from another computer without a client certificate this magpie issued, so turning this on would shut it out: issue one, install it in this browser, and open the page again over https://, or turn it on from the computer magpie runs on")) + return + } + if _, _, err := gateway.MTLSStore().CA(); err != nil { + fail(rw, err) + return + } + } + if err := settings.SetMTLS(in.On); err != nil { + fail(rw, err) + return + } + writeJSON(rw, settingsState()) + }) + // a certificate for a device, saved to Downloads as magpie-: + // client.pem, client-key.pem and ca.pem; the key is kept nowhere else + mux.HandleFunc("POST /api/settings/mtls/issue", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ Name string } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if c := pageCert(w, r); c != nil && strings.EqualFold(c.Subject.CommonName, strings.TrimSpace(in.Name)) { + fail(rw, errOwnCert) + return + } + iss, err := gateway.MTLSStore().Issue(in.Name) + if err != nil { + fail(rw, err) + return + } + dir, err := mtls.Export(iss, downloads()) + if err != nil { + fail(rw, fmt.Errorf("issued, but the files couldn't be saved, so the certificate is revoked again: %w", err)) + gateway.MTLSStore().Revoke(iss.Serial) + return + } + _ = w.OpenFolder(dir) // saved either way; the path is in the answer + st := settingsState() + st.MTLSSaved = tilde(dir) + writeJSON(rw, st) + }) + mux.HandleFunc("POST /api/settings/mtls/revoke", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ Serial string } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if c := pageCert(w, r); c != nil && strings.EqualFold(c.SerialNumber.Text(16), strings.TrimSpace(in.Serial)) { + fail(rw, errOwnCert) + return + } + if _, err := gateway.MTLSStore().Revoke(in.Serial); err != nil { + fail(rw, err) + return + } + writeJSON(rw, settingsState()) + }) +} diff --git a/internal/gui/mtls_test.go b/internal/gui/mtls_test.go new file mode 100644 index 000000000..d28f3545d --- /dev/null +++ b/internal/gui/mtls_test.go @@ -0,0 +1,194 @@ +package gui + +import ( + "crypto/tls" + "crypto/x509" + "encoding/json" + "encoding/pem" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +func mtlsMux(t *testing.T, w Windows) func(r *http.Request) (int, settingsJSON, string) { + t.Helper() + mux := http.NewServeMux() + mtlsRoutes(mux, w) + return func(r *http.Request) (int, settingsJSON, string) { + t.Helper() + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, r) + var s settingsJSON + json.Unmarshal(rec.Body.Bytes(), &s) + return rec.Code, s, rec.Body.String() + } +} + +func mtlsReq(path, body string) *http.Request { + return httptest.NewRequest("POST", path, strings.NewReader(body)) +} + +// leafFile reads the certificate an issue saved. +func leafFile(t *testing.T, path string) *x509.Certificate { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + p, _ := pem.Decode(b) + c, err := x509.ParseCertificate(p.Bytes) + if err != nil { + t.Fatal(err) + } + return c +} + +// Settings → Network and sharing (hhdaxia on X, #5596): turning mTLS on +// makes the CA, Issue saves a device's three files to Downloads and lists +// it, Revoke takes it off the list and out of the admitted. +func TestSettingsMTLSIssueRevoke(t *testing.T) { + h := sandboxHome(t) + os.MkdirAll(filepath.Join(h, "Downloads"), 0o755) + post := mtlsMux(t, folderOnly{}) + + code, s, out := post(mtlsReq("/api/settings/mtls", `{"on":true}`)) + if code != 200 || !s.MTLS || !settings.Shared().MTLS { + t.Fatalf("on: %d %s", code, out) + } + if _, _, err := gateway.MTLSStore().CA(); err != nil { + t.Fatal(err) + } + code, s, out = post(mtlsReq("/api/settings/mtls/issue", `{"name":"laptop"}`)) + if code != 200 || len(s.MTLSCerts) != 1 || s.MTLSCerts[0].Name != "laptop" || s.MTLSSaved == "" { + t.Fatalf("issue: %d %s", code, out) + } + dir := filepath.Join(h, "Downloads", "magpie-laptop") + for _, f := range []string{"client.pem", "client-key.pem", "ca.pem"} { + if _, err := os.Stat(filepath.Join(dir, f)); err != nil { + t.Fatalf("not saved: %v", err) + } + } + leaf := leafFile(t, filepath.Join(dir, "client.pem")) + if err := gateway.MTLSStore().Admits(leaf); err != nil { + t.Fatalf("issued, not admitted: %v", err) + } + if code, _, _ := post(mtlsReq("/api/settings/mtls/issue", `{"name":"a/b"}`)); code == 200 { + t.Fatal("a name with a slash issued") + } + code, s, out = post(mtlsReq("/api/settings/mtls/revoke", `{"serial":"`+s.MTLSCerts[0].Serial+`"}`)) + if code != 200 || len(s.MTLSCerts) != 0 { + t.Fatalf("revoke: %d %s", code, out) + } + if gateway.MTLSStore().Admits(leaf) == nil { + t.Fatal("revoked, still admitted") + } + if code, s, _ = post(mtlsReq("/api/settings/mtls", `{"on":false}`)); code != 200 || s.MTLS || settings.Shared().MTLS { + t.Fatal("still on") + } +} + +// A page open from another computer never shuts itself out: without a +// certificate it can't turn mTLS on; with one it can't revoke that one +// or issue its name again. The computer magpie runs on can do all three. +func TestSettingsMTLSPageLockout(t *testing.T) { + h := sandboxHome(t) + os.MkdirAll(filepath.Join(h, "Downloads"), 0o755) + app := mtlsMux(t, folderOnly{}) + app(mtlsReq("/api/settings/mtls", `{"on":true}`)) + _, s, _ := app(mtlsReq("/api/settings/mtls/issue", `{"name":"phone"}`)) + app(mtlsReq("/api/settings/mtls", `{"on":false}`)) + if len(s.MTLSCerts) != 1 { + t.Fatal("not issued") + } + serial := s.MTLSCerts[0].Serial + leaf := leafFile(t, filepath.Join(h, "Downloads", "magpie-phone", "client.pem")) + web := mtlsMux(t, webHost{}) + + far := mtlsReq("/api/settings/mtls", `{"on":true}`) + far.RemoteAddr = "192.168.1.30:50000" + if code, _, out := web(far); code == 200 || !strings.Contains(out, "without a client certificate") || settings.Shared().MTLS { + t.Fatalf("a page from another computer without a certificate turned it on: %d %s", code, out) + } + near := mtlsReq("/api/settings/mtls", `{"on":true}`) + near.RemoteAddr = "127.0.0.1:50000" + if code, _, out := web(near); code != 200 || !settings.Shared().MTLS { + t.Fatalf("this computer's page: %d %s", code, out) + } + // the page that came with phone's certificate + withCert := func(path, body string) *http.Request { + r := mtlsReq(path, body) + r.RemoteAddr = "192.168.1.30:50000" + r.TLS = &tls.ConnectionState{PeerCertificates: []*x509.Certificate{leaf}, VerifiedChains: [][]*x509.Certificate{{leaf}}} + return r + } + if code, _, out := web(withCert("/api/settings/mtls/revoke", `{"serial":"`+strings.ToUpper(serial)+`"}`)); code == 200 || !strings.Contains(out, "this page came with that certificate") { + t.Fatalf("revoked its own: %d %s", code, out) + } + if code, _, out := web(withCert("/api/settings/mtls/issue", `{"name":" PHONE "}`)); code == 200 || !strings.Contains(out, "this page came with that certificate") { + t.Fatalf("issued its own name again: %d %s", code, out) + } + if gateway.MTLSStore().Admits(leaf) != nil { + t.Fatal("its certificate was revoked") + } + if code, _, out := web(withCert("/api/settings/mtls", `{"on":true}`)); code != 200 { + t.Fatalf("a page with a good certificate: %d %s", code, out) + } + if code, _, out := app(mtlsReq("/api/settings/mtls/revoke", `{"serial":"`+serial+`"}`)); code != 200 { + t.Fatalf("the app's revoke: %d %s", code, out) + } +} + +// The provider editor's certificate paths (#5596): saved typed with ~, +// shown back with it, kept by a Save that leaves them out, and cleared by +// one that sends them empty. +func TestProviderSaveClientCert(t *testing.T) { + h := sandboxHome(t) + os.MkdirAll(filepath.Join(h, "Downloads"), 0o755) + app := mtlsMux(t, folderOnly{}) + if code, _, out := app(mtlsReq("/api/settings/mtls/issue", `{"name":"laptop"}`)); code != 200 { + t.Fatalf("%d %s", code, out) + } + mux := http.NewServeMux() + providerRoutes(mux, nil) + post := func(body string) (int, string) { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/save", strings.NewReader(body))) + return w.Code, w.Body.String() + } + base := `{"id":"home","name":"Home","key":"k","chat":"https://home.example:3425/v1","icon":"generic"` + certs := `"clientCert":"~/Downloads/magpie-laptop/client.pem","clientKey":"~/Downloads/magpie-laptop/client-key.pem","serverCA":"~/Downloads/magpie-laptop/ca.pem"` + if code, out := post(base + `,"new":true,` + certs + `}`); code != 200 { + t.Fatalf("%d %s", code, out) + } + p, _ := provider.Find("home") + if p.ClientCert != filepath.Join(h, "Downloads", "magpie-laptop", "client.pem") || p.ServerCA == "" { + t.Fatalf("saved %q %q", p.ClientCert, p.ServerCA) + } + info := providerInfo(*p, nil) + if !info.TakesClientCert || info.ClientCert != "~/Downloads/magpie-laptop/client.pem" { + t.Fatalf("shown %v %q", info.TakesClientCert, info.ClientCert) + } + if code, out := post(base + `,"from":"home","models":[],"headers":{}}`); code != 200 { + t.Fatalf("%d %s", code, out) + } + if p, _ = provider.Find("home"); p.ClientCert == "" || p.ClientKey == "" { + t.Fatal("a Save that left them out cleared them") + } + if code, out := post(base + `,"from":"home","models":[],"headers":{},"clientCert":"","clientKey":"","serverCA":""}`); code != 200 { + t.Fatalf("%d %s", code, out) + } + if p, _ = provider.Find("home"); p.ClientCert != "" || p.ServerCA != "" { + t.Fatal("sent empty, still kept") + } + if code, _ := post(base + `,"from":"home","models":[],"headers":{},"clientCert":"~/Downloads/magpie-laptop/client.pem"}`); code == 200 { + t.Fatal("a certificate without its key saved") + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index d0af5a29d..92d57919f 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -139,6 +139,13 @@ type providerJSON struct { // spoken HTTP/1.1 to, never HTTP/2 (provider.HTTP1); taken where // TakesInsecureTLS is HTTP1 bool `json:"http1"` + // the client certificate, its key and the server CA it is reached + // with (provider.ClientCert, #5596), as shown; TakesClientCert: it + // may have them, being the user's own or Remote magpie + ClientCert string `json:"clientCert,omitempty"` + ClientKey string `json:"clientKey,omitempty"` + ServerCA string `json:"serverCA,omitempty"` + TakesClientCert bool `json:"takesClientCert,omitempty"` // its Responses turns over the Responses WebSocket (provider.Socket, // #5781): auto, on or ""; TakesSocket: a provider of a key with a // Responses URL @@ -810,7 +817,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, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, Socket: p.Socket, TakesSocket: p.TakesSocket(), LimitRestOff: p.LimitRestOff, 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, 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, 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, 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, @@ -1590,6 +1597,13 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // host is taken unchecked (#2383); a save that leaves it out // keeps it InsecureTLS *bool `json:"insecureTLS"` + // ClientCert, ClientKey and ServerCA are the PEM files of a + // client certificate it shows and a CA its server may be + // signed by (#5596, provider.ClientCert); a save that leaves + // them out keeps them + ClientCert *string `json:"clientCert"` + ClientKey *string `json:"clientKey"` + ServerCA *string `json:"serverCA"` // HTTP1 is whether its own hosts are spoken HTTP/1.1 to; a // save that leaves it out keeps it HTTP1 *bool `json:"http1"` @@ -2024,6 +2038,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) if req.HTTP1 != nil { in.HTTP1 = *req.HTTP1 } @@ -2071,6 +2086,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) if req.HTTP1 != nil { in.HTTP1 = *req.HTTP1 } else if old != nil { @@ -2633,7 +2649,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { } saved := *p if req.Typed { - q := typed(*p, in, req.Proxy, req.InsecureTLS, req.HTTP1) + q := withCerts(typed(*p, in, req.Proxy, req.InsecureTLS, req.HTTP1), p, req.ClientCert, req.ClientKey, req.ServerCA) p = &q } if len(req.Test) > 0 { @@ -2670,7 +2686,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { } p = *saved } - p = typed(p, in, req.Proxy, req.InsecureTLS, req.HTTP1) + p = withCerts(typed(p, in, req.Proxy, req.InsecureTLS, req.HTTP1), &p, req.ClientCert, req.ClientKey, req.ServerCA) if strings.TrimSpace(in.Decide) != "" { // a decision API is asked its smallest question, at // POST …/systemone (#647) @@ -2752,7 +2768,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if p.Name == "" { p.Name = cmp.Or(strings.TrimSpace(in.Name), "the vendor") } - p = typed(p, in, req.Proxy, req.InsecureTLS, req.HTTP1) + p = withCerts(typed(p, in, req.Proxy, req.InsecureTLS, req.HTTP1), &p, req.ClientCert, req.ClientKey, req.ServerCA) ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) defer cancel() all, err := p.ListAll(ctx) @@ -2796,7 +2812,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { defer cancel() ask := *p if req.Typed { - ask = typed(*p, in, req.Proxy, req.InsecureTLS, req.HTTP1) + ask = withCerts(typed(*p, in, req.Proxy, req.InsecureTLS, req.HTTP1), p, req.ClientCert, req.ClientKey, req.ServerCA) } ms, dropped, err := ask.Refetch(ctx) if err != nil { @@ -3275,6 +3291,31 @@ func typed(p, in provider.Provider, proxy *string, insecureTLS, http1 *bool) pro return p } +// withCerts is p with the client certificate, key and server CA a save +// 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 { + var kept provider.Provider + if old != nil { + kept = *old + } + pick := func(typed *string, was string) string { + if typed == nil { + return was + } + v, err := provider.CertPath(*typed) + if err != nil { + return strings.TrimSpace(*typed) // the save says why + } + return v + } + p.ClientCert = pick(cert, kept.ClientCert) + p.ClientKey = pick(key, kept.ClientKey) + p.ServerCA = pick(ca, kept.ServerCA) + return p +} + // queueOf is a save's queueLimit or queueWait: keep when the save left it // out, 0 for null, else the number. func queueOf(raw json.RawMessage, what string) (n int, keep bool, err error) { diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index ba2f0efd4..1e344b843 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -214,6 +214,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) { was.RouterNote = "Los Angeles" // the Library's servers/hub-note was.RouterAllTools = true // the Library's servers/hub-tools was.BusyLoad = 150 // the Routing page's busy-load + was.MTLS = true // Network and sharing's settings/mtls // the Routing groups page's defaults for every group (groups/defaults) was.GroupSink, was.GroupFirstToken, was.GroupPatience = true, 30, 120 if err := settings.Save(was); err != nil { diff --git a/internal/gui/tests/mtls-settings.test.cjs b/internal/gui/tests/mtls-settings.test.cjs new file mode 100644 index 000000000..5a9a2c252 --- /dev/null +++ b/internal/gui/tests/mtls-settings.test.cjs @@ -0,0 +1,317 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// mTLS (hhdaxia on X, #5596): Settings › Network, beside Allowed +// addresses, turns on Require a client certificate, issues a device's +// certificate (saved to Downloads, the path said) and revokes one. A page +// that would shut itself out is refused in its own language. Hidden while +// magpie answers only this computer. The provider editor's Advanced holds +// a Client certificate row (certificate, key, server CA) for a provider of +// the user's at https://, saved with Save; none at http:// or for a +// preset's. English and Chinese, Chromium and WebKit, 390px; the strings +// in all four languages; 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 { watchSettingsReads, settingsDrawn, reach } = require("./reader.cjs"); + +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 LOCKOUT = "this page is open from another computer without a client certificate this magpie issued, so turning this on would shut it out: issue one, install it in this browser, and open the page again over https://, or turn it on from the computer magpie runs on"; + +function settingsServer(lang, posts, over) { + const s = { + theme: "light", lang, tray: "panel", currency: "usd", version: "0.1.400", dir: "/config/magpie", + gateway: "http://127.0.0.1:3425", proxyNow: "none", proxySource: "none", login: false, + visionModels: [], imageGenModels: [], allowIPs: [], + lan: true, lanURLs: ["http://192.168.1.20:3425"], mtls: false, mtlsCerts: [], + fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, ...over, + }; + let n = 0; + 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" }, fx: s.fx }); + if (url.pathname === "/api/settings") return json(s); + if (url.pathname.startsWith("/api/settings/mtls")) { + const body = route.request().postDataJSON(); + posts.push({ path: url.pathname, body }); + delete s.mtlsSaved; + if (url.pathname === "/api/settings/mtls") { + if (body.on && s.farPage) return json({ error: LOCKOUT }, 400); + s.mtls = body.on; + } else if (url.pathname.endsWith("/issue")) { + n++; + s.mtlsCerts = [...s.mtlsCerts, { name: body.name, serial: "ab" + n, expires: "2028-11-10T00:00:00Z" }]; + s.mtlsSaved = "~/Downloads/magpie-" + body.name; + } else { + s.mtlsCerts = s.mtlsCerts.filter((c) => c.serial !== body.serial); + } + return json(s); + } + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + await file(route, url); + }; +} + +const en = { + name: "Require a client certificate", + sub: "Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can", + certs: "Client certificates", + certsSub: "Saved to Downloads for the device: the certificate, its key and magpie’s CA", + field: "Device name", issue: "Issue", revoke: "Revoke", + lockout: "This page is open from another computer without a certificate, so turning this on would shut it out: turn it on from the computer magpie runs on", + own: "This page uses that certificate, so it would be shut out: do this from another device, or from the computer magpie runs on", + cert: "Client certificate", ca: "Server CA", hint: "PEM files, for a server that asks for one (mTLS)", +}; +const zh = { name: "要求客户端证书" }; + +async function newPage(browser, width = 390, height = 640) { + const page = await (await browser.newContext({ viewport: { width, height }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + return { page, errors }; +} + +async function openSettings(browser, lang, posts, over) { + const { page, errors } = await newPage(browser); + await page.route("**/*", settingsServer(lang, posts, over)); + await watchSettingsReads(page); + await page.goto("http://127.0.0.1:4999/?view=settings&tab=network"); + await settingsDrawn(page); + return { page, errors }; +} + +async function fits(box) { + const bad = await box.evaluate((b) => { + const out = []; + const right = b.getBoundingClientRect().right + 0.5; + for (const e of b.querySelectorAll(".row, input, button, .name")) { + const r = e.getBoundingClientRect(); + if (r.right > right || r.width === 0) out.push(e.className + " " + r.right + ">" + right); + if (e.matches("button, .name") && e.scrollWidth > e.clientWidth + 1) out.push("cut: " + e.textContent); + } + if (document.documentElement.scrollWidth > innerWidth) out.push("page scrolls sideways"); + return out; + }); + assert.deepEqual(bad, []); +} + +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 home = { ...base, id: "home", name: "Home Magpie", chat: "https://home.example:3425/v1", takesClientCert: true }; +const kept = { ...base, id: "kept", name: "Kept Box", chat: "https://box.example/v1", takesClientCert: true, clientCert: "~/c/client.pem", clientKey: "~/c/client-key.pem", serverCA: "~/c/ca.pem" }; +const plain = { ...base, id: "plain", name: "Plain Box", chat: "http://192.168.1.21:8000/v1", takesClientCert: true }; +const openai = { ...base, id: "openai", name: "OpenAI", preset: "openai", chat: "https://api.openai.example/v1", takesClientCert: false }; + +function providersServer(lang, posts) { + const providers = { + providers: [home, kept, plain, openai], + presets: [{ id: "openai", name: "OpenAI", kind: "vendor", icon: "openai", chat: "https://api.openai.example/v1", added: true }], + excluded: [], gateway: { running: true, window: true }, + }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + 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") { + posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() }); + return json(providers); + } + if (url.pathname.startsWith("/api/")) return json({}); + await file(route, url); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": mTLS in Settings and the provider editor (hhdaxia, #5596)", 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 openSettings(browser, "en", []); + 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), "Until {date}", "Saved to {path}"]]); + assert.deepEqual(missing, [], lang); + } + await page.context().close(); + }); + + await t.test("hidden while magpie answers only this computer", async () => { + const { page, errors } = await openSettings(browser, "en", [], { lan: false, lanURLs: [] }); + await page.locator("#lanList .row").first().waitFor(); + assert.equal(await page.locator("#mtlsList .row").count(), 0); + assert.deepEqual(errors, []); + await page.context().close(); + }); + + for (const lang of ["en", "zh"]) { + await t.test(lang + ": on, issue, revoke", async () => { + const posts = []; + const { page, errors } = await openSettings(browser, lang, posts); + const box = page.locator("#mtlsList"); + const w = {}; + for (const [k, s] of Object.entries(en)) { + w[k] = await page.evaluate((s) => t(s), s); + if (lang !== "en") assert.notEqual(w[k], s, `"${s}" has no ${lang} translation`); + if (lang === "zh" && zh[k]) assert.equal(w[k], zh[k]); + } + const toggle = box.locator(".mtls-row"); + await toggle.waitFor(); + assert.equal((await toggle.locator(".name").textContent()).trim(), w.name); + assert.equal((await toggle.locator(".sub").textContent()).trim(), w.sub); + await fits(box); + + const on = toggle.locator("button.opt").last(); + await reach(page, on); + await on.click(); + await page.waitForFunction(() => document.querySelector("#mtlsList .mtls-row .opt.on")?.textContent && document.querySelectorAll("#mtlsList .mtls-row .opt")[1].classList.contains("on")); + assert.deepEqual(posts.at(-1), { path: "/api/settings/mtls", body: { on: true } }); + + const field = box.locator(".mtls-issue input"); + assert.equal(await field.getAttribute("aria-label"), w.field); + await reach(page, field); + await field.fill("laptop"); + const issue = box.locator(".mtls-issue button", { hasText: w.issue }); + await reach(page, issue); + await issue.click(); + await box.locator(".mtls-cert .name", { hasText: "laptop" }).waitFor(); + assert.deepEqual(posts.at(-1), { path: "/api/settings/mtls/issue", body: { name: "laptop" } }); + assert.equal(await box.locator(".mtls-issue input").inputValue(), "", "the field is left empty for the next one"); + // and with Enter + await box.locator(".mtls-issue input").fill("phone"); + await box.locator(".mtls-issue input").press("Enter"); + await box.locator(".mtls-cert .name", { hasText: "phone" }).waitFor(); + const until = await page.evaluate(() => t("Until {date}", { date: new Date("2028-11-10T00:00:00Z").toLocaleDateString(intlLang(), { year: "numeric", month: "short", day: "numeric" }) })); + assert.equal((await box.locator(".mtls-cert .sub").first().textContent()).trim(), until); + await fits(box); + + const revoke = box.locator(".mtls-cert").filter({ hasText: "laptop" }).locator("button", { hasText: w.revoke }); + await reach(page, revoke); + await revoke.click(); + await page.waitForFunction(() => document.querySelectorAll("#mtlsList .mtls-cert").length === 1); + assert.deepEqual(posts.at(-1), { path: "/api/settings/mtls/revoke", body: { serial: "ab1" } }); + const border = await box.locator(".row").first().evaluate((r) => getComputedStyle(r).borderLeftWidth); + assert(border === "0px" || border === "", "no left border accent: " + border); + assert.equal(await box.locator("select").count(), 0); + assert.deepEqual(errors, []); + await page.context().close(); + }); + } + + await t.test("a page that would shut itself out is told so in its language", async () => { + const posts = []; + const { page, errors } = await openSettings(browser, "zh", posts, { farPage: true }); + const toggle = page.locator("#mtlsList .mtls-row"); + await toggle.waitFor(); + const on = toggle.locator("button.opt").last(); + await reach(page, on); + await on.click(); + const says = await page.evaluate((s) => t(s), en.lockout); + assert.notEqual(says, en.lockout); + await page.waitForFunction((s) => document.querySelector("#mtlsList .mtls-row .sub.err")?.textContent.trim() === s, says); + assert.equal(await toggle.locator(".opt").first().evaluate((b) => b.classList.contains("on")), true, "still off"); + await fits(page.locator("#mtlsList")); + assert.deepEqual(errors, []); + await page.context().close(); + }); + + for (const lang of ["en", "zh"]) { + await t.test(lang + ": the provider editor's client certificate", async () => { + const open = async (name) => { + const { page, errors } = await newPage(browser, 420, 760); + const posts = []; + await page.route("**/*", providersServer(lang, posts)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: name }).click(); + await page.locator(".editor .bar").waitFor(); + const adv = page.locator(".editor details.advanced"); + return { page, errors, posts, adv }; + }; + const w = await (async () => { + const { page } = await newPage(browser); + await page.route("**/*", providersServer(lang, [])); + await page.goto("http://magpie.test/?view=providers"); + await page.waitForFunction(() => typeof t === "function"); + const out = await page.evaluate((ks) => Object.fromEntries(ks.map((k) => [k, t(k)])), [en.cert, en.hint, "Save"]); + await page.context().close(); + return out; + })(); + const save = async (page, posts) => { + const n = posts.length; + await page.locator(".editor .bar").getByRole("button", { name: w.Save, exact: true }).click(); + for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50); + return posts.at(-1); + }; + + { + const { page, errors, posts, adv } = await open("Home Magpie"); + assert.equal(await adv.evaluate((d) => d.open), false, "folded with nothing set"); + await adv.locator(":scope > summary").click(); + const box = page.locator(".editor .client-cert"); + await box.waitFor(); + assert.ok(await page.locator(".editor", { hasText: w[en.hint] }).count() > 0); + await box.locator("input.cert-clientCert").fill("~/magpie-laptop/client.pem"); + await box.locator("input.cert-clientKey").fill("~/magpie-laptop/client-key.pem"); + await box.locator("input.cert-serverCA").fill("~/magpie-laptop/ca.pem "); + for (const i of await box.locator("input").all()) { + const r = await i.boundingBox(); + assert.ok(r.width > 120 && r.x + r.width <= 420, "fits: " + JSON.stringify(r)); + } + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "no sideways scroll"); + const saved = await save(page, posts); + assert.equal(saved.action, "save"); + assert.equal(saved.body.clientCert, "~/magpie-laptop/client.pem"); + assert.equal(saved.body.clientKey, "~/magpie-laptop/client-key.pem"); + assert.equal(saved.body.serverCA, "~/magpie-laptop/ca.pem"); + assert.deepEqual(errors, []); + await page.context().close(); + } + { + const { page, errors, adv } = await open("Kept Box"); + assert.equal(await adv.evaluate((d) => d.open), true, "opens with them set"); + assert.equal(await page.locator(".editor .client-cert input.cert-serverCA").inputValue(), "~/c/ca.pem"); + assert.deepEqual(errors, []); + await page.context().close(); + } + { + const { page, errors, adv } = await open("Plain Box"); + await adv.locator(":scope > summary").click(); + assert.equal(await page.locator(".editor .client-cert").isVisible(), false, "none at http://"); + assert.deepEqual(errors, []); + await page.context().close(); + } + { + const { page, errors, posts } = await open("OpenAI"); + assert.equal(await page.locator(".editor .client-cert").count(), 0); + const saved = await save(page, posts); + assert.equal("clientCert" in saved.body, false, "a preset's Save sends none"); + assert.deepEqual(errors, []); + await page.context().close(); + } + }); + } + }); +} diff --git a/internal/gui/web.go b/internal/gui/web.go index 74787d686..c97adccbb 100644 --- a/internal/gui/web.go +++ b/internal/gui/web.go @@ -343,7 +343,7 @@ func LANAddrs() []string { // routes, judged by the gateway (onePort), and the page and its API behind // the allow list and the key. func webServed(port, key string, keep time.Duration, page http.Handler) http.Handler { - return onePort(gateway.AllowGuard(webHandler(port, key, keep, page))) + return onePort(gateway.AllowGuard(gateway.ClientCertGuard(webHandler(port, key, keep, page)))) } // webHandler is what `magpie web` on port serves: the page and its API diff --git a/internal/mtls/mtls.go b/internal/mtls/mtls.go new file mode 100644 index 000000000..1084510ce --- /dev/null +++ b/internal/mtls/mtls.go @@ -0,0 +1,458 @@ +// Package mtls is magpie's own certificate authority for mutual TLS +// (hhdaxia on X: "希望能支持 mtls,避免暴露端口到公网被 compromise"; +// #5596). With it on (settings' MTLS, `magpie mtls on`), the gateway and +// `magpie web`'s page serve other computers over HTTPS with a server +// certificate this CA signs (or the user's own, --tls-cert), and a +// connection from another computer is let in only with a client +// certificate this CA issued and nobody revoked. Client certificates are +// issued for a device by name (`magpie mtls issue `, Settings → +// Network and sharing) and exported as PEM files beside the CA's own +// certificate, which the device trusts the server by: Remote magpie takes +// all three (provider.ClientCert, ClientKey and ServerCA), as curl does +// (--cert, --key, --cacert). +// +// The CA's key never leaves this computer: it is kept in magpie's folder +// (0600) and is neither synced nor backed up, as the files here are no +// part of those. +package mtls + +import ( + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "math/big" + "net" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "sync/atomic" + "time" +) + +// Store is the CA kept in Dir: ca.pem, ca-key.pem and clients.json, the +// certificates issued. +type Store struct{ Dir string } + +// Client is a client certificate issued: Name the device's, as the user +// gave it; Serial the certificate's, in hex; Revoked when it was taken +// back, zero while it is good. +type Client struct { + Name string `json:"name"` + Serial string `json:"serial"` + Issued time.Time `json:"issued"` + Expires time.Time `json:"expires"` + Revoked time.Time `json:"revoked,omitzero"` +} + +// Good: issued, not revoked and not run out at now. +func (c Client) Good(now time.Time) bool { return c.Revoked.IsZero() && now.Before(c.Expires) } + +// Validity of what the CA signs: the CA ten years, a client certificate +// two, a server certificate (made again at each start) one. +const ( + caLife = 10 * 365 * 24 * time.Hour + clientLife = 2 * 365 * 24 * time.Hour + serverLife = 365 * 24 * time.Hour +) + +var mu sync.Mutex // one change to a store's files at a time, in this process + +func (s Store) caFile() string { return filepath.Join(s.Dir, "ca.pem") } +func (s Store) caKeyFile() string { return filepath.Join(s.Dir, "ca-key.pem") } +func (s Store) clientsFile() string { return filepath.Join(s.Dir, "clients.json") } + +// CAFile is the CA's certificate, the file a device trusts the server by. +func (s Store) CAFile() string { return s.caFile() } + +// HasCA: the CA was made. +func (s Store) HasCA() bool { + _, err := os.Stat(s.caKeyFile()) + return err == nil +} + +// CA is the store's CA, made on first use. +func (s Store) CA() (*x509.Certificate, crypto.Signer, error) { + mu.Lock() + defer mu.Unlock() + return s.ca() +} + +func (s Store) ca() (*x509.Certificate, crypto.Signer, error) { + cb, cerr := os.ReadFile(s.caFile()) + kb, kerr := os.ReadFile(s.caKeyFile()) + if cerr == nil && kerr == nil { + return parsePair(cb, kb) + } + if !errors.Is(cerr, os.ErrNotExist) && cerr != nil { + return nil, nil, cerr + } + if !errors.Is(kerr, os.ErrNotExist) && kerr != nil { + return nil, nil, kerr + } + if cerr == nil || kerr == nil { + // one of the two alone: never made over, which would orphan every + // certificate the CA issued + return nil, nil, fmt.Errorf("magpie's mTLS CA in %s is missing its certificate or its key", s.Dir) + } + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, nil, err + } + host, _ := os.Hostname() + now := time.Now() + tmpl := &x509.Certificate{ + SerialNumber: serial(), + Subject: pkix.Name{CommonName: strings.TrimSpace("magpie CA " + host), Organization: []string{"magpie"}}, + NotBefore: now.Add(-time.Hour), + NotAfter: now.Add(caLife), + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature, + BasicConstraintsValid: true, + IsCA: true, + MaxPathLenZero: true, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + return nil, nil, err + } + kder, err := x509.MarshalPKCS8PrivateKey(key) + if err != nil { + return nil, nil, err + } + if err := os.MkdirAll(s.Dir, 0o700); err != nil { + return nil, nil, err + } + if err := writeFile(s.caKeyFile(), pemOf("PRIVATE KEY", kder), 0o600); err != nil { + return nil, nil, err + } + if err := writeFile(s.caFile(), pemOf("CERTIFICATE", der), 0o644); err != nil { + return nil, nil, err + } + cert, err := x509.ParseCertificate(der) + return cert, key, err +} + +func parsePair(cb, kb []byte) (*x509.Certificate, crypto.Signer, error) { + p, _ := pem.Decode(cb) + if p == nil { + return nil, nil, errors.New("magpie's mTLS CA certificate isn't PEM") + } + cert, err := x509.ParseCertificate(p.Bytes) + if err != nil { + return nil, nil, err + } + k, _ := pem.Decode(kb) + if k == nil { + return nil, nil, errors.New("magpie's mTLS CA key isn't PEM") + } + key, err := x509.ParsePKCS8PrivateKey(k.Bytes) + if err != nil { + return nil, nil, err + } + signer, ok := key.(crypto.Signer) + if !ok { + return nil, nil, errors.New("magpie's mTLS CA key can't sign") + } + return cert, signer, nil +} + +// Pool is the CA as a pool a server verifies client certificates by. +func (s Store) Pool() (*x509.CertPool, error) { + ca, _, err := s.CA() + if err != nil { + return nil, err + } + pool := x509.NewCertPool() + pool.AddCert(ca) + return pool, nil +} + +// Issued is a client certificate as it was issued, with its key: the +// only time the key is seen, as the store keeps none. +type Issued struct { + Client + Cert, Key, CA []byte // PEM +} + +// Issue signs a client certificate for the device name. One issued +// before under the same name, still good, is revoked: the name is the +// device's, and a device issued again (a lost or new one) has the one +// certificate. +func (s Store) Issue(name string) (Issued, error) { + name = strings.TrimSpace(name) + if name == "" { + return Issued{}, errors.New("a client certificate needs a name, the device's: magpie mtls issue ") + } + if strings.ContainsAny(name, "/\\:*?\"<>|") || strings.ContainsFunc(name, func(r rune) bool { return r < ' ' }) { + return Issued{}, fmt.Errorf("%q: a name can't hold / \\ : * ? \" < > | or control characters", name) + } + mu.Lock() + defer mu.Unlock() + ca, caKey, err := s.ca() + if err != nil { + return Issued{}, err + } + clients, err := s.clients() + if err != nil { + return Issued{}, err + } + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return Issued{}, err + } + now := time.Now() + sn := serial() + tmpl := &x509.Certificate{ + SerialNumber: sn, + Subject: pkix.Name{CommonName: name, Organization: []string{"magpie"}}, + NotBefore: now.Add(-time.Hour), + NotAfter: now.Add(clientLife), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, ca, &key.PublicKey, caKey) + if err != nil { + return Issued{}, err + } + kder, err := x509.MarshalPKCS8PrivateKey(key) + if err != nil { + return Issued{}, err + } + for i := range clients { + if strings.EqualFold(clients[i].Name, name) && clients[i].Revoked.IsZero() { + clients[i].Revoked = now + } + } + c := Client{Name: name, Serial: sn.Text(16), Issued: now, Expires: tmpl.NotAfter} + clients = append(clients, c) + if err := s.saveClients(clients); err != nil { + return Issued{}, err + } + return Issued{Client: c, Cert: pemOf("CERTIFICATE", der), Key: pemOf("PRIVATE KEY", kder), CA: pemOf("CERTIFICATE", ca.Raw)}, nil +} + +// List is every certificate issued, the newest first. +func (s Store) List() ([]Client, error) { + mu.Lock() + defer mu.Unlock() + c, err := s.clients() + slices.SortStableFunc(c, func(a, b Client) int { return b.Issued.Compare(a.Issued) }) + return c, err +} + +// Revoke takes back the good certificates of the device name, or the one +// whose serial name is. A connection already made with one ends with its +// next request: the gateway asks Admits on each handshake and each +// request. +func (s Store) Revoke(name string) (int, error) { + name = strings.TrimSpace(name) + mu.Lock() + defer mu.Unlock() + clients, err := s.clients() + if err != nil { + return 0, err + } + n := 0 + for i := range clients { + if (strings.EqualFold(clients[i].Name, name) || strings.EqualFold(clients[i].Serial, name)) && clients[i].Revoked.IsZero() { + clients[i].Revoked = time.Now() + n++ + } + } + if n == 0 { + return 0, fmt.Errorf("no certificate issued to %q is in use: magpie mtls list", name) + } + return n, s.saveClients(clients) +} + +// Admits says whether cert, a client certificate the CA's pool verified, +// is let in: issued here and not revoked. One the list doesn't hold (its +// file lost, or edited) is refused, as is any when the list can't be +// read. +func (s Store) Admits(cert *x509.Certificate) error { + clients, err := s.cachedClients() + if err != nil { + return fmt.Errorf("the client certificates issued can't be read: %w", err) + } + sn := cert.SerialNumber.Text(16) + for _, c := range clients { + if c.Serial == sn { + if !c.Revoked.IsZero() { + return fmt.Errorf("the client certificate %q was revoked", c.Name) + } + return nil + } + } + return fmt.Errorf("the client certificate %q isn't one this magpie issued", cert.Subject.CommonName) +} + +var cache struct { + sync.Mutex + gen int64 // saves in this process, so one within the file's mtime tick is seen + path string + mod time.Time + size int64 + clients []Client +} + +// cachedClients is clients.json, parsed again only when it changed: it is +// asked on every handshake. +func (s Store) cachedClients() ([]Client, error) { + fi, err := os.Stat(s.clientsFile()) + if err != nil { + return nil, err + } + cache.Lock() + defer cache.Unlock() + if cache.path == s.clientsFile() && cache.mod.Equal(fi.ModTime()) && cache.size == fi.Size() && cache.gen == saves.Load() { + return cache.clients, nil + } + gen := saves.Load() + mu.Lock() + c, err := s.clients() + mu.Unlock() + if err != nil { + return nil, err + } + cache.path, cache.mod, cache.size, cache.clients, cache.gen = s.clientsFile(), fi.ModTime(), fi.Size(), c, gen + return c, nil +} + +func (s Store) clients() ([]Client, error) { + b, err := os.ReadFile(s.clientsFile()) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var out []Client + if err := json.Unmarshal(b, &out); err != nil { + return nil, fmt.Errorf("%s: %w", s.clientsFile(), err) + } + return out, nil +} + +func (s Store) saveClients(c []Client) error { + b, err := json.MarshalIndent(c, "", " ") + if err != nil { + return err + } + defer saves.Add(1) + return writeFile(s.clientsFile(), append(b, '\n'), 0o600) +} + +var saves atomic.Int64 + +// ServerCert is a server certificate the CA signs for names and ips, with +// its key: made in memory each time the gateway starts serving, never +// written. +func (s Store) ServerCert(names []string, ips []net.IP) (tls.Certificate, error) { + ca, caKey, err := s.CA() + if err != nil { + return tls.Certificate{}, err + } + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return tls.Certificate{}, err + } + now := time.Now() + cn := "magpie" + if len(names) > 0 { + cn = names[0] + } + tmpl := &x509.Certificate{ + SerialNumber: serial(), + Subject: pkix.Name{CommonName: cn, Organization: []string{"magpie"}}, + NotBefore: now.Add(-time.Hour), + NotAfter: now.Add(serverLife), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + DNSNames: names, + IPAddresses: ips, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, ca, &key.PublicKey, caKey) + if err != nil { + return tls.Certificate{}, err + } + leaf, err := x509.ParseCertificate(der) + if err != nil { + return tls.Certificate{}, err + } + return tls.Certificate{Certificate: [][]byte{der, ca.Raw}, PrivateKey: key, Leaf: leaf}, nil +} + +// Export writes what a device needs to dir/magpie-: client.pem, +// client-key.pem (0600) and ca.pem, and returns that folder. +func Export(iss Issued, dir string) (string, error) { + out := filepath.Join(dir, "magpie-"+strings.ReplaceAll(iss.Name, " ", "-")) + if _, err := os.Stat(out); err == nil { + for i := 2; ; i++ { + o := fmt.Sprintf("%s-%d", out, i) + if _, err := os.Stat(o); errors.Is(err, os.ErrNotExist) { + out = o + break + } + } + } + if err := os.MkdirAll(out, 0o700); err != nil { + return "", err + } + for _, f := range []struct { + name string + b []byte + mode os.FileMode + }{{"client.pem", iss.Cert, 0o644}, {"client-key.pem", iss.Key, 0o600}, {"ca.pem", iss.CA, 0o644}} { + if err := writeFile(filepath.Join(out, f.name), f.b, f.mode); err != nil { + return "", err + } + } + return out, nil +} + +func serial() *big.Int { + n, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127)) + if err != nil { + panic(err) + } + return n.Add(n, big.NewInt(1)) +} + +func pemOf(typ string, der []byte) []byte { + return pem.EncodeToMemory(&pem.Block{Type: typ, Bytes: der}) +} + +// writeFile writes b to path through a temp file renamed over it, so a +// reader never sees half of one. +func writeFile(path string, b []byte, mode os.FileMode) error { + tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + if err := tmp.Chmod(mode); err != nil { + tmp.Close() + return err + } + if _, err := tmp.Write(b); err != nil { + tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmp.Name(), path) +} diff --git a/internal/mtls/mtls_test.go b/internal/mtls/mtls_test.go new file mode 100644 index 000000000..34cade709 --- /dev/null +++ b/internal/mtls/mtls_test.go @@ -0,0 +1,213 @@ +package mtls + +import ( + "crypto/tls" + "crypto/x509" + "encoding/pem" + "net" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func leafOf(t *testing.T, b []byte) *x509.Certificate { + t.Helper() + p, _ := pem.Decode(b) + if p == nil { + t.Fatal("not PEM") + } + c, err := x509.ParseCertificate(p.Bytes) + if err != nil { + t.Fatal(err) + } + return c +} + +func verifies(t *testing.T, st Store, c *x509.Certificate) error { + t.Helper() + pool, err := st.Pool() + if err != nil { + t.Fatal(err) + } + _, err = c.Verify(x509.VerifyOptions{Roots: pool, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}}) + return err +} + +// TestIssueAdmitsRevoke: a certificate issued verifies by the CA and is +// admitted; revoked, it is refused; issuing the name again revokes the one +// before and admits the new one alone. +func TestIssueAdmitsRevoke(t *testing.T) { + st := Store{Dir: filepath.Join(t.TempDir(), "mtls")} + a, err := st.Issue("laptop") + if err != nil { + t.Fatal(err) + } + ca := leafOf(t, a.CA) + if !ca.IsCA { + t.Fatal("ca.pem isn't a CA") + } + la := leafOf(t, a.Cert) + if err := verifies(t, st, la); err != nil { + t.Fatalf("issued certificate doesn't verify: %v", err) + } + if _, err := tls.X509KeyPair(a.Cert, a.Key); err != nil { + t.Fatalf("cert and key don't pair: %v", err) + } + if err := st.Admits(la); err != nil { + t.Fatalf("issued certificate refused: %v", err) + } + b, err := st.Issue("LAPTOP") + if err != nil { + t.Fatal(err) + } + if err := st.Admits(la); err == nil { + t.Fatal("a name issued again still admits the certificate before") + } + lb := leafOf(t, b.Cert) + if err := st.Admits(lb); err != nil { + t.Fatalf("new certificate refused: %v", err) + } + if n, err := st.Revoke("laptop"); err != nil || n != 1 { + t.Fatalf("revoke = %d, %v", n, err) + } + if err := st.Admits(lb); err == nil || !strings.Contains(err.Error(), "revoked") { + t.Fatalf("revoked certificate: %v", err) + } + if _, err := st.Revoke("laptop"); err == nil { + t.Fatal("revoking nothing in use is no error") + } + l, err := st.List() + if err != nil || len(l) != 2 { + t.Fatalf("list = %v, %v", l, err) + } + for _, c := range l { + if c.Good(c.Issued) { + t.Errorf("%s still good", c.Serial) + } + } +} + +// TestRevokeBySerial: a serial names one certificate. +func TestRevokeBySerial(t *testing.T) { + st := Store{Dir: t.TempDir()} + a, _ := st.Issue("a") + b, _ := st.Issue("b") + if n, err := st.Revoke(strings.ToUpper(a.Serial)); err != nil || n != 1 { + t.Fatalf("revoke = %d, %v", n, err) + } + if st.Admits(leafOf(t, a.Cert)) == nil || st.Admits(leafOf(t, b.Cert)) != nil { + t.Fatal("the serial revoked the wrong certificate") + } +} + +// TestAdmitsRefusesForeign: a certificate another CA signed, or this CA's +// own not on the list (the list lost or unreadable), is refused. +func TestAdmitsRefusesForeign(t *testing.T) { + st := Store{Dir: t.TempDir()} + other := Store{Dir: t.TempDir()} + st.Issue("mine") + o, _ := other.Issue("theirs") + lo := leafOf(t, o.Cert) + if verifies(t, st, lo) == nil { + t.Fatal("another CA's certificate verifies") + } + if st.Admits(lo) == nil { + t.Fatal("another CA's certificate admitted") + } + m, _ := st.Issue("phone") + lm := leafOf(t, m.Cert) + if err := os.WriteFile(st.clientsFile(), []byte("{not json"), 0o600); err != nil { + t.Fatal(err) + } + if err := st.Admits(lm); err == nil { + t.Fatal("an unreadable list admits") + } + if _, err := st.Issue("x"); err == nil { + t.Fatal("issue over an unreadable list wrote over it") + } + os.Remove(st.clientsFile()) + if err := st.Admits(lm); err == nil { + t.Fatal("a lost list admits") + } +} + +// TestCAHalfMissing: a CA with its key or its certificate gone is an +// error, never made over (which would orphan every certificate issued). +func TestCAHalfMissing(t *testing.T) { + st := Store{Dir: t.TempDir()} + if _, _, err := st.CA(); err != nil { + t.Fatal(err) + } + if runtime.GOOS != "windows" { + if fi, _ := os.Stat(st.caKeyFile()); fi.Mode().Perm() != 0o600 { + t.Errorf("ca-key.pem mode %v", fi.Mode().Perm()) + } + } + os.Remove(st.caFile()) + if _, _, err := st.CA(); err == nil { + t.Fatal("a CA without its certificate was made over") + } + if _, err := os.Stat(st.caFile()); err == nil { + t.Fatal("ca.pem written again") + } +} + +func TestIssueName(t *testing.T) { + st := Store{Dir: t.TempDir()} + for _, n := range []string{"", " ", "a/b", `a\b`, "a:b", "a\nb"} { + if _, err := st.Issue(n); err == nil { + t.Errorf("%q issued", n) + } + } +} + +// TestServerCert: signed by the CA for the names and addresses given. +func TestServerCert(t *testing.T) { + st := Store{Dir: t.TempDir()} + c, err := st.ServerCert([]string{"localhost", "box.local"}, []net.IP{net.IPv4(192, 168, 1, 5)}) + if err != nil { + t.Fatal(err) + } + pool, _ := st.Pool() + for _, name := range []string{"box.local", "192.168.1.5"} { + if _, err := c.Leaf.Verify(x509.VerifyOptions{Roots: pool, DNSName: name}); err != nil { + t.Errorf("%s: %v", name, err) + } + } + if _, err := c.Leaf.Verify(x509.VerifyOptions{Roots: pool, DNSName: "evil.example"}); err == nil { + t.Error("signed for a name not given") + } +} + +// TestExport: three files, the key 0600, a second export beside the first. +func TestExport(t *testing.T) { + st := Store{Dir: t.TempDir()} + out := t.TempDir() + iss, _ := st.Issue("my phone") + d1, err := Export(iss, out) + if err != nil { + t.Fatal(err) + } + if filepath.Base(d1) != "magpie-my-phone" { + t.Fatalf("folder %s", d1) + } + d2, _ := Export(iss, out) + if d2 == d1 { + t.Fatal("second export over the first") + } + for _, f := range []string{"client.pem", "client-key.pem", "ca.pem"} { + if _, err := os.Stat(filepath.Join(d1, f)); err != nil { + t.Error(err) + } + } + if _, err := tls.LoadX509KeyPair(filepath.Join(d1, "client.pem"), filepath.Join(d1, "client-key.pem")); err != nil { + t.Error(err) + } + if runtime.GOOS != "windows" { + if fi, _ := os.Stat(filepath.Join(d1, "client-key.pem")); fi.Mode().Perm() != 0o600 { + t.Errorf("key mode %v", fi.Mode().Perm()) + } + } +} diff --git a/internal/netproxy/clientcert.go b/internal/netproxy/clientcert.go new file mode 100644 index 000000000..ba9b9b021 --- /dev/null +++ b/internal/netproxy/clientcert.go @@ -0,0 +1,194 @@ +package netproxy + +import ( + "context" + "crypto/tls" + "crypto/x509" + "errors" + "fmt" + "net/http" + "net/url" + "os" + "strings" + "sync" + "time" +) + +type clientCertKey struct{} + +// clientCert is a provider's own TLS identity (#5596, clxsh: a magpie at +// home behind an Nginx that asks for a client certificate, reached by +// Remote magpie from the office): the PEM certificate and key it shows +// 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 +} + +// WithClientCert is ctx for requests made on behalf of a provider that +// shows the server a certificate of its own (cert and key, PEM files), or +// trusts a CA of its own for the server's (ca, a PEM file), or both: a +// request through a transport Dispatch made to the host of one of bases, +// over https, goes through a transport kept for that identity alone, +// which shows the certificate when the server asks for one and takes a +// server certificate signed by ca beside the system's roots. Any other +// host — a redirect elsewhere, an image or a balance URL on another host +// — 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{}} + if c.cert == "" || c.key == "" { + c.cert, c.key = "", "" + } + if c.cert == "" && c.ca == "" { + return ctx + } + for _, b := range bases { + u, err := url.Parse(strings.TrimSpace(b)) + if err != nil || !strings.EqualFold(u.Scheme, "https") || u.Hostname() == "" { + continue + } + c.hosts[hostKey(u)] = true + } + if len(c.hosts) == 0 { + return ctx + } + return context.WithValue(ctx, clientCertKey{}, &c) +} + +func clientCertOf(ctx context.Context) *clientCert { + if ctx == nil { + return nil + } + c, _ := ctx.Value(clientCertKey{}).(*clientCert) + return c +} + +// 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. +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)] { + return "" + } + var b strings.Builder + for _, f := range []string{c.cert, c.key, c.ca} { + b.WriteString(f) + if f != "" { + if fi, err := os.Stat(f); err == nil { + fmt.Fprintf(&b, "\x01%d.%d", fi.ModTime().UnixNano(), fi.Size()) + } + } + b.WriteByte(0) + } + return b.String() +} + +// ErrClientCertOverHTTPSProxy is why a request made with a provider's own +// TLS identity isn't sent through an https:// proxy: the proxy's own TLS +// is dialled with the same config, so it could be shown the certificate, +// and its own be taken for being signed by the provider's CA. +var ErrClientCertOverHTTPSProxy = errors.New("a provider with a client certificate or a CA of its own can't be reached through an https:// proxy, which would be shown them too: give it an http:// or socks5:// proxy, or none") + +// clientTLS has t, a clone kept for one TLS identity (clientRoute), show +// its certificate when a server asks for one and take a server's signed +// by its CA. The files are read here, when the transport is made; one +// that doesn't load fails each handshake with why. +func clientTLS(t *http.Transport, route string) { + parts := strings.Split(route, "\x00") + file := func(i int) string { + if i >= len(parts) { + return "" + } + f, _, _ := strings.Cut(parts[i], "\x01") + return f + } + cert, key, ca := file(0), file(1), file(2) + if t.TLSClientConfig == nil { + t.TLSClientConfig = &tls.Config{} + } + cfg := t.TLSClientConfig + if cert != "" { + var once sync.Once + var pair *tls.Certificate + var perr error + cfg.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { + once.Do(func() { + c, err := tls.LoadX509KeyPair(cert, key) + if err != nil { + perr = fmt.Errorf("the client certificate %s and key %s don't load: %w", cert, key, err) + return + } + pair = &c + }) + return pair, perr + } + } + if ca != "" { + pool, err := caPool(ca) + if err != nil { + cfg.InsecureSkipVerify = false + cfg.VerifyConnection = func(tls.ConnectionState) error { return err } + } else if !cfg.InsecureSkipVerify { + cfg.RootCAs = pool + } + } + if next := t.Proxy; next != nil { + t.Proxy = func(req *http.Request) (*url.URL, error) { + u, err := next(req) + if err == nil && u != nil && strings.EqualFold(u.Scheme, "https") { + return nil, ErrClientCertOverHTTPSProxy + } + return u, err + } + } +} + +// 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) { + b, err := os.ReadFile(ca) + if err != nil { + return nil, fmt.Errorf("the server CA %s can't be read: %w", ca, err) + } + pool, err := x509.SystemCertPool() + if err != nil || pool == nil { + pool = x509.NewCertPool() + } + if !pool.AppendCertsFromPEM(b) { + return nil, fmt.Errorf("the server CA %s holds no PEM certificate", ca) + } + return pool, nil +} + +// CheckClientCert says why a provider's TLS identity can't be used: a +// certificate without its key or a key without its certificate, a pair +// that doesn't load or has run out, a CA file with no certificate. nil +// with none set. +func CheckClientCert(cert, key, ca string) error { + cert, key, ca = strings.TrimSpace(cert), strings.TrimSpace(key), strings.TrimSpace(ca) + switch { + case cert != "" && key == "": + return fmt.Errorf("the client certificate %s needs its private key too", cert) + case cert == "" && key != "": + return fmt.Errorf("the private key %s needs its client certificate too", key) + } + if cert != "" { + c, err := tls.LoadX509KeyPair(cert, key) + if err != nil { + return fmt.Errorf("the client certificate %s and key %s don't load: %w", cert, key, err) + } + if leaf, err := x509.ParseCertificate(c.Certificate[0]); err == nil && time.Now().After(leaf.NotAfter) { + return fmt.Errorf("the client certificate %s ran out on %s", cert, leaf.NotAfter.Format("2006-01-02")) + } + } + if ca != "" { + if _, err := caPool(ca); err != nil { + return err + } + } + return nil +} diff --git a/internal/netproxy/clientcert_test.go b/internal/netproxy/clientcert_test.go new file mode 100644 index 000000000..6aca5aec9 --- /dev/null +++ b/internal/netproxy/clientcert_test.go @@ -0,0 +1,205 @@ +package netproxy + +import ( + "context" + "crypto/tls" + "errors" + "io" + "log" + "net" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/mtls" +) + +// mtlsServer is an HTTPS server with a certificate st's CA signs, that +// asks for a client certificate st's CA issued (require) or takes one if +// given, and answers with the name on the one shown. +func mtlsServer(t *testing.T, st mtls.Store, require bool, h http.HandlerFunc) *httptest.Server { + t.Helper() + cert, err := st.ServerCert([]string{"localhost"}, []net.IP{net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatal(err) + } + pool, err := st.Pool() + if err != nil { + t.Fatal(err) + } + if h == nil { + h = func(w http.ResponseWriter, r *http.Request) { + name := "none" + if len(r.TLS.PeerCertificates) > 0 { + name = r.TLS.PeerCertificates[0].Subject.CommonName + } + io.WriteString(w, name) + } + } + s := httptest.NewUnstartedServer(h) + s.Config.ErrorLog = log.New(io.Discard, "", 0) + s.TLS = &tls.Config{Certificates: []tls.Certificate{cert}, ClientCAs: pool, ClientAuth: tls.VerifyClientCertIfGiven} + if require { + s.TLS.ClientAuth = tls.RequireAndVerifyClientCert + } + s.StartTLS() + t.Cleanup(s.Close) + return s +} + +// device issues a certificate for name and writes the three files a +// device is given, returning their paths. +func device(t *testing.T, st mtls.Store, name string) (cert, key, ca string) { + t.Helper() + iss, err := st.Issue(name) + if err != nil { + t.Fatal(err) + } + d, err := mtls.Export(iss, t.TempDir()) + if err != nil { + t.Fatal(err) + } + return filepath.Join(d, "client.pem"), filepath.Join(d, "client-key.pem"), filepath.Join(d, "ca.pem") +} + +func body(t *testing.T, c *http.Client, ctx context.Context, u string) (string, error) { + t.Helper() + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) + res, err := c.Do(req) + if err != nil { + return "", err + } + defer res.Body.Close() + b, err := io.ReadAll(res.Body) + return string(b), err +} + +// A provider's client certificate and server CA (#5596) reach its own +// host alone: the host it names is reached with them, while the same +// request without them, one to another host signed by the same CA, a +// redirect there, and one made for another provider (With) are not shown +// the certificate nor take the CA. +func TestClientCertOnlyItsHost(t *testing.T) { + st := mtls.Store{Dir: t.TempDir()} + other := mtlsServer(t, st, false, nil) + own := mtlsServer(t, st, true, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/elsewhere" { + http.Redirect(w, r, other.URL+"/", http.StatusFound) + return + } + io.WriteString(w, r.TLS.PeerCertificates[0].Subject.CommonName) + }) + cert, key, ca := device(t, st, "laptop") + d := Dispatch(&http.Transport{Proxy: Func, ForceAttemptHTTP2: true}).(*dispatch) + t.Cleanup(d.CloseIdleConnections) + c := &http.Client{Transport: d} + bg := context.Background() + 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) + } + if got, err := body(t, c, mine, own.URL+"/v1/models"); err != nil || got != "laptop" { + t.Fatalf("with them: %q, %v", got, err) + } + if _, err := body(t, c, mine, other.URL); !certRefused(err) { + t.Fatalf("another host: want a certificate error, got %v", err) + } + if _, err := body(t, c, mine, own.URL+"/elsewhere"); !certRefused(err) { + t.Fatalf("a redirect to another host: want a certificate error, got %v", err) + } + 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) { + t.Fatalf("an http:// base: want a certificate error, got %v", err) + } +} + +// A server CA alone (a server that takes no client certificate, signed by +// a CA of the user's) is trusted beside the system's roots, and no +// certificate is shown; a server that asks for one is refused without. +func TestServerCAAlone(t *testing.T) { + st := mtls.Store{Dir: t.TempDir()} + lenient := mtlsServer(t, st, false, nil) + strict := mtlsServer(t, st, true, nil) + _, _, ca := device(t, st, "x") + 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) + if got, err := body(t, c, ctx, lenient.URL); err != nil || got != "none" { + t.Fatalf("CA alone: %q, %v", got, err) + } + if _, err := body(t, c, ctx, strict.URL); err == nil { + t.Fatal("a server asking for a certificate answered without one") + } +} + +// A certificate renewed in place (the same paths) is shown from the next +// request: the route names each file's change. +func TestClientCertRenewedInPlace(t *testing.T) { + st := mtls.Store{Dir: t.TempDir()} + s := mtlsServer(t, st, true, nil) + 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) + if got, _ := body(t, c, ctx, s.URL); got != "old" { + t.Fatalf("got %q", got) + } + c2, k2, _ := device(t, st, "new") + for from, to := range map[string]string{c2: cert, k2: key} { + b, _ := os.ReadFile(from) + if err := os.WriteFile(to, append(b, '\n'), 0o600); err != nil { + t.Fatal(err) + } + } + if got, err := body(t, c, ctx, s.URL); got != "new" { + t.Fatalf("after renewal: %q, %v", got, err) + } +} + +// An https:// proxy would be shown the certificate (its TLS is dialled +// with the same config), so a request with one is refused there; an +// http:// proxy is used as it is. +func TestClientCertRefusesHTTPSProxy(t *testing.T) { + for scheme, refused := range map[string]bool{"https": true, "http": false} { + tr := &http.Transport{Proxy: func(*http.Request) (*url.URL, error) { return &url.URL{Scheme: scheme, Host: "proxy:8080"}, nil }} + clientTLS(tr, "c.pem\x00k.pem\x00\x00") + u, err := tr.Proxy(httptest.NewRequest(http.MethodGet, "https://h/", nil)) + if refused != errors.Is(err, ErrClientCertOverHTTPSProxy) || (!refused && u == nil) { + t.Errorf("%s proxy: %v, %v", scheme, u, err) + } + } +} + +func TestCheckClientCert(t *testing.T) { + st := mtls.Store{Dir: t.TempDir()} + cert, key, ca := device(t, st, "x") + _, otherKey, _ := device(t, st, "y") + junk := filepath.Join(t.TempDir(), "junk.pem") + os.WriteFile(junk, []byte("not pem"), 0o600) + for _, c := range []struct { + cert, key, ca string + ok bool + }{ + {"", "", "", true}, + {cert, key, ca, true}, + {cert, key, "", true}, + {"", "", ca, true}, + {cert, "", "", false}, + {"", key, "", false}, + {cert, otherKey, "", false}, + {cert, key, junk, false}, + {cert, key, filepath.Join(t.TempDir(), "gone.pem"), false}, + } { + if err := CheckClientCert(c.cert, c.key, c.ca); (err == nil) != c.ok { + t.Errorf("%q %q %q: %v", filepath.Base(c.cert), filepath.Base(c.key), filepath.Base(c.ca), err) + } + } +} diff --git a/internal/netproxy/netproxy.go b/internal/netproxy/netproxy.go index 88a4d1544..49eb94373 100644 --- a/internal/netproxy/netproxy.go +++ b/internal/netproxy/netproxy.go @@ -122,12 +122,16 @@ func Held(ctx context.Context) error { // "direct", #1522) goes through its own provider's proxy, never the one // it was made under. A provider's leave not to check its certificate // (WithUncheckedTLS) goes the same way: it is the outer provider's, and -// dropped here, and so is its ask for HTTP/1.1 (WithHTTP1). +// dropped here, and so is its ask for HTTP/1.1 (WithHTTP1) and its own +// TLS identity (WithClientCert). func With(ctx context.Context, choice string) context.Context { - if choice = strings.TrimSpace(choice); choice == "" && choiceOf(ctx) == "" && uncheckedOf(ctx) == nil && http1Of(ctx) == nil { + if choice = strings.TrimSpace(choice); choice == "" && choiceOf(ctx) == "" && uncheckedOf(ctx) == nil && http1Of(ctx) == nil && clientCertOf(ctx) == nil { return ctx } ctx = context.WithValue(ctx, choiceKey{}, choice) + if clientCertOf(ctx) != nil { + ctx = context.WithValue(ctx, clientCertKey{}, (*clientCert)(nil)) + } if uncheckedOf(ctx) != nil { ctx = context.WithValue(ctx, uncheckedKey{}, map[string]bool(nil)) } @@ -195,7 +199,8 @@ var HTTP1 func(u *url.URL) bool // connection carried a TLS record that didn't decrypt (recordError, for h2Broken after) go // through a clone kept for HTTP/1.1 (http1Only), and one to a host whose certificate the provider's user // said not to check (WithUncheckedTLS) through a clone kept for that -// host alone (uncheckTLS). A host whose IPv6 is taken but goes nowhere +// host alone (uncheckTLS), and one made with a provider's own TLS +// identity (WithClientCert) through a clone kept for it (clientTLS). A host whose IPv6 is taken but goes nowhere // is dialed over IPv4 (v4Fallback). func Dispatch(base *http.Transport) http.RoundTripper { v4Fallback(base) @@ -219,13 +224,14 @@ type route struct { choice string h1 bool unchecked string + client string // clientRoute } func (d *dispatch) RoundTrip(req *http.Request) (*http.Response, error) { if d.moved() { d.CloseIdleConnections() } - r := route{choice: choiceOf(req.Context()), h1: HTTP1 != nil && HTTP1(req.URL) || http1Asked(req) || overHTTP1(req.Context()) || h2BrokenFor(req), unchecked: uncheckedHost(req)} + r := route{choice: choiceOf(req.Context()), h1: HTTP1 != nil && HTTP1(req.URL) || http1Asked(req) || overHTTP1(req.Context()) || h2BrokenFor(req), unchecked: uncheckedHost(req), client: clientRoute(req)} t := d.base if r != (route{}) { t = d.transport(r) @@ -303,6 +309,9 @@ func (d *dispatch) transport(r route) *http.Transport { if r.unchecked != "" { uncheckTLS(t) } + if r.client != "" { + clientTLS(t, r.client) + } if isCalm(d.base) { // a clone shares base's HTTP/2 connections, dialled through // base's proxy, until it is given its own diff --git a/internal/provider/client_cert_test.go b/internal/provider/client_cert_test.go new file mode 100644 index 000000000..7a16a0715 --- /dev/null +++ b/internal/provider/client_cert_test.go @@ -0,0 +1,138 @@ +package provider + +import ( + "context" + "crypto/tls" + "io" + "log" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/mtls" +) + +// mtlsMagpie is a magpie behind mTLS (#5596, clxsh: an Nginx asking for +// a client certificate in front of the magpie at home): its certificate +// is st's CA's, and it answers only a client showing one st issued, with +// the gateway key. +func mtlsMagpie(t *testing.T, st mtls.Store) *httptest.Server { + t.Helper() + cert, err := st.ServerCert([]string{"localhost"}, []net.IP{net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatal(err) + } + pool, _ := st.Pool() + s := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer remote-key" && r.Header.Get("x-api-key") != "remote-key" { + http.Error(w, "no key", http.StatusUnauthorized) + return + } + w.Header().Set("Content-Type", "application/json") + if strings.HasSuffix(r.URL.Path, "/chat/completions") { + io.WriteString(w, `{"id":"c1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`) + return + } + io.WriteString(w, `{"data":[{"id":"home/model"}]}`) + })) + s.Config.ErrorLog = log.New(io.Discard, "", 0) + s.TLS = &tls.Config{Certificates: []tls.Certificate{cert}, ClientCAs: pool, ClientAuth: tls.RequireAndVerifyClientCert} + s.StartTLS() + t.Cleanup(s.Close) + return s +} + +// Remote magpie with a client certificate, its key and the server's CA +// lists the other magpie's models and passes its connection test; without +// them both fail on the certificate. The paths are kept whole, a ~ taken +// as home. +func TestRemoteMagpieClientCert(t *testing.T) { + azureHome(t) + dialsOut(t) + st := mtls.Store{Dir: t.TempDir()} + srv := mtlsMagpie(t, st) + iss, err := st.Issue("office") + if err != nil { + t.Fatal(err) + } + home, _ := os.UserHomeDir() + dir, err := mtls.Export(iss, home) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if err := Save(Provider{ID: "office", Preset: RemoteMagpiePreset, Key: "remote-key", Chat: srv.URL}); err != nil { + t.Fatal(err) + } + p, _ := Find("office") + if _, err := p.List(ctx); err == nil { + t.Fatal("without a certificate: listed") + } + if rs := p.Test(ctx); len(rs) == 0 || rs[0].OK { + t.Fatalf("its test without a certificate: %+v", rs) + } + base := "~/" + filepath.Base(dir) + "/" + p.ClientCert, p.ClientKey, p.ServerCA = base+"client.pem", base+"client-key.pem", base+"ca.pem" + if err := Save(*p); err != nil { + t.Fatal(err) + } + p, _ = Find("office") + if p.ClientCert != filepath.Join(dir, "client.pem") || p.ServerCA != filepath.Join(dir, "ca.pem") { + t.Fatalf("paths kept as %q %q", p.ClientCert, p.ServerCA) + } + ms, err := p.List(ctx) + if err != nil || len(ms) != 1 { + t.Fatalf("with a certificate: %v %v", ms, err) + } + if rs := p.Test(ctx); len(rs) == 0 || !rs[0].OK { + t.Fatalf("its test with a certificate: %+v", rs) + } + // the server's CA alone: the server is trusted, the handshake still + // refused for want of a certificate + p.ClientCert, p.ClientKey = "", "" + if err := Save(*p); err != nil { + t.Fatal(err) + } + p, _ = Find("office") + if _, err := p.List(ctx); err == nil || certError(err) && strings.Contains(err.Error(), "unknown authority") { + t.Fatalf("CA alone: %v, want the handshake refused, not the server", err) + } +} + +// What Save refuses: a certificate for a preset's provider, one without +// its key, a relative path, a pair that doesn't match, a CA file that +// isn't one. +func TestClientCertSaveChecks(t *testing.T) { + azureHome(t) + st := mtls.Store{Dir: t.TempDir()} + a, _ := st.Issue("a") + b, _ := st.Issue("b") + da, _ := mtls.Export(a, t.TempDir()) + db, _ := mtls.Export(b, t.TempDir()) + cert, key, ca := filepath.Join(da, "client.pem"), filepath.Join(da, "client-key.pem"), filepath.Join(da, "ca.pem") + own := func(c, k, s string) Provider { + return Provider{ID: "home", Name: "Home", Chat: "https://home.example/v1", Key: "k", Models: []string{"m"}, ClientCert: c, ClientKey: k, ServerCA: s} + } + for name, c := range map[string]struct { + p Provider + ok bool + }{ + "all three": {own(cert, key, ca), true}, + "CA alone": {own("", "", ca), true}, + "no key": {own(cert, "", ""), false}, + "key alone": {own("", key, ""), false}, + "relative": {own("client.pem", "client-key.pem", ""), false}, + "another's key": {own(cert, filepath.Join(db, "client-key.pem"), ""), false}, + "CA not PEM": {own("", "", key), false}, + "a preset's": {Provider{ID: "openrouter", Preset: "openrouter", Key: "k", ClientCert: cert, ClientKey: key}, false}, + } { + err := Save(c.p) + if (err == nil) != c.ok { + t.Errorf("%s: %v", name, err) + } + } +} diff --git a/internal/provider/insecure_tls.go b/internal/provider/insecure_tls.go index 80bb09950..0a0e7f1c4 100644 --- a/internal/provider/insecure_tls.go +++ b/internal/provider/insecure_tls.go @@ -1,5 +1,12 @@ package provider +import ( + "fmt" + "os" + "path/filepath" + "strings" +) + // TakesInsecureTLS is whether the provider may have its certificate left // unchecked (InsecureTLS, #2383): only one the user added with a base URL // of their own. A subscription's or a plugin's account, a preset's (whose @@ -9,6 +16,14 @@ func (p Provider) TakesInsecureTLS() bool { return p.Account == nil && p.Preset == "" && !p.IsVertex() && hasEndpoint(p) && !subscriptionID(p.ID) } +// TakesClientCert is whether the provider may show a client certificate +// of its own, or trust a server CA of its own (ClientCert, #5596): one the +// user added with a base URL of its own, as TakesInsecureTLS, and Remote +// magpie, whose other magpie may ask for one (`magpie mtls`). +func (p Provider) TakesClientCert() bool { + return p.Account == nil && (p.Preset == "" || p.IsRemoteMagpie()) && !p.IsVertex() && hasEndpoint(p) && !subscriptionID(p.ID) +} + // 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. @@ -21,3 +36,24 @@ func (p Provider) UncheckedHosts() []string { } return out } + +// CertPath is a client certificate's, key's or CA's file as ClientCert +// keeps it: ~ taken as home, and a whole path, since the gateway reads it +// from wherever it was started. +func CertPath(p string) (string, error) { + p = strings.Trim(strings.TrimSpace(p), `"'`) + if p == "" { + return "", nil + } + if rest, ok := strings.CutPrefix(p, "~"); ok && (rest == "" || rest[0] == '/' || rest[0] == '\\') { + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + p = filepath.Join(home, rest) + } + if !filepath.IsAbs(p) { + return "", fmt.Errorf("%s: give the file's whole path", p) + } + return filepath.Clean(p), nil +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 1fcbb47df..4830f4c74 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -29,6 +29,7 @@ import ( "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/lastgood" "github.com/yetone/magpie/internal/lazyre" + "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/settings" "github.com/yetone/magpie/internal/steady" ) @@ -461,6 +462,19 @@ type Provider struct { // (UncheckedHosts); see Via. HTTP1 bool `json:"http1,omitempty"` + // ClientCert and ClientKey are the PEM files of a client certificate + // magpie shows the provider's own HTTPS hosts when they ask for one, + // and ServerCA a PEM CA their certificate may be signed by beside the + // system's roots (#5596, clxsh, and hhdaxia on X: Remote magpie to a + // magpie at home behind an Nginx that requires a client certificate, + // or one with `magpie mtls` on). Only a provider the user added, and + // Remote magpie, takes them (TakesClientCert), for the hosts of its + // own base URLs (UncheckedHosts), on every request made for it: + // models, the connection test, requests, quotas; see Via. + ClientCert string `json:"clientCert,omitempty"` + ClientKey string `json:"clientKey,omitempty"` + ServerCA string `json:"serverCA,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), @@ -1244,6 +1258,21 @@ 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 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) + } + for _, f := range []*string{&p.ClientCert, &p.ClientKey, &p.ServerCA} { + v, err := CertPath(*f) + if err != nil { + return fmt.Errorf("%s: %w", p.ID, err) + } + *f = v + } + if err := netproxy.CheckClientCert(p.ClientCert, p.ClientKey, p.ServerCA); err != nil { + return fmt.Errorf("%s: %w", p.ID, err) + } + } if strings.Contains(p.Decide, WorkspaceID) { return errors.New("Bailian's decision model is asked at your workspace's host: give its workspace ID (workspace=… or the editor's Workspace ID), or pick the Token Plan") } diff --git a/internal/provider/proxy.go b/internal/provider/proxy.go index 1059acbaf..b20c1d6fe 100644 --- a/internal/provider/proxy.go +++ b/internal/provider/proxy.go @@ -27,6 +27,9 @@ 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()...) + } return withSocket(ctx, p) } diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 30e8c0b4f..f6f7c209b 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -220,6 +220,13 @@ type Settings struct { // its place (gateway.AllowIPs). This computer's own (KeepOwn), as LAN // is: the addresses are of the network this computer is on. AllowIPs []string `json:"allowIPs,omitempty"` + // MTLS has other computers show a client certificate magpie issued + // (`magpie mtls`, Settings → Network and sharing) before anything is + // answered (hhdaxia on X, #5596): the gateway and magpie web's page + // are served over TLS with magpie's own CA, and a remote request + // without a good certificate is refused. This computer's own + // (KeepOwn), as LAN is. + MTLS bool `json:"mtls,omitempty"` // FetchPrivate are the private hosts and ranges (a name, name:port, an // IP or a CIDR range) magpie may download a URL from that it didn't // choose itself: an image or video a request names or a vendor answers @@ -1499,7 +1506,7 @@ func (s *Settings) KeepOwn(cur Settings) { s.NoWSLAgents = cur.NoWSLAgents s.QuotaReads = cur.QuotaReads s.NoAccountDiscovery = cur.NoAccountDiscovery - s.LAN, s.AllowIPs = cur.LAN, cur.AllowIPs + s.LAN, s.AllowIPs, s.MTLS = cur.LAN, cur.AllowIPs, cur.MTLS s.RouterNote, s.RouterAllTools = cur.RouterNote, cur.RouterAllTools s.FetchPrivate = cur.FetchPrivate s.SessionTerminal = cur.SessionTerminal @@ -1990,6 +1997,18 @@ func SetGatewayConversations(on bool) error { return save(s, true) } +// SetMTLS sets MTLS alone, from what the file holds now. A settings file +// that can't be read is left as it is, with the error. +func SetMTLS(on bool) error { + defer lockFile()() + s, err := loadChecked() + if err != nil { + return err + } + s.MTLS = on + return save(s, false) +} + // SetQuitNoAsk sets QuitNoAsk alone, from what the file holds now (the // Quit question's "Don't ask again"). A settings file that can't be read // is left as it is, with the error. diff --git a/internal/settingsapi/settingsapi.go b/internal/settingsapi/settingsapi.go index 1c4df10d4..350308c1a 100644 --- a/internal/settingsapi/settingsapi.go +++ b/internal/settingsapi/settingsapi.go @@ -286,6 +286,7 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err in.Port = cur.Port // set on its own (port), which moves the gateway in.CORSOrigins = cur.CORSOrigins // set on its own (cors) in.AllowIPs = cur.AllowIPs // set on its own (allowips) + in.MTLS = cur.MTLS // set on its own (mtls) in.FetchPrivate = cur.FetchPrivate // in settings.json only in.RouterNote = cur.RouterNote // set on its own (the Library's servers/hub-note) in.RouterAllTools = cur.RouterAllTools // set on its own (the Library's servers/hub-tools)