diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 7ec8c0a50..31f53293b 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -398,7 +398,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. - A Codex Responses Lite request (an `additional_tools` input item, or `reasoning.context` `all_turns`; Codex 0.165 and on) carries its instructions in the input, and Codex sends it with no top-level `instructions` and no `reasoning.summary`. `codexBody` adds neither to it (`codexLite`): before, it added Codex's full instructions and `summary: "auto"`, about 4K input tokens a request more than the official client (legeling567 on X; `TestCodexBodyLiteGetsNoInstructions`). A request that isn't Lite still gets them. The backend's `x-codex-turn-state` stays with the account that issued it: the gateway keeps the state a reply gave for that account and turn (`client_metadata` `thread_id` and `turn_id`) and sends it on the turn's next request to the same account, as Codex over HTTP sends it back; a state Codex sends itself goes only to the account that issued it ([codex_turnstate.go](../../internal/gateway/codex_turnstate.go), `TestCodexPoolTurnStateStaysWithItsAccount`). - 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. A turn on the socket tells the try's client trace of itself as Go's client tells it of an HTTP request (`socketTrace`): on a kept socket it is a request on an open connection, on a new one the handshake's DNS, connect and TLS stand and its round trip is the wait for the connection; the message written is the request written and the first frame the reply's first byte. So the Routing page's "Where the time went" (`TryNet`) and the usage record's split have the vendor's wait for every socket turn, where a kept socket's turn had nothing but its masking and a new socket's put the backend's wait in its first token (buhaodeshiyehao on X, `TestSocketTurnTellsWhereItsTimeWent`). 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 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. magpie's own requests of a Remote magpie take the same transport: its cards and quota history (`remoteBodyAs`), a key's limit (`askRemoteKeyLimit`), the model list's wait (`waitRemoteList`), and the Library's server for its MCP router, whose checks and calls go through `ViaRemoteMagpieAt` (`viaRemoteMagpie` in `internal/library/mcp_check.go`). A 403 from one is read as "isn't shared" only when the magpie there says so (`remoteRefused`); a client certificate check's or a proxy's refusal is said as it came (hhdaxia on X, `TestRemoteMagpieOwnRequestsShowClientCert`, `TestRemoteForbiddenSaysWhatRefused`, `TestRemoteMagpieRouterShowsClientCert`). Through an `https://` proxy such a request is refused (`ErrClientCertOverHTTPSProxy`). The route is keyed on the files' paths, mtimes and sizes, so a certificate renewed in place gets a new transport (`TestRemoteMagpieClientCert`, `TestClientCertSaveChecks`, the `clientcert_test.go` tests). - The same providers may instead pin their server's certificate (`ServerPin`: the SHA-256 of its DER, lower-case hex; Zhangzhangi on X, a Remote magpie on a domain with a self-signed certificate macOS calls not standards compliant). Off by default, per provider. The editor's Advanced → Server certificate asks `POST /api/provider/peekcert`, which reaches the form's first `https://` address through its proxy and client certificate with the certificate unchecked (`Provider.PeekServerCert`) and shows its fingerprint, names, dates and why this computer doesn't take it (`x509.Verify` with the system roots); Trust keeps the pin, and the row then says in red that the certificate isn't verified. `Via` passes the pin to `netproxy.WithClientCert`, whose transport for those hosts skips the chain, name and date checks and refuses in `VerifyConnection` any leaf whose SHA-256 isn't the pin (`pinTLS`, `PinMismatchError`). The hosts it applies at are `PinHosts`: every endpoint of a provider that takes a client certificate, and of a preset's only the `https://` addresses at a host neither the preset nor its regions name (Zhangzhangi on X, "建议对别的自签名域名也生效": LM Studio or Ollama on another computer), never a subscription's, Vertex or a vendor's own host; a client certificate and Server CA still go only where `TakesClientCert` holds. `TakesServerPin` is in `/api/providers`, and the editor shows the row while the form has such an address (`pinAddrs` in app.js). `Save` refuses a pin that isn't 64 hex digits, or on a provider with no such address (`TestServerPinRemoteMagpie`, `TestServerPinSaveChecks`, `TestServerPinPresetAtOwnServer`, `TestServerPinNoVendorHost`, `TestPinOnlyThatCertificate`, `provider-server-pin.test.cjs`). - A provider may connect a host of its base URLs to addresses of the user's choosing, as `curl --resolve` (`Provider.Resolve`, a map of host name to places; quantum_lsfc on X, a managed network whose domains go to an internal L4 SNI gateway, where an IP in the base URL fails the certificate and `/etc/hosts` can't be edited). A place is an IP address (with `:port` if the gateway listens elsewhere) or `dns:`, looked up at each new connection so a rotating record is followed. Only the TCP target changes: the URL's name is still the TLS server name and the `Host`. The places are tried in order, each given 8s (`resolveTry`); when none connects, the name is dialled as if there were no rule. `Via` puts the rule on the context (`netproxy.WithResolve`), `Dispatch` keeps one transport clone per rule and wraps its `DialContext` (`resolveTLS`). Through a proxy (the provider's, the global one, the environment's) the rule is not used: the proxy gets `CONNECT` with the original name and connects itself; `RoundTrip` marks a request direct (`directKey`) only when `t.Proxy` says none. `TakesResolve` is where `TakesInsecureTLS`, `TakesClientCert` or `PinHosts` hold: a provider the user added, Remote magpie, a preset at a host of the user's own; never a subscription's account or a vendor's own host. Plugins are not covered: a plugin's requests are `fetch` calls in the Bun plugin host, which has no hook for the connection's address, so a plugin's provider takes no rule (`TakesResolve` is false for an account). `Save` runs `netproxy.CheckResolve` (bare host names, IP or `dns:` places, at most 32 hosts and 16 places) and refuses a rule on a provider that doesn't take one. The gateway's offline check leaves such a provider's host out of the hosts it dials to tell whether the network is up (`otherHosts`), since it dials them by name. The editor's Advanced → Connect to is a box of `host = place, place` lines (`resolveRow` in tlscerts.js; `TestResolveSaved`, `TestResolveVia`, `TestOtherHostsSkipResolved`, `TestProviderSaveResolve`, the `netproxy` `TestResolve*` tests, `provider-resolve.test.cjs`). - A provider the user added may be held to HTTP/1.1 (`HTTP1`, the editor's "HTTP version" row under Advanced, shown while an address is `https://`; kepner_53726 on Discord: a company gateway whose HTTP/2 streams broke mid-reply with "tls: bad record MAC" while a plain Go client held). It takes the same providers as `InsecureTLS` (`TakesInsecureTLS`), and `Save` refuses it on any other. `Provider.Via` adds `netproxy.WithHTTP1` with the hosts of its own base URLs, so a request made on its behalf to one of those hosts goes through the `Dispatch` transport's HTTP/1.1 copy (`route.h1`); another host, and a request made for another provider (`netproxy.With` drops it), are offered HTTP/2 as before (`TestHTTP1AskedOnlyItsHost`, `TestHTTP1OwnProviderOnly`, `TestProviderSaveHTTP1`). Without it, a TLS record error read on an HTTP/2 reply (`recordError`: "bad record MAC", "received record with version …", an oversized record) moves that host:port to HTTP/1.1 for 6 hours (`h2BrokenFor`; see [Gateway routing](gateway-routing.md)). diff --git a/internal/library/bridge_mtls_test.go b/internal/library/bridge_mtls_test.go new file mode 100644 index 000000000..036d1543c --- /dev/null +++ b/internal/library/bridge_mtls_test.go @@ -0,0 +1,62 @@ +package library + +import ( + "context" + "crypto/tls" + "io" + "log" + "net" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/mtls" + "github.com/yetone/magpie/internal/provider" +) + +// hhdaxia on X: a Remote magpie behind mTLS took the provider's client +// certificate for its model calls alone. The Library's server for its MCP +// router is checked, and used, through the same transport: with the +// certificate on the provider it answers; with none it is refused at the +// handshake, as before. +func TestRemoteMagpieRouterShowsClientCert(t *testing.T) { + h := sandbox(t) + st := mtls.Store{Dir: t.TempDir()} + cert, err := st.ServerCert([]string{"localhost"}, []net.IP{net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatal(err) + } + pool, _ := st.Pool() + var seen http.Header + srv := httptest.NewUnstartedServer(mcpHandler(t, false, &seen)) + srv.Config.ErrorLog = log.New(io.Discard, "", 0) + srv.TLS = &tls.Config{Certificates: []tls.Certificate{cert}, ClientCAs: pool, ClientAuth: tls.RequireAndVerifyClientCert} + srv.StartTLS() + t.Cleanup(srv.Close) + iss, err := st.Issue("office") + if err != nil { + t.Fatal(err) + } + dir, err := mtls.Export(iss, h) + if err != nil { + t.Fatal(err) + } + s := &Server{Name: "office", Transport: "http", URL: srv.URL + gateway.HubMCPAll, Bridge: "office", Headers: bridgeHeaders("remote-key")} + // the server's CA alone: trusted, but no certificate to show + if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: "remote-key", Chat: srv.URL, + ServerCA: filepath.Join(dir, "ca.pem")}); err != nil { + t.Fatal(err) + } + if got := CheckServer(context.Background(), s); got.State == "ok" { + t.Fatalf("without a client certificate: %+v", got) + } + if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: "remote-key", Chat: srv.URL, + ClientCert: filepath.Join(dir, "client.pem"), ClientKey: filepath.Join(dir, "client-key.pem"), ServerCA: filepath.Join(dir, "ca.pem")}); err != nil { + t.Fatal(err) + } + if got := CheckServer(context.Background(), s); got.State != "ok" || got.Tools != 2 { + t.Fatalf("with the provider's client certificate: %+v", got) + } +} diff --git a/internal/library/mcp_check.go b/internal/library/mcp_check.go index c4cddc4c5..5807625dd 100644 --- a/internal/library/mcp_check.go +++ b/internal/library/mcp_check.go @@ -24,6 +24,7 @@ import ( "github.com/yetone/magpie/internal/mcpauth" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/wslrun" ) @@ -104,7 +105,21 @@ var checkClient = &http.Client{Transport: checkTransport()} func checkTransport() http.RoundTripper { t := http.DefaultTransport.(*http.Transport).Clone() t.Proxy = netproxy.Func - return netproxy.Dispatch(t) + return viaRemoteMagpie{netproxy.Dispatch(t)} +} + +// viaRemoteMagpie sends a request to a Remote magpie's MCP router through +// that provider's own transport (provider.Via): its proxy, its client +// certificate and the server certificate it trusts, as its model calls go. +// Only the router's path is looked up, so no other server's request reads +// providers.json. +type viaRemoteMagpie struct{ next http.RoundTripper } + +func (t viaRemoteMagpie) RoundTrip(r *http.Request) (*http.Response, error) { + if strings.HasSuffix(strings.TrimRight(r.URL.Path, "/"), gateway.HubMCPAll) { + r = r.WithContext(provider.ViaRemoteMagpieAt(r.Context(), r.URL)) + } + return t.next.RoundTrip(r) } // checked is the last check of each server, by name, with what the diff --git a/internal/provider/proxy.go b/internal/provider/proxy.go index 7d1547f64..531695c16 100644 --- a/internal/provider/proxy.go +++ b/internal/provider/proxy.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "maps" + "net/url" "slices" "strings" @@ -284,3 +285,24 @@ func ProxyGone(p Provider) string { } return "" } + +// ViaRemoteMagpieAt is ctx for a request to u made on behalf of the +// Remote magpie whose gateway u is on (its scheme and host): Via of that +// provider, so the Library's connection to its MCP router goes as its +// model calls do (hhdaxia on X: a client certificate the remote asks for +// went with the model calls alone). ctx as it is when no Remote magpie +// is at u. +func ViaRemoteMagpieAt(ctx context.Context, u *url.URL) context.Context { + if u == nil || u.Host == "" { + return ctx + } + for _, p := range All() { + if !p.IsRemoteMagpie() || p.Anthropic == "" { + continue + } + if b, err := url.Parse(p.Anthropic); err == nil && strings.EqualFold(b.Scheme, u.Scheme) && strings.EqualFold(b.Host, u.Host) { + return p.Via(ctx) + } + } + return ctx +} diff --git a/internal/provider/remote_follow.go b/internal/provider/remote_follow.go index 070916e3c..984ac3c4b 100644 --- a/internal/provider/remote_follow.go +++ b/internal/provider/remote_follow.go @@ -234,7 +234,7 @@ func followedOne(id string) *Provider { // as the list is fetched (listHeaders, signRemote), so the list the other // magpie compares is the one a fetch is answered. func waitRemoteList(ctx context.Context, p Provider, tag string) (string, error) { - ctx, cancel := context.WithTimeout(ctx, (listWaitAsk+20)*time.Second) + ctx, cancel := context.WithTimeout(p.Via(ctx), (listWaitAsk+20)*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.Anthropic+"/v1/models", nil) if err != nil { diff --git a/internal/provider/remote_key_limits.go b/internal/provider/remote_key_limits.go index 4cd9a0bb1..e3916fa71 100644 --- a/internal/provider/remote_key_limits.go +++ b/internal/provider/remote_key_limits.go @@ -250,7 +250,7 @@ func keyWindowName(what, period string) string { // askRemoteKeyLimit asks p's gateway, with key, for that key's limit. func askRemoteKeyLimit(ctx context.Context, p Provider, key string) (*remoteKeyAnswer, error) { - ctx, cancel := context.WithTimeout(ctx, 8*time.Second) + ctx, cancel := context.WithTimeout(p.Via(ctx), 8*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.Anthropic+RemoteKeyLimitPath, nil) if err != nil { @@ -268,7 +268,7 @@ func askRemoteKeyLimit(ctx context.Context, p Provider, key string) (*remoteKeyA case res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed: return nil, errors.New(errRemoteNoKeyLimit) case res.StatusCode == http.StatusForbidden: - return nil, errors.New(errRemoteNotShared) + return nil, remoteRefused(p, res, b) case res.StatusCode == http.StatusUnauthorized: return nil, errors.New(errRemoteKey) case res.StatusCode < 200 || res.StatusCode >= 300: diff --git a/internal/provider/remote_mtls_test.go b/internal/provider/remote_mtls_test.go new file mode 100644 index 000000000..5157a6ada --- /dev/null +++ b/internal/provider/remote_mtls_test.go @@ -0,0 +1,159 @@ +package provider + +import ( + "context" + "crypto/tls" + "encoding/json" + "errors" + "io" + "log" + "net" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/yetone/magpie/internal/mtls" +) + +// mtlsPeer is a magpie behind mTLS that answers what magpie asks of a +// Remote magpie besides its model calls: its cards, its quota history, +// a key's limit, its root and its model list's wait. It answers only a +// client that showed a certificate st issued, with the key. +func mtlsPeer(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("x-api-key") != "remote-key" { + http.Error(w, "no key", http.StatusUnauthorized) + return + } + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case RemoteCardsPath: + json.NewEncoder(w).Encode(map[string]any{"object": "list", "data": []SubscriptionQuota{{Provider: "codex", Name: "Codex", Kind: "subscription", User: "a@x.com"}}}) + case "/v1/magpie/quotas/history": + json.NewEncoder(w).Encode(map[string]any{"object": "list", "data": []QuotaHistory{{Provider: "codex"}}}) + case RemoteKeyLimitPath: + io.WriteString(w, `{"limited":false,"key":"k"}`) + case "/v1": + io.WriteString(w, `{"name":"magpie","mcp_hub":true}`) + case "/v1/models": + w.Header().Set("ETag", `"l1"`) + io.WriteString(w, `{"object":"list","data":[{"id":"gpt-6","object":"model"}]}`) + default: + http.NotFound(w, r) + } + })) + 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 +} + +// hhdaxia on X (0.1.4258): a Remote magpie behind mTLS, with the client +// certificate set on the provider, answered its model calls, but the +// Usage page's read of its cards went without the certificate and said +// the remote "isn't shared". Every request magpie makes of a Remote +// magpie goes through the provider's transport now: the cards, the +// quota history, a key's limit, the root (its MCP router, an update) and +// the model list's wait. +func TestRemoteMagpieOwnRequestsShowClientCert(t *testing.T) { + azureHome(t) + dialsOut(t) + st := mtls.Store{Dir: t.TempDir()} + srv := mtlsPeer(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) + } + if err := Save(Provider{ID: "office", Name: "Office", Preset: RemoteMagpiePreset, Key: "remote-key", Chat: srv.URL, + ClientCert: dir + "/client.pem", ClientKey: dir + "/client-key.pem", ServerCA: dir + "/ca.pem"}); err != nil { + t.Fatal(err) + } + ForgetRemoteCardsForTest() + t.Cleanup(ForgetRemoteCardsForTest) + p, err := Find("office") + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if _, err := p.List(ctx); err != nil { + t.Fatalf("model list (the path that always had it): %v", err) + } + cs := peerCards(RemoteCards(ctx)) + if len(cs) != 1 || cs[0].Error != "" || cs[0].Provider != "office/codex" { + t.Errorf("cards: %+v", cs) + } + if hs := RemoteQuotaHistories(ctx, "7"); len(hs) != 1 { + t.Errorf("quota history: %+v", hs) + } + if _, err := askRemoteKeyLimit(ctx, *p, p.Key); err != nil { + t.Errorf("key limit: %v", err) + } + if _, err := remoteBody(ctx, *p, http.MethodGet, "/v1", RemoteHubWait); err != nil { + t.Errorf("root: %v", err) + } + if tag, err := waitRemoteList(ctx, *p, ""); err != nil || tag != `"l1"` { + t.Errorf("list wait: %q %v", tag, err) + } +} + +// A 403 is "isn't shared" only when the magpie there says so. A client +// certificate check's refusal — magpie's own, or a proxy's page in front +// of it — is said as it came, never as sharing to turn on. +func TestRemoteForbiddenSaysWhatRefused(t *testing.T) { + for name, c := range map[string]struct { + ctype, body string + shared bool + has string + }{ + "not shared (quotas)": {"application/json", `{"error":{"message":"magpie's quotas are told to another machine only when magpie is shared on the local network (Settings → Network and sharing → Share on local network) and the request carries its API key"}}`, true, ""}, + "not shared (guard)": {"text/plain", "magpie isn't shared on the local network\n", true, ""}, + "no client cert": {"text/plain", "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\n", false, "client certificate"}, + "a proxy's page": {"text/html", "403 Forbidden

403 Forbidden


nginx
", false, "client certificate"}, + "empty": {"text/plain", "", false, "403"}, + } { + t.Run(name, func(t *testing.T) { + azureHome(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", c.ctype) + w.WriteHeader(http.StatusForbidden) + io.WriteString(w, c.body) + })) + t.Cleanup(srv.Close) + p := Provider{ID: "office", Name: "Office", Preset: RemoteMagpiePreset, Key: "k", Chat: srv.URL, Anthropic: srv.URL} + for what, err := range map[string]error{ + "cards": func() error { + _, err := remoteBody(context.Background(), p, http.MethodGet, RemoteCardsPath, remoteWait) + return err + }(), + "key limit": func() error { _, err := askRemoteKeyLimit(context.Background(), p, "k"); return err }(), + } { + if err == nil { + t.Fatalf("%s: no error", what) + } + if got := err.Error() == errRemoteNotShared; got != c.shared { + t.Errorf("%s: %q, isn't shared = %v, want %v", what, err, got, c.shared) + } + if c.has != "" && !strings.Contains(err.Error(), c.has) { + t.Errorf("%s: %q, want it to say %q", what, err, c.has) + } + if errors.Is(err, errKeyHeld) { + t.Errorf("%s: held", what) + } + } + }) + } +} diff --git a/internal/provider/remote_quotas.go b/internal/provider/remote_quotas.go index 7e0a4efc9..ba9ac230e 100644 --- a/internal/provider/remote_quotas.go +++ b/internal/provider/remote_quotas.go @@ -77,6 +77,33 @@ const errRemoteNotShared = "remote magpie isn't shared; turn on Share on local n // usage on any page here, its key held to Claude's models there). const errRemoteHeld = "remote magpie tells this key none of its quotas, as it holds the key to a budget, models or accounts; on that computer, turn on Quotas for the key under Gateway keys, and let it use every model of a provider whose usage it is to see" +// remoteRefused is the error of a 403 from p that isn't a key held or +// read-only: "isn't shared" only when the magpie there says so (its +// gateway's refusal names sharing on the local network). Any other 403 — +// a client certificate the remote, or a proxy in front of it, asked for +// and didn't get (hhdaxia on X: the Usage page said "isn't shared" while +// its read went without the provider's certificate), an address not on +// its allow list — is said as the remote said it. +func remoteRefused(p Provider, res *http.Response, b []byte) error { + said := strings.TrimSpace(string(b)) + var e struct { + Error struct { + Message string `json:"message"` + } `json:"error"` + } + if json.Unmarshal(b, &e) == nil && e.Error.Message != "" { + said = e.Error.Message + } + if strings.Contains(strings.ToLower(said), "shared on the local network") { + return errors.New(errRemoteNotShared) + } + if said == "" || strings.HasPrefix(said, "<") || len(said) > 600 { + // an HTML page, most likely a proxy's + return fmt.Errorf("%s refused magpie's request (%s), not as a magpie that isn't shared would; a proxy or a client certificate check in front of it may have", remoteName(p), res.Status) + } + return fmt.Errorf("%s refused magpie's request (%s): %s", remoteName(p), res.Status, said) +} + // errRemoteKey is a remote magpie that didn't take this provider's key (401). const errRemoteKey = "remote magpie didn't take this key; use one of its enabled gateway keys" @@ -529,7 +556,9 @@ func remoteBody(ctx context.Context, p Provider, method, path string, wait time. // remoteBodyAs is remoteBody for an answer of up to max bytes, and with // noShare as the word for a remote that doesn't have the path. func remoteBodyAs(ctx context.Context, p Provider, method, path string, wait time.Duration, max int64, noShare string) ([]byte, error) { - ctx, cancel := context.WithTimeout(ctx, wait) + // through p's own transport, as its model calls go: its proxy, its + // client certificate and the server certificate it trusts + ctx, cancel := context.WithTimeout(p.Via(ctx), wait) defer cancel() req, err := http.NewRequestWithContext(ctx, method, p.Anthropic+path, nil) if err != nil { @@ -563,7 +592,7 @@ func remoteBodyAs(ctx context.Context, p Provider, method, path string, wait tim case KeyReadOnlyCode: return nil, fmt.Errorf("%s", errRemoteReadOnly) } - return nil, fmt.Errorf("%s", errRemoteNotShared) + return nil, remoteRefused(p, res, b) case res.StatusCode == http.StatusUnauthorized: return nil, fmt.Errorf("%s", errRemoteKey) case res.StatusCode < 200 || res.StatusCode >= 300: diff --git a/internal/provider/remote_quotas_test.go b/internal/provider/remote_quotas_test.go index 15da9386c..372fd0f35 100644 --- a/internal/provider/remote_quotas_test.go +++ b/internal/provider/remote_quotas_test.go @@ -67,6 +67,10 @@ func (f *fakePeer) ServeHTTP(w http.ResponseWriter, r *http.Request) { } if f.status != 0 { w.WriteHeader(f.status) + if f.status == http.StatusForbidden { + // the gateway's own word for a magpie that isn't shared + w.Write([]byte(`{"error":{"message":"magpie's quotas are told to another machine only when magpie is shared on the local network (Settings → Network and sharing → Share on local network) and the request carries its API key"}}`)) + } return } if f.held {