diff --git a/docs/integrating.md b/docs/integrating.md index 2a67ce491..f2405103c 100644 --- a/docs/integrating.md +++ b/docs/integrating.md @@ -72,12 +72,16 @@ Volcengine Ark's `content` (reference video and audio, `draft_task`), `ratio`, `resolution`, `duration: -1`, `tools`, `watermark`, `sequential_image_generation` and the rest. A video's answer carries Ark's own fields too (`content.last_frame_url`, `usage`, `resolution`). -For the rest of Ark's API (an image stream, the task list, cancelling a -task) use `/v1/magpie/native//`: `POST -images/generations`, `POST` or `GET contents/generations/tasks`, `GET` or -`DELETE contents/generations/tasks/`, sent and answered in Ark's own -shape on the user's Ark key. It takes the same gateway key as every route, -and a key held to models, accounts or a budget is refused it. +For the rest of a vendor's API use +`/v1/magpie/native//`: GET, POST, PUT, PATCH or DELETE, +with `` joined to the provider's host (not its base URL), sent and +answered in the vendor's own shape on the user's key for that provider, +a stream as it comes. So Ark's task list is `GET +/v1/magpie/native/ark/api/v3/contents/generations/tasks`. It serves a +provider added with an API key, not a subscription or sign-in. Ark's +short paths (`images/generations`, `contents/generations/tasks[/]`) +still work under the key's base. It takes the same gateway key as every +route, and a key held to models, accounts or a budget is refused it. **Optional.** Send `X-Magpie-Session: ` with a conversation's requests and `GET /v1/magpie/route?session=` says which model a routing group diff --git a/docs/reference.md b/docs/reference.md index 8f088c976..c9dcd98cc 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -2209,6 +2209,7 @@ It exposes: | `/api/version`, `/api/tags`, `/api/show` | the catalog as an Ollama server lists it, for a client that takes a custom endpoint only as Ollama (below) | | `/mcp/magpie/hub` | MCP (Streamable HTTP): every MCP server in the Library, as one server, for any app, while *Library → MCP → MCP router* is on | | `/mcp/magpie/hub/{agent}` | MCP (Streamable HTTP): the Library's MCP servers ticked for that agent, as one server, while *Library → MCP → MCP router* is on | +| `/v1/magpie/native/{provider}/{path}` | a provider's own API, as it is (GET, POST, PUT, PATCH, DELETE; below) | With that switch on, each agent that takes an MCP server over HTTP is given one entry, `magpie`, in place of the Library's servers, and magpie @@ -2223,6 +2224,27 @@ each server's own entry again. It is guarded as the gateway is: a local request, or one with a gateway key, and no other web page ([MCP router](subsystems/mcp-router.md)). +`/v1/magpie/native//` reaches a provider's own API +through magpie, for what the OpenAI shape doesn't carry. `` is +the provider's id; `` is joined to its host, not to its base URL, +so `/v1/magpie/native/ark/api/v3/contents/generations/tasks` asks +`https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks`. +GET, POST, PUT, PATCH and DELETE are passed on with the query and body as +sent, and the answer comes back as it came, a stream as it arrives. +magpie signs it with the provider's key, the way that provider takes one; +the caller's own `Authorization`, `x-api-key`, `x-goog-api-key`, cookies +and `?key=` never go on. It serves a provider added with an API key (a +vendor's or your own), not a subscription, a sign-in or a plugin's +account. A path with a `.` or `..` segment (encoded too), a backslash, a +leading or encoded slash, or a scheme is refused. It takes the gateway key +every route does, and a key held to models, accounts or a spend limit is +refused it. With Settings › Privacy masking on, a JSON body is masked and +put back in the answer, and a body that isn't JSON is refused. Each +request is a Requests row and a usage record, with tokens when the +answer reports them. Ark's short paths (`images/generations`, +`contents/generations/tasks[/]`) still go under the key's base as +before. + Each `/v1/models` entry includes `reasoning` and `supported_reasoning_levels` (`[{"effort":"low"}, ...]`), and the same levels as plain names in `reasoning_levels` (`["low", ...]`, `[]` when there are none), which diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 3500e2469..474829d40 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -703,7 +703,7 @@ the MCP and an HTTP caller go through one translation and one set of holds. | `POST /v1/videos` | JSON or OpenAI's multipart: `model`, `prompt`, `seconds`, `size`, `input_reference` (first frame), plus `last_frame` and `reference_images` | OpenAI's video object, `status: "queued"`, an id that names the provider, the vendor's task and the key or account | | `GET /v1/videos/{id}` | | the video object: `queued`, `in_progress` (`progress`), `completed` or `failed` (`error`) | | `GET /v1/videos/{id}/content` | | the video (`video/mp4`, or `video/quicktime` for a MOV: `videoType`), or 409 while it isn't made | -| `POST`, `GET`, `DELETE /v1/magpie/native/{provider}/{path...}` | the vendor's own request | the vendor's own answer, a stream as it comes (`native.go`, below) | +| `GET`, `POST`, `PUT`, `PATCH`, `DELETE /v1/magpie/native/{provider}/{path...}` | the vendor's own request | the vendor's own answer, a stream as it comes (`native.go`, below) | Each vendor is sent its own request: @@ -804,24 +804,61 @@ it; anything else asks for `b64_json`. `TestArkImagesPassOnTheirOwnFields`. `/v1/magpie/native/{provider}/{path...}` ([`native.go`](../../internal/gateway/native.go)) passes a request to the provider's own API as it is, and its answer back -as it came, an event stream flushed as it arrives: for what the OpenAI -shape can't carry (Ark's image stream, its task list and cancel, a field -newer than magpie). It is served for Volcengine Ark only (`isArk`, not a -remote magpie), at `images/generations` (POST), -`contents/generations/tasks` (POST, GET with Ark's query) and -`contents/generations/tasks/` (GET, DELETE) under the key's base -(`nativeArkPath`); any other provider or path is a 404 that says what is -served. It is behind the gateway's guards as every route is (a key beyond -loopback, corsGuard, the key's rate), refused to a read-only key -(`readOnlyRefused`), and refused (403, `nativeHeld`) to a key held to -models, accounts or a spend limit, or issued by one: magpie can't tell -which model a poll or a cancel is of, and prices no answer it doesn't -read, so the OpenAI routes serve such a key. A model the user switched off -is refused. The body's strings are masked (fails closed) and put back in -the answer (`restoring`), numbers kept exact (`UseNumber`). It is signed -with the provider's key and magpie's User-Agent, never the caller's -headers, and each request is a Requests row and a usage record -(`Operation: "native"`, no tokens). `TestNativeArkRoute`, `TestNativeArkStreamsAsItComes`. +as it came, an event stream flushed as it arrives and a large answer +copied through, never held whole (axelburks on Discord): for what the +OpenAI shape can't carry. GET, POST, PUT, PATCH and DELETE +(`nativeMethods`) are routed. + +- **Which providers.** One reached with an API key (`nativeKeyed`: no + `Account`, a `Key`, not a remote magpie, not Vertex AI): a vendor's or + the user's own. A subscription's, a sign-in's or a plugin's account is + a 403 that says so; an unknown, off or decide-only provider a 404. +- **Where.** The path after the provider, as the caller escaped it, is + joined to the host of the provider's first base (`nativeProto`: Chat, + Responses, Anthropic, Gemini), not to the base's path, so a vendor's v2 + paths are reached too (`nativeTarget`). It refuses (400) an empty path, + a `.` or `..` segment (`%2e%2e` and across `%2F` too), a backslash, a + leading or encoded leading slash, `://`, a first segment that reads as + a scheme, and any URL whose host or scheme, parsed back, isn't the + base's. The mux redirects an unencoded `..` before the route sees it. +- **Headers.** The caller's auth (`Authorization`, `Proxy-Authorization`, + `x-api-key`, `api-key`, `x-goog-api-key`, `Cookie`), the browser's and + a proxy's (`Origin`, `Referer`, `Sec-*`, `X-Forwarded-*`, `Forwarded`, + `Cf-*`), the hop's own and `X-Magpie-*` are dropped (`nativeDropped`), + the gateway key's `?key=` too (`nativeQuery`); the rest go as they came. + `Sign` puts in the provider's key as it takes one, and magpie's + User-Agent goes in (`stampUA`). The answer's hop headers, `Set-Cookie`, + `Alt-Svc` and HSTS don't come back (`nativeAnswerDropped`). +- **Keys.** It is behind the gateway's guards as every route is (a key + beyond loopback, lanGuard's Host check against a rebound page, + corsGuard: a foreign Origin, `null` and `*.localhost` without a key, + the key's rate), refused to a read-only key (`readOnlyRefused`), and + refused (403, `nativeHeld`) to a key held to models, accounts or a + spend limit, or issued by one: magpie can't tie a path it doesn't read + to a model, and prices no answer it doesn't read, so the OpenAI routes + serve such a key. A model the user switched off, named in a JSON body's + `model`, is refused. +- **Masking.** With Settings › Privacy masking and a provider not set to + go unmasked, the body is decoded as JSON (numbers exact, `UseNumber`) + and its strings masked (fails closed); a body that isn't JSON is a 415, + as nothing unmasked may go. Only a request something was masked in has + its answer read through `restoring`, which holds a JSON answer whole to + put the values back; every other answer streams through. +- **Record.** Each request is a Requests row and a usage record + (`Operation: "native"`), with the tokens a JSON or event-stream answer + reports (`usageSniffer`, read as the path's protocol, `nativeSniffed`), + none otherwise. + +Ark's images and video tasks at their short paths under the key's base +(`nativeArkPath`: `images/generations` POST, `contents/generations/tasks` +POST and GET, `contents/generations/tasks/` GET and DELETE) are served +as they were first (`nativeArk`): the body must be a JSON object, it is +re-encoded after masking, and only `Content-Type` and `Accept` go on. +`TestNativeArkRoute`, `TestNativeArkStreamsAsItComes`, +`TestNativeAnyForwardsAtTheHost`, `TestNativeAnyRecordsUsage`, +`TestNativeAnyRefusals`, `TestNativeAnyStaysOnTheHost`, +`TestNativeAnyRefusesPagesWithoutAKey`, `TestNativeAnyMasks`, +`TestNativeAnyStreamsAsItComes`, `TestNativeAnyArkHost`. A MiniMax API key (no account, a Chat, Anthropic or Responses base on api.minimax.io, api.minimaxi.com or api.minimax.cn: `filmsMiniMax`, diff --git a/internal/gateway/ark_native_test.go b/internal/gateway/ark_native_test.go index 63e9931ee..7d880467f 100644 --- a/internal/gateway/ark_native_test.go +++ b/internal/gateway/ark_native_test.go @@ -47,8 +47,8 @@ func newArkNative(t *testing.T) *arkNative { func arkNativeMux(s *Server) *http.ServeMux { mux := http.NewServeMux() - for _, m := range []string{"POST ", "GET ", "DELETE "} { - mux.HandleFunc(m+NativePath+"{provider}/{path...}", s.native) + for _, m := range nativeMethods { + mux.HandleFunc(m+" "+NativePath+"{provider}/{path...}", s.native) } return mux } @@ -63,8 +63,9 @@ func arkNativeAsk(t *testing.T, h http.Handler, who access.Identity, method, pat } // The native route passes Ark's own images and video tasks on, signed -// with the provider's key, its stream as it comes; nothing else of -// Ark's, and no key held to models, accounts or a limit. +// with the provider's key, its stream as it comes, and no key held to +// models, accounts or a limit. Ark's other paths are the generic route's +// (native_any_test.go). func TestNativeArkRoute(t *testing.T) { fresh(t) up := newArkNative(t) @@ -109,10 +110,6 @@ func TestNativeArkRoute(t *testing.T) { method, path string code int }{ - {free, "POST", NativePath + "ark/chat/completions", 404}, - {free, "GET", NativePath + "ark/images/generations", 404}, - {free, "GET", NativePath + "ark/contents/generations/tasks/a/b", 404}, - {free, "POST", NativePath + "other/images/generations", 404}, {free, "POST", NativePath + "nobody/images/generations", 404}, {access.Identity{KeyName: "held", Models: []string{"ark/doubao-seedream-4-5-251128"}}, "POST", NativePath + "ark/images/generations", 403}, {access.Identity{KeyName: "held", Accounts: []string{"ark"}}, "POST", NativePath + "ark/images/generations", 403}, diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b0e876a6d..5058b20a4 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1024,10 +1024,10 @@ func (s *Server) routes() *routeMux { mux.HandleFunc("GET /videos/{id}", s.videosGet) mux.HandleFunc("GET /v1/videos/{id}/content", s.videosContent) mux.HandleFunc("GET /videos/{id}/content", s.videosContent) - // a provider's own images and video API, as it is (native.go) - mux.HandleFunc("POST "+NativePath+"{provider}/{path...}", s.native) - mux.HandleFunc("GET "+NativePath+"{provider}/{path...}", s.native) - mux.HandleFunc("DELETE "+NativePath+"{provider}/{path...}", s.native) + // a provider's own API, as it is, at its host (native.go) + for _, m := range nativeMethods { + mux.HandleFunc(m+" "+NativePath+"{provider}/{path...}", s.native) + } mux.HandleFunc("POST "+claudeMCPPath+"{token}", s.subscription.mcpCall) mux.HandleFunc("/mcp/{name}", s.mcpProxy) mux.HandleFunc("/mcp/run/{name}", runMCP) diff --git a/internal/gateway/native.go b/internal/gateway/native.go index 35b5c9416..9a2901569 100644 --- a/internal/gateway/native.go +++ b/internal/gateway/native.go @@ -3,40 +3,50 @@ package gateway // The native route: a provider's own API, reached through magpie // (axelburks on Discord). /v1/images/generations and /v1/videos take // OpenAI's shape and pass on the vendor fields they don't read, but a -// vendor's API grows faster than magpie maps it: Ark's image streams, its -// task list and cancel, a field of a new model. A caller who wants all of +// vendor's API grows faster than magpie maps it. A caller who wants all of // it asks // -// POST /v1/magpie/native// +// /v1/magpie/native// // -// and gets the vendor's answer as it came, its stream too. What it keeps -// of the gateway: +// and magpie sends it to the provider's host, at / as the caller +// wrote it (not under the configured base's /v1 or /api/v3: a vendor's +// API has v2 paths too), the body and query as they came, signed with +// the provider's key; the answer comes back as it came, a stream as it +// arrives. So magpie relays every API a key of the user's reaches without +// handing the key out. What it keeps of the gateway: // // - the gateway's own guards first, as every route (a key from beyond -// loopback, a read-only key refused, corsGuard, the key's rate); -// - a key held to models, accounts or a spend limit is refused: the -// route can't say which model a task's poll or cancel is of, and -// magpie prices no answer it doesn't read, so it can't hold such a key -// to them. Such a key uses the OpenAI routes; -// - only paths the vendor makes images and videos at (nativePaths), on -// the methods the vendor takes there: never its chat, whose routing, -// usage and masking are the chat routes'; -// - the body's text masked as a video's fields are (maskStrings, fails -// closed), and put back in the answer; -// - the provider's first key signs it, the user's key never seen by the -// caller; a model the user turned off is refused; -// - each request is in the Requests log and in usage, untimed and -// uncounted in tokens, as a video's start is. +// loopback, corsGuard's Origin checks, lanGuard's Host check, a +// read-only key refused, the key's rate); +// - a key held to models, accounts or a spend limit is refused: a path +// magpie doesn't read can't be tied to a model, and magpie prices no +// answer it doesn't read, so it can't hold such a key to them. Such a +// key uses the OpenAI routes; +// - an API key's provider only (nativeKeyed): a vendor's or the user's +// own, never a subscription's, an OAuth sign-in's or a plugin's, whose +// tokens aren't API keys and whose vendors don't take their own API +// asked with them; +// - a path that stays on the provider's host (nativeTarget): no "." or +// ".." segment, encoded or not, no scheme, no second host; +// - the caller's own auth headers (and its gateway key in ?key=) never +// go on; the provider's key goes in as the provider takes it (Sign); +// - with Settings › Privacy masking, a JSON body's strings are masked +// (fails closed; another body is refused) and put back in the answer; +// - each request is a Requests row and a usage record, with the tokens +// its answer says when it says them (usageSniffer). // -// Only Volcengine Ark is served so far: the one asked for, and the one -// whose API magpie's own routes read. Another provider is told so. +// Ark's images and video tasks at their short paths under the key's base +// (nativeArkPath) are served as they were first (nativeArk). import ( "bytes" "cmp" "encoding/json" + "errors" "fmt" "net/http" + "net/url" + "regexp" "strings" "time" @@ -48,6 +58,9 @@ import ( // NativePath is where a provider's own API is reached. const NativePath = "/v1/magpie/native/" +// nativeMethods are the methods the native route takes. +var nativeMethods = []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete} + // nativePaths are the paths under an Ark key's base (/api/v3) the native // route passes on, and their methods: images, and video tasks (create, // list, get, cancel or delete). @@ -77,12 +90,12 @@ func (s *Server) native(w http.ResponseWriter, r *http.Request) { start := time.Now() id, path := r.PathValue("provider"), r.PathValue("path") who := callerOf(r) - call := Call{Time: start, From: provider.Chat, Agent: who.agent, Via: who.via, Provider: id, headers: headerLogOf(r.Context())} + call := &Call{Time: start, From: provider.Chat, Agent: who.agent, Via: who.via, Provider: id, headers: headerLogOf(r.Context())} usage.Saw(agentOf(r)) fail := func(code int, msg string) { call.Status, call.Error, call.Millis = code, msg, time.Since(start).Milliseconds() writeError(w, provider.Chat, code, msg) - s.record(call) + s.record(*call) } if k := access.Caller(r.Context()); nativeHeld(k) { fail(http.StatusForbidden, fmt.Sprintf("The gateway key %q is held to some models, accounts or a spend limit, which magpie can't hold a vendor's own API to: use /v1/images/generations and /v1/videos, which pass on the vendor's own fields too", k.KeyName)) @@ -94,14 +107,17 @@ func (s *Server) native(w http.ResponseWriter, r *http.Request) { return } p := *found - if p.IsRemoteMagpie() || !isArk(p) { - fail(http.StatusNotFound, fmt.Sprintf("%s's own API isn't passed on: magpie passes on Volcengine Ark's (a provider at ark..volces.com) so far. Use /v1/images/generations and /v1/videos", p.Name)) - return - } - if !nativeArkPath(r.Method, path) { - fail(http.StatusNotFound, fmt.Sprintf("magpie passes on Ark's images and video tasks: POST images/generations, POST or GET contents/generations/tasks, GET or DELETE contents/generations/tasks/; not %s %s", r.Method, path)) + if !p.IsRemoteMagpie() && isArk(p) && nativeArkPath(r.Method, path) { + s.nativeArk(w, r, p, call, fail) return } + s.nativeAny(w, r, p, call, fail) +} + +// nativeArk is Ark's images and video tasks at their short paths, joined +// to the key's base (/api/v3), as the route first served them. +func (s *Server) nativeArk(w http.ResponseWriter, r *http.Request, p provider.Provider, call *Call, fail func(int, string)) { + start, path := call.Time, r.PathValue("path") var body []byte if r.Method == http.MethodPost { in, admitted := s.requestBody(w, r, provider.Chat) @@ -170,7 +186,7 @@ func (s *Server) native(w http.ResponseWriter, r *http.Request) { if res.StatusCode >= 400 { call.Error = fmt.Sprintf("%s answered %d", p.Name, res.StatusCode) } - s.record(call) + s.record(*call) appendUsage(r, usage.Record{Operation: "native", Time: start, Agent: call.Agent, Via: call.Via, Provider: p.ID, Host: p.Where(), Model: call.Model, Requested: call.Model, ProviderAccount: accountOf(p), Millis: call.Millis, Status: call.Status, Session: sessionOf(r.Header)}) for _, k := range []string{"Content-Type", "Cache-Control", "X-Request-Id"} { @@ -195,3 +211,263 @@ func (s *Server) native(w http.ResponseWriter, r *http.Request) { } } } + +// nativeKeyed: p is reached with an API key of the user's, a vendor's or +// their own provider's: no subscription, OAuth sign-in or plugin account +// (Account), no Vertex AI (a Google token, not a key) and no remote +// magpie (its key is a gateway key, and its own routes are magpie's). +func nativeKeyed(p provider.Provider) bool { + return p.Account == nil && p.Key != "" && !p.IsRemoteMagpie() && !p.IsVertex() +} + +// nativeProto is the protocol whose base names p's host and whose +// signing p's key is sent with: OpenAI's (Chat or Responses) where p +// speaks it, else Anthropic's, else Gemini's. +func nativeProto(p provider.Provider) provider.Protocol { + for _, pr := range []provider.Protocol{provider.Chat, provider.Responses, provider.Anthropic, provider.Gemini} { + if p.Base(pr) != "" { + return pr + } + } + return provider.Chat +} + +// schemeLike is a first segment that reads as a URL's scheme ("http:", +// "javascript:x"). +var schemeLike = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9+.-]*:`) + +// nativeTarget is raw, the path after the provider as the caller escaped +// it, at base's host: scheme and host from base, nothing of base's path. +// It refuses what could leave the host or climb out of the path: an +// empty path, a "." or ".." segment (encoded too, %2e%2e, and across an +// encoded slash), a backslash, a second leading slash, a scheme or "://". +func nativeTarget(base, raw, query string) (*url.URL, error) { + b, err := url.Parse(base) + if err != nil || b.Host == "" || (b.Scheme != "http" && b.Scheme != "https") { + return nil, fmt.Errorf("the provider's base URL %q names no host", base) + } + path, err := url.PathUnescape(raw) + if err != nil { + return nil, fmt.Errorf("the path isn't escaped right: %v", err) + } + if path == "" || strings.HasPrefix(path, "/") || strings.ContainsAny(path, "\\\x00") || strings.Contains(path, "://") { + return nil, errors.New("the path is the provider's own, after its host: one that is empty, starts with a slash, holds a backslash or names a URL is refused") + } + segs := strings.Split(path, "/") + if schemeLike.MatchString(segs[0]) { + return nil, errors.New("the path is the provider's own, after its host: an absolute URL is refused") + } + for _, seg := range segs { + if seg == "." || seg == ".." { + return nil, errors.New(`the path is the provider's own, after its host: a "." or ".." segment is refused`) + } + } + u := &url.URL{Scheme: b.Scheme, Host: b.Host, Path: "/" + path, RawPath: "/" + raw, RawQuery: query} + // the URL as it goes out names base's host, whatever the path held + if back, err := url.Parse(u.String()); err != nil || back.Host != b.Host || back.Scheme != b.Scheme { + return nil, errors.New("the path is the provider's own, after its host: it named another") + } + return u, nil +} + +// nativeQuery is the caller's query without its gateway key (?key=, +// which callerKeys reads), as it came otherwise. +func nativeQuery(raw string) string { + if raw == "" || !strings.Contains(raw, "key=") { + return raw + } + var kept []string + for _, kv := range strings.Split(raw, "&") { + name, _, _ := strings.Cut(kv, "=") + if n, err := url.QueryUnescape(name); err == nil && n == "key" { + continue + } + kept = append(kept, kv) + } + return strings.Join(kept, "&") +} + +// nativeDropped are the caller's headers that never go to the vendor: +// its auth (a gateway key in any place callerKeys reads one, and any +// other credential), the browser's and a proxy's, the hop's own, and +// magpie's. The rest go as they came. +var nativeDropped = map[string]bool{ + "Authorization": true, "Proxy-Authorization": true, "X-Api-Key": true, "Api-Key": true, "X-Goog-Api-Key": true, "Cookie": true, + "Host": true, "Origin": true, "Referer": true, "Forwarded": true, "X-Real-Ip": true, "Via": true, + "Connection": true, "Proxy-Connection": true, "Keep-Alive": true, "Te": true, "Trailer": true, "Transfer-Encoding": true, "Upgrade": true, + "Content-Length": true, "Accept-Encoding": true, "User-Agent": true, +} + +func nativeHeaderDropped(k string) bool { + k = http.CanonicalHeaderKey(k) + return nativeDropped[k] || strings.HasPrefix(k, "X-Forwarded-") || strings.HasPrefix(k, "X-Magpie-") || + strings.HasPrefix(k, "Sec-") || strings.HasPrefix(k, "Cf-") +} + +// nativeAnswerDropped are the vendor's answer headers that don't come +// back: the hop's own, its cookies, and what is about its own host. +var nativeAnswerDropped = map[string]bool{ + "Connection": true, "Keep-Alive": true, "Te": true, "Trailer": true, "Transfer-Encoding": true, "Upgrade": true, "Proxy-Authenticate": true, + "Set-Cookie": true, "Alt-Svc": true, "Strict-Transport-Security": true, +} + +// nativeSniffed is the protocol a reply at path is read for usage as. +func nativeSniffed(proto provider.Protocol, path string) provider.Protocol { + switch { + case strings.HasSuffix(path, "/responses") || path == "responses": + return provider.Responses + case strings.HasSuffix(path, "/messages") || path == "messages": + return provider.Anthropic + case strings.Contains(path, ":generateContent") || strings.Contains(path, ":streamGenerateContent"): + return provider.Gemini + case proto == provider.Anthropic || proto == provider.Gemini: + return proto + } + return provider.Chat +} + +// nativeAny passes any request of the caller's to p's own API, at p's +// host (nativeTarget), as it came. +func (s *Server) nativeAny(w http.ResponseWriter, r *http.Request, p provider.Provider, call *Call, fail func(int, string)) { + start := call.Time + if !nativeKeyed(p) { + fail(http.StatusForbidden, fmt.Sprintf("%s isn't reached with an API key, so its own API isn't passed on: the native route serves a provider added with a key (a vendor's or your own), never a subscription's, a sign-in's or a plugin's account", p.Name)) + return + } + proto := nativeProto(p) + call.To = proto + // the path after the provider, as the caller escaped it + rest := strings.TrimPrefix(r.URL.EscapedPath(), NativePath) + _, raw, _ := strings.Cut(rest, "/") + at, err := nativeTarget(p.Base(proto), raw, nativeQuery(r.URL.RawQuery)) + if err != nil { + fail(http.StatusBadRequest, err.Error()) + return + } + var body []byte + masked := false + if r.Method != http.MethodGet { + in, admitted := s.requestBody(w, r, provider.Chat) + if !admitted { + return + } + body = in + } + if len(body) > 0 { + trimmed := bytes.TrimSpace(body) + // the model, read where a JSON body names one, for a model the + // user turned off and the record + if len(trimmed) > 0 && trimmed[0] == '{' && len(trimmed) <= 32<<20 { + var m struct { + Model any `json:"model"` + } + if json.Unmarshal(trimmed, &m) == nil { + call.Model, _ = m.Model.(string) + } + } + if msg, off := modelOff(p, call.Model, p.ID+"/"+call.Model); call.Model != "" && off { + fail(http.StatusForbidden, msg) + return + } + if redactionWanted() && !p.SkipsRedaction() { + var v any + dec := json.NewDecoder(bytes.NewReader(body)) + dec.UseNumber() // a seed or an id goes as it came + if err := dec.Decode(&v); err != nil || dec.More() { + fail(http.StatusUnsupportedMediaType, "Settings › Privacy masks what goes to a vendor, and magpie masks a JSON body only: this one isn't JSON, so nothing was sent. Send JSON, or set this provider to go unmasked") + return + } + // the value inside a list, so a lone string is masked as well + box := []any{v} + var hits maskHits + if err := maskStrings(r.Context(), box, &hits); err != nil { // fails closed + fail(maskStatus(err), err.Error()) + return + } + if hits.n > 0 { + v = box[0] + var b bytes.Buffer + enc := json.NewEncoder(&b) + enc.SetEscapeHTML(false) + if err := enc.Encode(v); err != nil { + fail(http.StatusBadRequest, err.Error()) + return + } + body, masked = bytes.TrimSuffix(b.Bytes(), []byte("\n")), true + noteMasked(r, "native", hits, string(body), 0, p.ID, call.Model) + } + } + } + if masked { + var done func() + w, done = restoring(w) + defer done() + } + ctx := s.metered(p.Via(r.Context()), p, "") + req, err := http.NewRequestWithContext(ctx, r.Method, at.String(), bytes.NewReader(body)) + if err != nil { + fail(http.StatusBadGateway, err.Error()) + return + } + for k, vs := range r.Header { + if !nativeHeaderDropped(k) { + req.Header[k] = append([]string(nil), vs...) + } + } + stampUA(ctx, p, req.Header) + if err := p.Sign(ctx, req, proto, body); err != nil { + fail(http.StatusBadGateway, err.Error()) + return + } + res, err := p.Do(s.client, req) + if err != nil { + fail(http.StatusBadGateway, fmt.Sprintf("%s didn't answer: %v", p.Name, err)) + return + } + defer res.Body.Close() + ct := res.Header.Get("Content-Type") + var sn *usageSniffer + if strings.Contains(ct, "json") || strings.HasPrefix(ct, "text/event-stream") { + sn = newSniffer(nativeSniffed(proto, at.Path), ct) + } + for k, vs := range res.Header { + if nativeAnswerDropped[http.CanonicalHeaderKey(k)] || (res.Uncompressed && (k == "Content-Length" || k == "Content-Encoding")) { + continue + } + w.Header()[k] = append([]string(nil), vs...) + } + w.WriteHeader(res.StatusCode) + // as it comes, never held whole: a stream flushed as it arrives, a + // large file copied through + rc := http.NewResponseController(w) + buf := make([]byte, 32<<10) + for { + n, err := res.Body.Read(buf) + if n > 0 { + if sn != nil { + sn.write(buf[:n]) + } + if _, werr := w.Write(buf[:n]); werr != nil { + break + } + rc.Flush() + } + if err != nil { // io.EOF, or the vendor gone + break + } + } + call.Status, call.Millis = res.StatusCode, time.Since(start).Milliseconds() + if res.StatusCode >= 400 { + call.Error = fmt.Sprintf("%s answered %d", p.Name, res.StatusCode) + } + var u Usage + if sn != nil && res.StatusCode < 400 { + u = sn.usage() + } + call.Usage = u + s.record(*call) + appendUsage(r, usage.Record{Operation: "native", Time: start, Agent: call.Agent, Via: call.Via, Provider: p.ID, Host: p.Where(), Model: call.Model, Requested: call.Model, Served: u.Served, Upstream: u.Upstream, + ProviderKeyID: provider.KeyID(p.Key), ProviderKeyName: p.KeyName, + Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, CacheWrite1h: u.CacheWrite1h, Reasoning: u.Reasoning, + Millis: call.Millis, Status: call.Status, Session: sessionOf(r.Header)}) +} diff --git a/internal/gateway/native_any_test.go b/internal/gateway/native_any_test.go new file mode 100644 index 000000000..9eb112a3f --- /dev/null +++ b/internal/gateway/native_any_test.go @@ -0,0 +1,439 @@ +package gateway + +import ( + "bufio" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/usage" +) + +// vendorSeen is one request a vendor's API was sent. +type vendorSeen struct { + method, uri string + header http.Header + body string +} + +// vendorAPI is a vendor's own API on a test server: it records each +// request and answers JSON, or what answer says for the path. +type vendorAPI struct { + *httptest.Server + mu sync.Mutex + seen []vendorSeen + answer func(w http.ResponseWriter, r *http.Request, body []byte) bool +} + +func newVendorAPI(t *testing.T) *vendorAPI { + t.Helper() + v := &vendorAPI{} + v.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + v.mu.Lock() + v.seen = append(v.seen, vendorSeen{r.Method, r.URL.RequestURI(), r.Header.Clone(), string(body)}) + answer := v.answer + v.mu.Unlock() + if answer != nil && answer(w, r, body) { + return + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("X-Vendor", "yes") + w.Header().Set("Set-Cookie", "vendor=1") + w.WriteHeader(201) + io.WriteString(w, `{"echo":`+strconvQuote(string(body))+`}`) + })) + t.Cleanup(v.Close) + return v +} + +func (v *vendorAPI) asked() []vendorSeen { + v.mu.Lock() + defer v.mu.Unlock() + return append([]vendorSeen(nil), v.seen...) +} + +// nativeServe is the gateway as it listens: lanGuard, then every guard +// Handler puts before a route. +func nativeServe(t *testing.T) http.Handler { + t.Helper() + return lanGuard(New().Handler()) +} + +func nativeDo(h http.Handler, method, target, remote, body string, hdr ...string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, target, strings.NewReader(body)) + req.RemoteAddr = remote + for i := 0; i+1 < len(hdr); i += 2 { + req.Header.Add(hdr[i], hdr[i+1]) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec +} + +func saveVendor(t *testing.T, p provider.Provider) { + t.Helper() + if err := provider.Save(p); err != nil { + t.Fatal(err) + } +} + +// Every method reaches the vendor at its host, at the path the caller +// wrote (not under the base's /v1), with the query and body as they +// came, signed with the provider's key the way it takes one; the +// caller's own credentials, its gateway ?key= and the browser's headers +// never go on, and the answer comes back with the vendor's status and +// headers, its cookies left out. +func TestNativeAnyForwardsAtTheHost(t *testing.T) { + fresh(t) + up := newVendorAPI(t) + saveVendor(t, provider.Provider{ID: "vendor", Name: "Vendor", Chat: up.URL + "/v1", Key: "vk", Models: []string{"m"}}) + saveVendor(t, provider.Provider{ID: "claudeish", Name: "Claudeish", Anthropic: up.URL + "/anthropic", Key: "ak", Models: []string{"c"}}) + h := nativeServe(t) + body := `{"model":"m","seed":12345678901234567,"x":[1,2.50,"é<>&"]}` + for _, m := range nativeMethods { + b := body + if m == http.MethodGet { + b = "" + } + rec := nativeDo(h, m, "http://127.0.0.1:3425"+NativePath+"vendor/v2/files/f-1?y=1&key=gw-secret&z=%2F", "127.0.0.1:50000", b, + "Authorization", "Bearer caller-secret", "X-Api-Key", "caller-x", "Cookie", "c=1", "X-Custom", "kept", "Content-Type", "application/json") + if rec.Code != 201 || rec.Header().Get("X-Vendor") != "yes" || rec.Header().Get("Set-Cookie") != "" { + t.Fatalf("%s: %d %v %s", m, rec.Code, rec.Header(), rec.Body) + } + } + seen := up.asked() + if len(seen) != len(nativeMethods) { + t.Fatalf("vendor asked %d times: %+v", len(seen), seen) + } + for i, s := range seen { + m := nativeMethods[i] + want := body + if m == http.MethodGet { + want = "" + } + if s.method != m || s.uri != "/v2/files/f-1?y=1&z=%2F" || s.body != want { + t.Errorf("%s: vendor got %s %s %q", m, s.method, s.uri, s.body) + } + if s.header.Get("Authorization") != "Bearer vk" || s.header.Get("X-Api-Key") != "" || s.header.Get("Cookie") != "" || + s.header.Get("X-Custom") != "kept" || strings.Contains(strings.Join(flatHeader(s.header), "\n"), "caller") { + t.Errorf("%s: vendor's headers %v", m, s.header) + } + } + + rec := nativeDo(h, "POST", "http://127.0.0.1:3425"+NativePath+"claudeish/v1/messages/count_tokens", "127.0.0.1:50000", `{"model":"c"}`, "Authorization", "Bearer caller-secret") + seen = up.asked() + last := seen[len(seen)-1] + if rec.Code != 201 || last.uri != "/v1/messages/count_tokens" || last.header.Get("X-Api-Key") != "ak" || strings.Contains(strings.Join(flatHeader(last.header), "\n"), "caller") { + t.Fatalf("anthropic: %d %+v", rec.Code, last) + } +} + +func flatHeader(h http.Header) []string { + var out []string + for k, vs := range h { + out = append(out, k+": "+strings.Join(vs, ",")) + } + return out +} + +// What a request costs is on record: a usage record for each, with the +// tokens the answer says (a stream's last event here) and none when it +// says none. +func TestNativeAnyRecordsUsage(t *testing.T) { + fresh(t) + up := newVendorAPI(t) + up.answer = func(w http.ResponseWriter, r *http.Request, body []byte) bool { + if r.URL.Path != "/v1/chat/completions" { + return false + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, `data: {"id":"1","model":"m-2","choices":[{"delta":{"content":"hi"}}]}`+"\n\n") + io.WriteString(w, `data: {"id":"1","model":"m-2","choices":[],"usage":{"prompt_tokens":7,"completion_tokens":3,"total_tokens":10}}`+"\n\n") + io.WriteString(w, "data: [DONE]\n\n") + return true + } + saveVendor(t, provider.Provider{ID: "vendor", Name: "Vendor", Chat: up.URL + "/v1", Key: "vk", Models: []string{"m"}}) + h := nativeServe(t) + if rec := nativeDo(h, "GET", "http://127.0.0.1:3425"+NativePath+"vendor/v1/models", "127.0.0.1:50000", ""); rec.Code != 201 { + t.Fatalf("models: %d %s", rec.Code, rec.Body) + } + if rec := nativeDo(h, "POST", "http://127.0.0.1:3425"+NativePath+"vendor/v1/chat/completions", "127.0.0.1:50000", `{"model":"m","stream":true}`); rec.Code != 200 || !strings.Contains(rec.Body.String(), "[DONE]") { + t.Fatalf("chat: %d %s", rec.Code, rec.Body) + } + var recs []usage.Record + for i := 0; i < 100; i++ { + if recs = usage.Load(time.Time{}); len(recs) >= 2 { + break + } + time.Sleep(20 * time.Millisecond) + } + var plain, chat *usage.Record + for i := range recs { + switch { + case recs[i].Operation == "native" && recs[i].Status == 201: + plain = &recs[i] + case recs[i].Operation == "native" && recs[i].Status == 200: + chat = &recs[i] + } + } + if plain == nil || plain.Provider != "vendor" || plain.Input != 0 || plain.Output != 0 { + t.Fatalf("models record %+v in %+v", plain, recs) + } + if chat == nil || chat.Model != "m" || chat.Input != 7 || chat.Output != 3 || chat.ProviderKeyID != provider.KeyID("vk") { + t.Fatalf("chat record %+v in %+v", chat, recs) + } +} + +// Only a provider reached with an API key is served: a subscription's +// or a sign-in's account, a remote magpie's gateway key, or no key at +// all never; a key held to models, accounts or a limit not on any path. +func TestNativeAnyRefusals(t *testing.T) { + fresh(t) + up := newVendorAPI(t) + saveVendor(t, provider.Provider{ID: "vendor", Name: "Vendor", Chat: up.URL + "/v1", Key: "vk", Models: []string{"m"}}) + saveVendor(t, provider.Provider{ID: "keyless", Name: "Keyless", Chat: up.URL + "/v1", Models: []string{"m"}}) + saveVendor(t, provider.Provider{ID: "vendor-off", Name: "Off", Chat: up.URL + "/v1", Key: "vk", Models: []string{"m"}, Off: true}) + mux := arkNativeMux(New()) + free := access.Identity{KeyID: "desk", KeyName: "Desk"} + for _, c := range []struct { + who access.Identity + method, path string + code int + }{ + {free, "POST", NativePath + "keyless/v1/chat/completions", 403}, + {free, "GET", NativePath + "nobody/v1/models", 404}, + {free, "GET", NativePath + "vendor-off/v1/models", 404}, + {access.Identity{KeyName: "held", Models: []string{"vendor/m"}}, "GET", NativePath + "vendor/v1/models", 403}, + {access.Identity{KeyName: "held", Accounts: []string{"vendor"}}, "PUT", NativePath + "vendor/v1/x", 403}, + {access.Identity{KeyName: "held", Limit: &access.Limit{}}, "DELETE", NativePath + "vendor/v1/files/f", 403}, + {access.Identity{KeyName: "issued", Issuer: &access.Identity{KeyName: "boss", Models: []string{"vendor/m"}}}, "PATCH", NativePath + "vendor/v1/x", 403}, + } { + before := len(up.asked()) + rec := arkNativeAsk(t, mux, c.who, c.method, c.path, `{"model":"m"}`) + if rec.Code != c.code || len(up.asked()) > before { + t.Errorf("%s %s as %+v: %d (asked: %v) %s", c.method, c.path, c.who, rec.Code, len(up.asked()) > before, rec.Body) + } + } + for _, c := range []struct { + p provider.Provider + want bool + }{ + {provider.Provider{ID: "a", Key: "k", Chat: "https://x/v1"}, true}, + {provider.Provider{ID: "a", Chat: "https://x/v1"}, false}, + {provider.Provider{ID: "a", Key: "k", Chat: "https://x/v1", Account: &provider.Account{}}, false}, + } { + if got := nativeKeyed(c.p); got != c.want { + t.Errorf("nativeKeyed(%+v) = %v", c.p, got) + } + } +} + +// A path never leaves the provider's host: a "." or ".." segment, +// encoded or not, an encoded slash or backslash that would start +// another host or path, or a scheme, is refused before the vendor is +// asked. +func TestNativeAnyStaysOnTheHost(t *testing.T) { + fresh(t) + up := newVendorAPI(t) + saveVendor(t, provider.Provider{ID: "vendor", Name: "Vendor", Chat: up.URL + "/v1", Key: "vk", Models: []string{"m"}}) + h := nativeServe(t) + for _, p := range []string{ + "a/../b", "a/./b", "a/%2e%2e/b", "a/%2E%2E/%2E%2E/admin", "..%2Fx", "%2e%2e%2fx", "a%2F..%2Fb", "%2e/x", + "%2Fevil.example/x", "%2F%2Fevil.example/x", "%5Cevil.example/x", "a%5C..%5Cb", + "https:%2F%2Fevil.example/x", "http:", "https:/evil.example", "javascript:x", + "a%00b", "", + } { + before := len(up.asked()) + rec := nativeDo(h, "GET", "http://127.0.0.1:3425"+NativePath+"vendor/"+p, "127.0.0.1:50000", "") + if rec.Code < 300 || len(up.asked()) > before { + t.Errorf("%q: %d (asked: %+v) %s", p, rec.Code, up.asked()[before:], rec.Body) + } + } + // and the target itself, for what the mux would clean first + for _, c := range []struct { + raw string + want string + }{ + {"v2/x", "https://api.example/v2/x?q=1"}, + {"v1/models/gemini-2.5-pro:generateContent", "https://api.example/v1/models/gemini-2.5-pro:generateContent?q=1"}, + {"v1/files/a%2Fb", "https://api.example/v1/files/a%2Fb?q=1"}, + {"a/../b", ""}, {"./a", ""}, {"a/.", ""}, {"/evil.example/x", ""}, {"%2F%2Fevil.example", ""}, + {"evil.example%3A80@x/y", ""}, {"v1/x%3A80@evil/y", "https://api.example/v1/x%3A80@evil/y?q=1"}, {"mailto:a@b/x", ""}, {"http://evil.example/x", ""}, {"a\\b", ""}, {"%zz", ""}, + } { + u, err := nativeTarget("https://api.example/v1", c.raw, "q=1") + got := "" + if err == nil { + got = u.String() + } + if got != c.want { + t.Errorf("nativeTarget(%q) = %q, %v; want %q", c.raw, got, err, c.want) + } + } + if _, err := nativeTarget("unix:///sock", "x", ""); err == nil { + t.Error("a base with no http host was taken") + } + if got := nativeQuery("a=1&key=gw&b=%6Bey&k%65y=x&keys=2"); got != "a=1&b=%6Bey&keys=2" { + t.Errorf("nativeQuery = %q", got) + } +} + +// Without a gateway key, a page the gateway doesn't trust reaches no +// vendor through the native route, by any method: a foreign Origin, a +// sandboxed frame's null one, a *.localhost page (WebKit asks DNS for +// it), a page rebound onto 127.0.0.1 under its own name, or another +// machine. +func TestNativeAnyRefusesPagesWithoutAKey(t *testing.T) { + fresh(t) + newCaller(t, "desk") + up := newVendorAPI(t) + saveVendor(t, provider.Provider{ID: "vendor", Name: "Vendor", Chat: up.URL + "/v1", Key: "vk", Models: []string{"m"}}) + h := nativeServe(t) + chrome := []string{"User-Agent", "Mozilla/5.0 (Macintosh) AppleWebKit/605.1.15 Version/27.2 Safari/605.1.15", "Sec-Fetch-Site", "cross-site", "Sec-Fetch-Mode", "cors"} + for _, c := range []struct { + name, remote, host string + hdr []string + }{ + {"a foreign page", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "https://evil.example"}, chrome...)}, + {"Origin null", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "null"}, chrome...)}, + {"a localhost subdomain", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "http://a.localhost"}, chrome...)}, + {"a rebound page", "127.0.0.1:50123", "rebind.attacker.example:3425", chrome}, + {"a rebound page's POST", "127.0.0.1:50123", "rebind.attacker.example:3425", append([]string{"Origin", "http://rebind.attacker.example:3425"}, chrome...)}, + {"another machine", "192.168.1.20:50123", "192.168.1.10:3425", nil}, + } { + for _, m := range nativeMethods { + before := len(up.asked()) + rec := nativeDo(h, m, "http://"+c.host+NativePath+"vendor/v1/chat/completions", c.remote, `{"model":"m"}`, c.hdr...) + if rec.Code != 403 && rec.Code != 401 || len(up.asked()) > before { + t.Errorf("%s %s: %d (asked: %v) %s", c.name, m, rec.Code, len(up.asked()) > before, rec.Body) + } + } + } + // the same route from this computer's own caller is served + if rec := nativeDo(h, "GET", "http://127.0.0.1:3425"+NativePath+"vendor/v1/models", "127.0.0.1:50123", "", "User-Agent", "curl/8"); rec.Code != 201 { + t.Fatalf("own caller: %d %s", rec.Code, rec.Body) + } +} + +// With Settings › Privacy masking, a secret in the body never reaches +// the vendor and comes back in the answer; a body that isn't JSON can't +// be masked, so it isn't sent. +func TestNativeAnyMasks(t *testing.T) { + fresh(t) + if err := settings.Save(settings.Settings{Redact: true}); err != nil { + t.Fatal(err) + } + up := newVendorAPI(t) + saveVendor(t, provider.Provider{ID: "vendor", Name: "Vendor", Chat: up.URL + "/v1", Key: "vk", Models: []string{"m"}}) + h := nativeServe(t) + secret := "sk-ant-api03-" + strings.Repeat("Ab3x", 20) + rec := nativeDo(h, "POST", "http://127.0.0.1:3425"+NativePath+"vendor/v2/notes", "127.0.0.1:50000", `{"model":"m","text":"key `+secret+`"}`) + seen := up.asked() + if rec.Code != 201 || len(seen) != 1 || strings.Contains(seen[0].body, secret) || !strings.Contains(rec.Body.String(), secret) { + t.Fatalf("%d %s; vendor got %+v", rec.Code, rec.Body, seen) + } + rec = nativeDo(h, "POST", "http://127.0.0.1:3425"+NativePath+"vendor/v2/upload", "127.0.0.1:50000", "raw "+secret) + if rec.Code != 415 || len(up.asked()) != 1 { + t.Fatalf("not JSON: %d %s; vendor asked %d", rec.Code, rec.Body, len(up.asked())) + } +} + +// An answer reaches the caller as the vendor sends it: a stream's first +// event, and the first part of a large JSON answer, before the vendor's +// last byte. +func TestNativeAnyStreamsAsItComes(t *testing.T) { + fresh(t) + release := make(chan struct{}) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v2/big" { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"items":["`+strings.Repeat("a", 64<<10)) + } else { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, "event: first\ndata: {}\n\n") + } + w.(http.Flusher).Flush() + select { // until the caller has the first part + case <-release: + case <-r.Context().Done(): + } + if r.URL.Path == "/v2/big" { + io.WriteString(w, `"]}`) + } else { + io.WriteString(w, "event: last\ndata: {}\n\n") + } + })) + t.Cleanup(up.Close) + saveVendor(t, provider.Provider{ID: "vendor", Name: "Vendor", Chat: up.URL + "/v1", Key: "vk", Models: []string{"m"}}) + gw := httptest.NewServer(lanGuard(New().Handler())) + t.Cleanup(gw.Close) + for _, path := range []string{"v2/stream", "v2/big"} { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + req, _ := http.NewRequestWithContext(ctx, "POST", gw.URL+NativePath+"vendor/"+path, strings.NewReader(`{"model":"m"}`)) + res, err := http.DefaultClient.Do(req) + if err != nil { + cancel() + t.Fatal(err) + } + got := make(chan string, 1) + go func() { + if path == "v2/big" { + b := make([]byte, 32<<10) + n, _ := io.ReadFull(res.Body, b) + got <- string(b[:n]) + return + } + line, _ := bufio.NewReader(res.Body).ReadString('\n') + got <- line + }() + select { + case first := <-got: + if (path == "v2/stream" && first != "event: first\n") || (path == "v2/big" && !strings.HasPrefix(first, `{"items":["aaa`)) { + t.Errorf("%s: first part %.40q", path, first) + } + case <-ctx.Done(): + t.Errorf("%s: nothing came before the vendor's last byte", path) + } + release <- struct{}{} + res.Body.Close() + cancel() + } +} + +// Ark keeps its first routes (its short paths under /api/v3, as before, +// in ark_native_test.go) and reaches the rest of its API at its host. +func TestNativeAnyArkHost(t *testing.T) { + fresh(t) + up := newVendorAPI(t) + was := isArk + isArk = func(p provider.Provider) bool { return p.ID == "ark" } + t.Cleanup(func() { isArk = was }) + saveVendor(t, provider.Provider{ID: "ark", Name: "Volcengine Ark", Chat: up.URL + "/api/v3", Key: "key", Models: []string{"doubao"}}) + h := arkNativeMux(New()) + free := access.Identity{KeyID: "desk", KeyName: "Desk"} + if rec := arkNativeAsk(t, h, free, "POST", NativePath+"ark/images/generations", `{"model":"doubao","prompt":"x"}`); rec.Code != 201 { + t.Fatalf("short path: %d %s", rec.Code, rec.Body) + } + if rec := arkNativeAsk(t, h, free, "POST", NativePath+"ark/api/v3/chat/completions", `{"model":"doubao"}`); rec.Code != 201 { + t.Fatalf("host path: %d %s", rec.Code, rec.Body) + } + if rec := arkNativeAsk(t, h, free, "GET", NativePath+"ark/api/v3/contents/generations/tasks/a/b", ``); rec.Code != 201 { + t.Fatalf("host GET: %d %s", rec.Code, rec.Body) + } + var uris []string + for _, s := range up.asked() { + uris = append(uris, s.method+" "+s.uri) + } + want := "POST /api/v3/images/generations\nPOST /api/v3/chat/completions\nGET /api/v3/contents/generations/tasks/a/b" + if strings.Join(uris, "\n") != want { + t.Fatalf("Ark was asked\n%s\nwant\n%s", strings.Join(uris, "\n"), want) + } +} diff --git a/internal/gateway/readonly_test.go b/internal/gateway/readonly_test.go index 00f984a2f..d6c14809d 100644 --- a/internal/gateway/readonly_test.go +++ b/internal/gateway/readonly_test.go @@ -45,6 +45,7 @@ var readOnlyRefused = []string{ "POST /v1/videos", "POST /videos", "GET /v1/videos/{id}", "GET /videos/{id}", "GET /v1/videos/{id}/content", "GET /videos/{id}/content", "POST " + NativePath + "{provider}/{path...}", "GET " + NativePath + "{provider}/{path...}", "DELETE " + NativePath + "{provider}/{path...}", + "PUT " + NativePath + "{provider}/{path...}", "PATCH " + NativePath + "{provider}/{path...}", // MCP servers, plugins' and Codex's backends, Gemini, everything else "POST " + claudeMCPPath + "{token}", "/mcp/{name}", "/mcp/run/{name}", SearchMCPPath, VisionMCPPath, ImageMCPPath, ImageMCPFiles + "{name}", diff --git a/site/public/docs/integrate.html b/site/public/docs/integrate.html index d9632d7d3..9dba16ba7 100644 --- a/site/public/docs/integrate.html +++ b/site/public/docs/integrate.html @@ -122,7 +122,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"Models

GET /v1/models lists what the user has turned on: id (provider/model, or a routing group’s name, sent as it is), display_name, owned_by (the provider), reasoning and supported_reasoning_levels ([{"effort":"low"},…], and the same as plain names in reasoning_levels), context_window and max_output_tokens when known, and modalities when magpie knows whether it takes images. List them from there rather than shipping a list: the user adds and removes providers in magpie. Reasoning is asked in your API’s own field (reasoning_effort, reasoning.effort, Anthropic’s thinking or output_config.effort). ?format=text gives the ids one a line. The list holds chat models alone: ask for image and video models with ?kind=image,video (or ?kind=all). Each is marked "kind": "image" or "video" and is made on /v1/images/generations or /v1/videos, not a chat route.

-

A vendor’s own fields: /v1/images/generations and /v1/videos take OpenAI’s fields and pass the others on to a vendor that takes them, such as Volcengine Ark’s content (reference video and audio, draft_task), ratio, resolution, duration: -1, tools, watermark and sequential_image_generation, and a video’s answer carries Ark’s own fields (content.last_frame_url, usage). For the rest of Ark’s API (an image stream, the task list, cancelling a task) use /v1/magpie/native/<provider>/<path>: POST images/generations, POST or GET contents/generations/tasks, GET or DELETE contents/generations/tasks/<id>, in Ark’s own shape on the user’s Ark key. It takes the same gateway key as every route, and a key held to models, accounts or a budget is refused it.

+

A vendor’s own fields: /v1/images/generations and /v1/videos take OpenAI’s fields and pass the others on to a vendor that takes them, such as Volcengine Ark’s content (reference video and audio, draft_task), ratio, resolution, duration: -1, tools, watermark and sequential_image_generation, and a video’s answer carries Ark’s own fields (content.last_frame_url, usage). For the rest of a vendor’s API use /v1/magpie/native/<provider>/<path>: GET, POST, PUT, PATCH or DELETE, with <path> joined to the provider’s host (not its base URL), in the vendor’s own shape on the user’s key for that provider, a stream as it comes; Ark’s task list is GET /v1/magpie/native/ark/api/v3/contents/generations/tasks. It serves a provider added with an API key, not a subscription or sign-in, and Ark’s short paths (images/generations, contents/generations/tasks) still work under the key’s base. It takes the same gateway key as every route, and a key held to models, accounts or a budget is refused it.

Optional

Send X-Magpie-Session: <id> with a conversation’s requests and GET /v1/magpie/route?session=<id> says which model a routing group picked for the turn and the fallbacks it tried, before the first token (long-poll with after=<seq>&wait=<s>). GET /v1/magpie/quotas lists the user’s subscription allowances, and GET /v1/magpie/usage and /v1/magpie/usage/requests the Usage page’s numbers and its requests (with session, and subagent/parent_agent for a Claude Code subagent’s call). They answer only this machine, or another with a gateway key; a key held to a budget, models or accounts sees its own calls and routes alone, and is refused the quotas unless its owner lets it see those of what it may use (magpie gateway-key quotas <id> on; its own limit is GET /v1/magpie/limit). Calls your app makes to its vendor itself can be reported with POST /v1/magpie/usage/requests (one record or up to 5000 a post, in usage.jsonl’s shape, each with a rid; past times are kept, so a history can be backfilled). They show on the Usage page as reported, and never count against a key’s limit. The reference has the details.

diff --git a/site/public/docs/zh/integrate.html b/site/public/docs/zh/integrate.html index 8d3a25caa..8c425a268 100644 --- a/site/public/docs/zh/integrate.html +++ b/site/public/docs/zh/integrate.html @@ -122,7 +122,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"模型

GET /v1/models 列出用户打开的模型:id(provider/model,或路由组的名字,原样发送即可)、display_name、owned_by(供应商)、reasoning 与 supported_reasoning_levels([{"effort":"low"},…];同样的档位以纯名字列在 reasoning_levels),已知时还有 context_window、max_output_tokens,以及 magpie 知道是否支持图片时的 modalities。请从这里读取,而不是内置一份列表:用户会在 magpie 里增删供应商。推理强度用你所用 API 自己的字段传(reasoning_effort、reasoning.effort、Anthropic 的 thinking 或 output_config.effort)。?format=text 每行一个 id。列表只有对话模型:要图像和视频模型,请加 ?kind=image,video(或 ?kind=all),它们带 "kind": "image" 或 "video",在 /v1/images/generations 或 /v1/videos 上生成,不走对话接口。

-

厂商自己的字段:/v1/images/generations 和 /v1/videos 读 OpenAI 的字段,其余字段原样转给支持它们的厂商,比如火山方舟的 content(参考视频、参考音频、draft_task)、ratio、resolution、duration: -1、tools、watermark、sequential_image_generation;视频的回答也带上方舟自己的字段(content.last_frame_url、usage)。方舟 API 的其他部分(图片流式输出、任务列表、取消任务)请用 /v1/magpie/native/<provider>/<path>:POST images/generations,POST 或 GET contents/generations/tasks,GET 或 DELETE contents/generations/tasks/<id>,按方舟自己的格式收发,用的是用户的方舟密钥。它和其他接口一样需要网关密钥;限了模型、账号或额度的密钥不能用它。

+

厂商自己的字段:/v1/images/generations 和 /v1/videos 读 OpenAI 的字段,其余字段原样转给支持它们的厂商,比如火山方舟的 content(参考视频、参考音频、draft_task)、ratio、resolution、duration: -1、tools、watermark、sequential_image_generation;视频的回答也带上方舟自己的字段(content.last_frame_url、usage)。厂商 API 的其他部分请用 /v1/magpie/native/<provider>/<path>:支持 GET、POST、PUT、PATCH、DELETE,<path> 接在服务商的域名后面(不是 base URL 后面),按厂商自己的格式收发,用的是用户为这个服务商填的密钥,流式回答边到边转;比如方舟的任务列表是 GET /v1/magpie/native/ark/api/v3/contents/generations/tasks。只服务用 API 密钥添加的服务商,不服务订阅或登录的账号;方舟原来的短路径(images/generations、contents/generations/tasks)照旧接在密钥的 base 后面。它和其他接口一样需要网关密钥;限了模型、账号或额度的密钥不能用它。

可选

在同一会话的请求里带上 X-Magpie-Session: <id>,GET /v1/magpie/route?session=<id> 就能在第一个 token 之前告诉你路由组为这一轮选了哪个模型、尝试过哪些后备(用 after=<seq>&wait=<s> 长轮询)。GET /v1/magpie/quotas 列出用户各订阅的额度,GET /v1/magpie/usage 和 /v1/magpie/usage/requests 给出用量页的统计和逐条请求(带 session;Claude Code 子代理的调用还有 subagent/parent_agent)。它们只回答本机,或带网关密钥的其他机器;限了额度、模型或账号的密钥只看得到自己的调用和路由,额度不告诉它,除非它的主人允许它看自己可用部分的额度(magpie gateway-key quotas <id> on;它自己的限额见 GET /v1/magpie/limit)。你的应用直接发给厂商、不经过 magpie 的调用,可以用 POST /v1/magpie/usage/requests 上报(每次一条,或最多 5000 条,格式同 usage.jsonl 的一行,每条带 rid;过去的时间照原样保留,所以可以补录历史)。它们在用量页上标为上报,且从不计入密钥的限额。细节见参考文档。