diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index f0435e2ce..8b874cb49 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -695,6 +695,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) | Each vendor is sent its own request: @@ -782,6 +783,28 @@ that URL (`vendorClient`) and serves a MOV as `video/quicktime` `TestOnlyArkTakesItsOwnVideoAsks`, `TestArkVideoSize`, `TestArkVideoAnswersItsOwnFields`, `TestVideoType`. +#### The native route + +`/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`. 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 new file mode 100644 index 000000000..63e9931ee --- /dev/null +++ b/internal/gateway/ark_native_test.go @@ -0,0 +1,182 @@ +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" +) + +// arkNative is Ark's API on a test server for the native route: it +// records each request and answers a stream as events. +type arkNative struct { + *httptest.Server + mu sync.Mutex + seen []string +} + +func newArkNative(t *testing.T) *arkNative { + t.Helper() + a := &arkNative{} + a.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + a.mu.Lock() + a.seen = append(a.seen, r.Method+" "+r.URL.RequestURI()+" "+r.Header.Get("Authorization")+" "+string(body)) + a.mu.Unlock() + if strings.Contains(string(body), `"stream":true`) { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, "event: image_generation.partial_succeeded\ndata: {\"url\":\"https://example.com/1.png\"}\n\n") + w.(http.Flusher).Flush() + io.WriteString(w, "event: image_generation.completed\ndata: {}\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"cgt-1","items":[]}`) + })) + t.Cleanup(a.Close) + return a +} + +func arkNativeMux(s *Server) *http.ServeMux { + mux := http.NewServeMux() + for _, m := range []string{"POST ", "GET ", "DELETE "} { + mux.HandleFunc(m+NativePath+"{provider}/{path...}", s.native) + } + return mux +} + +func arkNativeAsk(t *testing.T, h http.Handler, who access.Identity, method, path, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req = req.WithContext(access.WithIdentity(req.Context(), who)) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec +} + +// 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. +func TestNativeArkRoute(t *testing.T) { + fresh(t) + up := newArkNative(t) + was := isArk + isArk = func(p provider.Provider) bool { return p.ID == "ark" } + t.Cleanup(func() { isArk = was }) + if err := provider.Save(provider.Provider{ID: "ark", Name: "Volcengine Ark", Chat: up.URL + "/api/v3", Key: "key", Models: []string{"doubao-seedream-4-5-251128"}}); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "other", Name: "Other", Chat: up.URL + "/v1", Key: "key2", Models: []string{"m"}}); err != nil { + t.Fatal(err) + } + h := arkNativeMux(New()) + free := access.Identity{KeyID: "desk", KeyName: "Desk"} + + rec := arkNativeAsk(t, h, free, "POST", NativePath+"ark/images/generations", `{"model":"doubao-seedream-4-5-251128","prompt":"四季","stream":true,"seed":12345678901234567}`) + if rec.Code != 200 || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/event-stream") || !strings.Contains(rec.Body.String(), "image_generation.completed") { + t.Fatalf("stream: %d %q %s", rec.Code, rec.Header(), rec.Body) + } + rec = arkNativeAsk(t, h, free, "GET", NativePath+"ark/contents/generations/tasks?page_size=3&filter.status=succeeded", "") + if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"items"`) { + t.Fatalf("list: %d %s", rec.Code, rec.Body) + } + rec = arkNativeAsk(t, h, free, "DELETE", NativePath+"ark/contents/generations/tasks/cgt-1", "") + if rec.Code != 200 { + t.Fatalf("cancel: %d %s", rec.Code, rec.Body) + } + up.mu.Lock() + seen := append([]string(nil), up.seen...) + up.mu.Unlock() + want := []string{ + `POST /api/v3/images/generations Bearer key {"model":"doubao-seedream-4-5-251128","prompt":"四季","seed":12345678901234567,"stream":true}`, + `GET /api/v3/contents/generations/tasks?page_size=3&filter.status=succeeded Bearer key `, + `DELETE /api/v3/contents/generations/tasks/cgt-1 Bearer key `, + } + if strings.Join(seen, "\n") != strings.Join(want, "\n") { + t.Fatalf("Ark was asked\n%s\nwant\n%s", strings.Join(seen, "\n"), strings.Join(want, "\n")) + } + + for _, c := range []struct { + who access.Identity + 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}, + {access.Identity{KeyName: "held", Limit: &access.Limit{}}, "POST", NativePath + "ark/images/generations", 403}, + {access.Identity{KeyName: "issued", Issuer: &access.Identity{KeyName: "boss", Limit: &access.Limit{}}}, "POST", NativePath + "ark/images/generations", 403}, + } { + up.mu.Lock() + before := len(up.seen) + up.mu.Unlock() + rec := arkNativeAsk(t, h, c.who, c.method, c.path, `{"model":"doubao-seedream-4-5-251128","prompt":"x"}`) + up.mu.Lock() + asked := len(up.seen) > before + up.mu.Unlock() + if rec.Code != c.code || asked { + t.Errorf("%s %s as %+v: %d (Ark asked: %v) %s", c.method, c.path, c.who, rec.Code, asked, rec.Body) + } + } +} + +// A stream reaches the caller as Ark sends it: the first event before +// Ark's last, not the whole answer once it ends. +func TestNativeArkStreamsAsItComes(t *testing.T) { + fresh(t) + release := make(chan struct{}) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, "event: image_generation.partial_succeeded\ndata: {}\n\n") + w.(http.Flusher).Flush() + select { // until the caller has the first event + case <-release: + case <-r.Context().Done(): + } + io.WriteString(w, "event: image_generation.completed\ndata: {}\n\n") + })) + t.Cleanup(up.Close) + t.Cleanup(func() { + select { + case <-release: + default: + close(release) + } + }) + was := isArk + isArk = func(p provider.Provider) bool { return p.ID == "ark" } + t.Cleanup(func() { isArk = was }) + if err := provider.Save(provider.Provider{ID: "ark", Name: "Volcengine Ark", Chat: up.URL + "/api/v3", Key: "key", Models: []string{"doubao-seedream-4-5-251128"}}); err != nil { + t.Fatal(err) + } + mux := arkNativeMux(New()) + front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mux.ServeHTTP(w, r.WithContext(access.WithIdentity(r.Context(), access.Identity{KeyID: "desk", KeyName: "Desk"}))) + })) + t.Cleanup(front.Close) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + req, _ := http.NewRequestWithContext(ctx, "POST", front.URL+NativePath+"ark/images/generations", strings.NewReader(`{"model":"doubao-seedream-4-5-251128","prompt":"四季","stream":true}`)) + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + line, err := bufio.NewReader(res.Body).ReadString('\n') + if err != nil || !strings.Contains(line, "partial_succeeded") { + t.Fatalf("the first event didn't come while Ark held the rest: %q %v", line, err) + } + close(release) +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index a70a4c7a2..ec83b377d 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1002,6 +1002,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) mux.HandleFunc("POST "+claudeMCPPath+"{token}", s.subscription.mcpCall) mux.HandleFunc("/mcp/{name}", s.mcpProxy) mux.HandleFunc("/mcp/run/{name}", runMCP) @@ -1050,7 +1054,7 @@ var catalogSize stamped[struct{}, int] func (s *Server) info(w http.ResponseWriter, r *http.Request) { out := map[string]any{"name": "magpie", "version": Version, "models": catalogSize.get(struct{}{}, func() int { return len(provider.Catalog()) }), "window": Window, - "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}} + "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", NativePath + "{provider}/{path}", "/v1/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}} // which process serves, for another magpie on this computer to name it // on its Routing page (#2606); not told to another machine if local(r) { diff --git a/internal/gateway/native.go b/internal/gateway/native.go new file mode 100644 index 000000000..35b5c9416 --- /dev/null +++ b/internal/gateway/native.go @@ -0,0 +1,197 @@ +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 +// it asks +// +// POST /v1/magpie/native// +// +// and gets the vendor's answer as it came, its stream too. 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. +// +// 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. + +import ( + "bytes" + "cmp" + "encoding/json" + "fmt" + "net/http" + "strings" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// NativePath is where a provider's own API is reached. +const NativePath = "/v1/magpie/native/" + +// 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). +func nativeArkPath(method, path string) bool { + switch { + case path == "images/generations": + return method == http.MethodPost + case path == "contents/generations/tasks": + return method == http.MethodPost || method == http.MethodGet + } + if id, ok := strings.CutPrefix(path, "contents/generations/tasks/"); ok && idPart.MatchString(id) { + return method == http.MethodGet || method == http.MethodDelete + } + return false +} + +// nativeHeld says who is held to something the native route can't hold +// it to: models, accounts, or a spend limit, its own or its issuer's. +func nativeHeld(who access.Identity) bool { + if who.Restricted() || who.Limit != nil || len(who.More) > 0 { + return true + } + return who.Issuer != nil && nativeHeld(*who.Issuer) +} + +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())} + 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) + } + 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)) + return + } + found, err := provider.Find(id) + if err != nil || !found.On() || found.DecideOnly() { + fail(http.StatusNotFound, fmt.Sprintf("magpie has no provider %q turned on", id)) + 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)) + return + } + var body []byte + if r.Method == http.MethodPost { + in, admitted := s.requestBody(w, r, provider.Chat) + if !admitted { + return + } + var v any + dec := json.NewDecoder(bytes.NewReader(in)) + dec.UseNumber() // a seed or an id goes as it came + if err := dec.Decode(&v); err != nil { + fail(http.StatusBadRequest, fmt.Sprintf("the request isn't JSON: %v", err)) + return + } + obj, _ := v.(map[string]any) + if obj == nil { + fail(http.StatusBadRequest, "the request is a JSON object, as Ark takes") + return + } + model, _ := obj["model"].(string) + call.Model = model + if msg, off := modelOff(p, model, p.ID+"/"+model); model != "" && off { + fail(http.StatusForbidden, msg) + return + } + var hits maskHits + if err := maskStrings(r.Context(), obj, &hits); err != nil { // fails closed + fail(maskStatus(err), err.Error()) + return + } + if hits.n > 0 { + b, _ := json.Marshal(obj) + noteMasked(r, "native", hits, string(b), 0, p.ID, model) + } + body, _ = json.Marshal(obj) + } + w, done := restoring(w) + defer done() + ctx := s.metered(p.Via(r.Context()), p, "") + at := cmp.Or(strings.TrimRight(p.Base(provider.Responses), "/"), strings.TrimRight(p.Base(provider.Chat), "/")) + "/" + path + if q := r.URL.RawQuery; q != "" { + at += "?" + q + } + req, err := http.NewRequestWithContext(ctx, r.Method, at, bytes.NewReader(body)) + if err != nil { + fail(http.StatusBadGateway, err.Error()) + return + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + if a := r.Header.Get("Accept"); a != "" { + req.Header.Set("Accept", a) + } + stampUA(ctx, p, req.Header) + if err := p.Sign(ctx, req, provider.Chat, 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() + 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) + } + 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"} { + if v := res.Header.Get(k); v != "" { + w.Header().Set(k, v) + } + } + w.WriteHeader(res.StatusCode) + // a stream goes on as it comes + rc := http.NewResponseController(w) + buf := make([]byte, 32<<10) + for { + n, err := res.Body.Read(buf) + if n > 0 { + if _, werr := w.Write(buf[:n]); werr != nil { + return + } + rc.Flush() + } + if err != nil { // io.EOF, or the vendor gone + return + } + } +} diff --git a/internal/gateway/readonly_test.go b/internal/gateway/readonly_test.go index 6d8e5adc0..00f984a2f 100644 --- a/internal/gateway/readonly_test.go +++ b/internal/gateway/readonly_test.go @@ -44,6 +44,7 @@ var readOnlyRefused = []string{ "POST /v1/audio/speech", "POST /audio/speech", "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...}", // MCP servers, plugins' and Codex's backends, Gemini, everything else "POST " + claudeMCPPath + "{token}", "/mcp/{name}", "/mcp/run/{name}", SearchMCPPath, VisionMCPPath, ImageMCPPath, ImageMCPFiles + "{name}",