Files
magpie/internal/gateway/ark_native_test.go
T
yetone 8a80796805 gateway: the native route passes any path of a keyed provider's own API on, at its host
axelburks (Discord #feedback) asked for /v1/magpie/native/<provider>/...
to reach the whole of a vendor's API, not only Ark's image and video
task paths. Now GET, POST, PUT, PATCH and DELETE of
/v1/magpie/native/<provider>/<path> go to the provider's host at /<path>
(not under the base's /v1 or /api/v3), with the query and body as they
came and the answer streamed back as it comes.

Guards:
- API-key providers only (nativeKeyed): no subscription, OAuth or plugin
  account, no remote magpie, no Vertex. 403 otherwise.
- The gateway's own guards as every route: lanGuard's Host check,
  corsGuard (foreign Origin, null, *.localhost without a key), a key
  beyond loopback, read-only keys refused (PUT/PATCH added to
  readOnlyRefused), and a key held to models/accounts/limits refused
  (nativeHeld, as before).
- nativeTarget refuses an empty path, "." / ".." segments (encoded too,
  across %2F), a backslash, a (encoded) leading slash, "://", a
  scheme-like first segment, and any URL whose host or scheme parsed back
  isn't the base's. 400, vendor not asked.
- The caller's Authorization, x-api-key, api-key, x-goog-api-key,
  Cookie, ?key=, Origin/Referer/Sec-*/X-Forwarded-*/Cf-*, hop and
  X-Magpie-* headers are dropped; Sign puts the provider's key in the
  way it takes one. Set-Cookie, Alt-Svc and HSTS don't come back.
- With masking on, a JSON body is masked (fails closed) and restored in
  the answer; a non-JSON body is a 415. Only a masked request's answer
  goes through restoring; every other answer streams in 32KB reads,
  never held whole.
- Each request is a Requests row and a usage record (Operation
  "native"), with tokens when a JSON or SSE answer reports them.
- Ark's short paths (nativeArkPath) keep their old code path, under the
  key's base, unchanged (nativeArk).

Docs: gateway-routing.md (table row, native route section),
reference.md (path table + paragraph), integrating.md, site
integrate.html en and zh.

Run (mote, darwin arm64, Go 1.26.8):
- go test -count=3 -run 'Native|ReadOnly' ./internal/gateway: ok
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./..., gofmt -l: clean
- Rebased on origin/main b61c71448 (851468ecb): gofmt -l, go vet
  (darwin, linux nogui, windows) of the touched packages, and go test
  -count=1 -timeout 45m ./internal/gateway ./internal/access: both ok.
- Rebased again on origin/main 34116ec01 (five commits, only the
  gateway-routing doc overlapping, merged clean), 5880a1412:
  gofmt -l, the three go vets of internal/gateway, and go test -run
  'Native|ReadOnly' ./internal/gateway: ok. The whole gateway package
  was not rerun there. The last rebase, over 11d9d0a3a (a routing GUI
  commit sharing no file with this one), was not run again.
- Before the rebase, the same packages at 083821dc9:
  access ok; gateway FAIL on TestSocketTurnBodiesFreed only ("1 of 12
  socket turn bodies still kept"), already filed as #5250 for the same
  symptom on a loaded mote; alone it passes 5 of 5 on this tree
  (-count=5), and the change doesn't touch the Responses socket.

Broken by hand, each red on its test:
- no "."/".." segment check: TestNativeAnyStaysOnTheHost (a/%2e%2e/b,
  ..%2Fx, a%2F..%2Fb reached the vendor)
- nativeKeyed always true: TestNativeAnyRefusals
- nativeHeld skipped: TestNativeAnyRefusals
- caller headers not dropped: TestNativeAnyForwardsAtTheHost
- ?key= passed on: TestNativeAnyForwardsAtTheHost
- route on POST/GET/DELETE only (the old registration):
  TestNativeAnyForwardsAtTheHost
- masking skipped: TestNativeAnyMasks
- no Flush: TestNativeAnyStreamsAsItComes (20s, nothing before the last
  byte)
- no sniffer: TestNativeAnyRecordsUsage
- no lanGuard: TestNativeAnyRefusesPagesWithoutAKey (rebound Host and
  another machine reached the vendor)

Not tried: a real call to Ark or any other vendor through the route;
everything here is against httptest vendors.
2026-11-04 22:05:21 +08:00

180 lines
6.9 KiB
Go

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 nativeMethods {
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, 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)
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 + "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)
}