plugin host: a plugin's redirect to another origin is sent none of its key headers (#5508)
Bun follows any redirect anywhere and, on a hop to another origin, drops only Authorization and Cookie. Checked on Bun 1.4.2 before the change: x-api-key, x-goog-api-key and a custom header reached a second local server on each of 301, 302, 303, 307 and 308. So a vendor (or anything answering at its URL) that redirected elsewhere got a plugin's key headers, and an https vendor's redirect to http was followed. host.js now applies provider.KeepsCredentials' rule (c57a5f7f5) at the one place every plugin fetch leaves, `sent`: - `followed` sends each hop with redirect "manual" and follows a 3xx itself only to the first request's origin (scheme, host, port), or http to https on the same host and default ports (`sameOrigin`, a port of provider.SameOrigin), at most 10 ("stopped after 10 redirects", as Go's). Any other 3xx is given back to the plugin as it came, Location included. - A bare request (no body, only accept/user-agent-like headers, BARE_HEADERS) still follows a redirect anywhere, as a download handed to a CDN does; it carries nothing of the plugin's. - 301/302 on POST and 303 become GET with the body and its headers dropped; 307/308 send the body again, and a stream body that can't be sent twice makes the 3xx the answer. - A fetch asked with redirect "manual" or "error" (mimo, cursor, gcp-ai and others do) goes out as it was asked. Paths this covers, all of which reach globalThis.fetch and so `sent`: - the gateway's request to a plugin account: Provider.do → the account's transport → plugin.Fetch → host "fetch" → fetchAs → the loader's fetch, or the host's fetch when the loader has none. A 3xx the host gives back reaches the caller as the vendor sent it. - plugin.Fetch from the check-ins (MiniMax, Qoder, Trae, WorkBuddy) and the models/usage/check/decide reads through plugins.go. - the plugin's own hooks: sign-in authorize/callback, models, usage, checkin, chat.headers, gateway request hooks, and pi.js's extensions (its watchFetch wraps the host's fetch). - proxied ones: a provider's or account's own proxy (via / init.proxy), magpie's global proxy, the SOCKS bridge (netproxy.ForBun) and the LAN direct rule. Each hop is sent by `hop` (the old `sent`), so each picks its own proxy for its own host. Not covered, filed as #5520: Bun.fetch (read-only and non-configurable in Bun 1.4.2, so it can't be wrapped; no community plugin calls it), and a library on node:http that follows redirects itself. node:http, node:http2 and WebSocket follow none. The Go side needs nothing more: Provider.do already hands a plugin account's request to its transport, which doesn't follow. Docs: provider-plugins.md (the rule, what isn't covered, the test) and gateway-routing.md's list of what follows KeepsCredentials. Test: TestPluginRedirectKeepsTheKeyAtItsOrigin (internal/plugin) drives a real host with the fake plugin, sending x-api-key, x-goog-api-key, a cookie, x-own and the loader's Authorization: 307 and 302 to a second local server are the answer and that server gets nothing; an https vendor's 307 to http on its own host and port is the answer; a same-origin 307 is followed with every header and its body; a 303 is a GET without Content-Type; a loop stops after 10; the usage hook's bare GET follows a 302 elsewhere. Broken by hand, on mote: - `sent` passing every fetch to `hop` (Bun's follow): red. away307 and away302 answered 200 {"stolen":true}, and the other server got x-api-key, x-goog-api-key and x-own (not Authorization or Cookie: Bun's own drop). - sameOrigin ignoring the scheme, and bare() always false: red. The https vendor's redirect to http was followed (400 "Client sent an HTTP request to an HTTPS server"), and the bare usage GET got the 302's body instead of "cdn". Restored, green. Run on mote at this tree on origin/main77bda84a6(the docs' #5520 reference added after; no code changed since): gofmt -l clean; go vet ./..., GOOS=windows go vet ./... and GOOS=linux go vet -tags nogui ./... clean. go test -tags nogui -count=1 -timeout 45m ./internal/plugin ./internal/gateway ./internal/provider: all ok (144s, 852s, 163s), no red. No host.js node tests exist. The full ./... suite was not run. Not tried: a real vendor's redirect (none known to redirect its API elsewhere), an http to https upgrade on default ports (the test can't bind 80/443), redirect "manual"/"error" from a plugin in a test (the fake plugin's loader doesn't set one; the code passes such a fetch to `hop` untouched), and Windows/Linux runs of the new test. Rebased on483b131ef(483b131efbrowser,6302f88bfsessions; neither touches this change's files). At the rebased head, on mote: gofmt -l clean, go vet (darwin, GOOS=windows, GOOS=linux -tags nogui) ok, go test -tags nogui -count=1 -run TestPluginRedirect ./internal/plugin ok. The three package runs above were at77bda84a6.
This commit is contained in:
@@ -1518,7 +1518,9 @@ doesn't follow one. The 3xx is the error, and it names where the search
|
||||
was sent. Every request sent with a provider's credential has the
|
||||
same rule: the gateway's client, `Provider.Do` through whichever client
|
||||
it is given (`provider.Keyed`), the provider package's own reads (usage,
|
||||
balance, models, sign-in refreshes) and the Codex relay follow a redirect
|
||||
balance, models, sign-in refreshes), the Codex relay and a plugin's
|
||||
fetch in the plugin host (`followed` in `host.js`, see
|
||||
[provider plugins](provider-plugins.md)) follow a redirect
|
||||
only to the request's origin, or from http to https on its host
|
||||
(`provider.KeepsCredentials` in
|
||||
[`redirect.go`](../../internal/provider/redirect.go)). Go would follow one
|
||||
|
||||
@@ -285,6 +285,8 @@ Keep the migration, host, and upstream behavior separate when investigating fail
|
||||
|
||||
The host gets magpie's proxy only as `MAGPIE_*_PROXY` and applies it to each fetch itself (`proxyFor`), and to each HTTP/2 session a plugin opens (`http2.connect`, `tunnel`, #1035). A host on the user's own network goes around that proxy as it does for magpie's own requests (`onLAN` in `host.js`, a port of `internal/netproxy/lan.go`'s: a private, link-local, loopback or CGNAT address, a `.local` name, or a name every address of which is one of those, looked up for 400 ms at most and kept a minute; #1572). A provider's own proxy is still taken as it is. The two rules are kept the same: a change to one is made in the other. A program a plugin starts, such as the Grok plugin's `grok login`, gets it back as `HTTPS_PROXY`/`HTTP_PROXY` from the spawn wrapper in `host.js`, unless the plugin set one. A sign-in that works in the built-in and fails through the plugin may be a host difference like this one, not a plugin bug. The same wrapper starts a program that names no folder of its own in `plugin-work` under magpie's config folder (with `PWD` to match), not in the host's own folder beside `settings.json`: the chat page plugin starts the user's MCP servers this way, and a tool's file saved by a relative name, or one named like magpie's own files, landed among magpie's (`TestPluginProgramsRunInTheirOwnFolder`). A folder the plugin gives is kept.
|
||||
|
||||
A plugin's fetch is followed through a redirect with its headers only to its own origin (scheme, host and port), or from http to https on the same host: `provider.KeepsCredentials`' rule, which magpie's own requests take (`sent` and `followed` in `host.js`, `sameOrigin` a port of `provider.SameOrigin`; #5508). Bun follows any redirect anywhere and drops only `Authorization` and `Cookie` on a hop to another origin, so `x-api-key`, `x-goog-api-key` and a vendor's own headers went to wherever the `Location` named, and an https vendor's redirect to http was followed. A redirect elsewhere is given back to the plugin as it came, `Location` included, and from a gateway request on to the caller (`Provider.do` hands a plugin's account to its transport, which doesn't follow). A request with no body and only headers any client sends (`BARE_HEADERS`: `accept`, `user-agent` and the like) still follows one anywhere, as a download handed on to a CDN does. A fetch the plugin asks with `redirect: "manual"` or `"error"` is left as it asked. Each hop takes its own proxy (`hop`, `proxyFor`), so a redirect to the user's own network goes direct. At most 10 redirects are followed ("stopped after 10 redirects"); a 307 or 308 whose body is a stream, which can't be sent twice, is the answer. Not covered: `Bun.fetch`, which Bun makes read-only (it skips the host's proxy as well), and a library on `node:http` that follows redirects itself (`node:http`, `node:http2` and WebSocket follow none), #5520.
|
||||
|
||||
magpie downloads the Bun build for this machine (`bunTarget` in [`bun.go`](../../internal/plugin/bun.go)): the baseline build on x64 Linux and Windows, the native `bun-windows-aarch64` on Windows on ARM (it was turned away as having no build until #2183), and on a musl Linux such as Alpine (`libc.Musl`, the check Claude Code's download uses too) the musl one, `bun-linux-x64-musl-baseline` or `bun-linux-aarch64-musl`. A glibc build names glibc's loader, which Alpine lacks, so it couldn't start there and exec said "no such file or directory" (#1877). A musl Linux keeps its Buns and their `state.json` under `bun/musl`, so a machine whose C library changed never runs the other one's build or takes its set-aside versions; everywhere else they stay in `bun`, where a Bun downloaded before is. A bun that is on disk but can't be started says it is a build for another C library and names `MAGPIE_BUN` (`cantStart`), and it isn't fallen back from or set aside: the version before is the same build. Bun's musl build needs libstdc++ and libgcc; on an Alpine without them, `bun add` and the host's start say which library is missing and `apk add libstdc++ libgcc` (`missingLibs`). `TestBunTargetForMusl`, `TestMuslBunKeptApartFromGlibc`, `TestCantStartSaysCLibrary`, `TestHostOnUnstartableBunSaysCLibrary`, `TestMissingLibsNamesThem` and `TestHostOnBunLackingLibsSaysWhich` in [`bunmusl_test.go`](../../internal/plugin/bunmusl_test.go) cover these.
|
||||
|
||||
A bun this machine can't run at all says so instead of its exit status (`wontLoad`, a `*BunUnstartableError`). Windows refuses to load Bun 1.3.14 and later before Windows 10 1809 and Windows Server 2019: they import kernel32's `CreatePseudoConsole`, which older Windows lacks, so the process ends with 0xc0000139 (STATUS_ENTRYPOINT_NOT_FOUND) before it runs (zgcwkj on Discord, a Windows service). A processor without an instruction Bun's x64 build uses (it targets SSE4.2) ends it with 0xc000001d on Windows and SIGILL elsewhere. `bun add`, `bun update` and the host's start (`whyDied`, `cantStart`) each wrap the exit in it. The message says which of the two it is and names `MAGPIE_BUN`. An install doesn't try the community repo's dist branch after it, because that `bun add` can't start either. The GUI's `fail` answers it with code `bun_unstartable`, `bunWhy` (`windows` or `cpu`) and `said`, the i18n.js key for it (`bunSaid` in api.go, kept there so app.js holds one line under its budget), which `api()` in app.js puts through `t()` in place of the English. `TestBunSaidIsTranslated` fails when a language lacks it. There is no fallback to an older Bun: the last one Windows Server 2016 loads, 1.3.13, is below `BunVersion`, and Bun's baseline assets are now the same binary. `TestWontLoadSaysWindowsOrCPU`, `TestInstallOnUnstartableBunSaysWhyAndSkipsDist` and `TestHostOnUnstartableBunSaysWhy` in [`bunload_test.go`](../../internal/plugin/bunload_test.go), `TestFailSaysBunUnstartable` in internal/gui and `plugin-bun-unstartable.test.cjs` (both engines, every language) cover these.
|
||||
@@ -325,6 +327,8 @@ Gateway parity tests in [`plugin_parity_test.go`](../../internal/gateway/plugin_
|
||||
|
||||
[`plugin_cliproxy_test.go`](../../internal/plugin/plugin_cliproxy_test.go)'s `TestPluginHostTakesANewProxy` starts a real host without a proxy, sets one, and checks that a program the plugin starts gets it. [`plugin_lan_test.go`](../../internal/plugin/plugin_lan_test.go)'s `TestPluginLeavesTheUserNetworkDirect` checks with a real host that fetches (http:// and https://) and an HTTP/2 session to this computer's private address reach it directly with a proxy set, and that a public address and an unresolvable name still go through the proxy. `plugin-signed-out-account.test.cjs` covers a moved Grok account signed out while in use and as the agent's own, in Chromium and WebKit, en and zh, 420 and 1100 wide.
|
||||
|
||||
[`plugin_redirect_test.go`](../../internal/plugin/plugin_redirect_test.go)'s `TestPluginRedirectKeepsTheKeyAtItsOrigin` sends a plugin's request with `x-api-key`, `x-goog-api-key`, a cookie and a header of its own through a real host: a 307 and a 302 to another local server are the answer and that server gets nothing, an https vendor's redirect to http on its own port is the answer, a same-origin 307 is followed with every header and its body, a 303 as a GET, a loop stops after 10, and the usage hook's bare GET follows a redirect elsewhere.
|
||||
|
||||
[`stderr_drain_test.go`](../../internal/plugin/stderr_drain_test.go)'s `TestDrainStderrKeepsTheChildGoing` checks that a child writing 8 MiB to stderr with no newline finishes, and that the log says its stderr was dropped. [`stderr_e2e_test.go`](../../internal/plugin/stderr_e2e_test.go)'s `TestHostStartsPastAnOverlongStderrLine` starts a real host whose plugin logs one 5 MiB line while it loads, and checks that the host starts; without the fix it fails on Windows only.
|
||||
|
||||
These tests cover two plugins on one provider id:
|
||||
|
||||
+90
-1
@@ -502,7 +502,96 @@ async function proxyFor(input) {
|
||||
// the first that got none
|
||||
const reach = new AsyncLocalStorage()
|
||||
|
||||
async function sent(input, init) {
|
||||
// sent is a fetch as the plugin asked it, through each redirect it may
|
||||
// follow (followed); hop is one request of it, through its proxy.
|
||||
function sent(input, init) {
|
||||
const redirect = init?.redirect ?? (input instanceof Request ? input.redirect : undefined) ?? "follow"
|
||||
if (redirect !== "follow") return hop(input, init)
|
||||
return followed(input, init)
|
||||
}
|
||||
|
||||
// A plugin's request is followed through a redirect with its headers only
|
||||
// to its own origin (the scheme, host and port it was sent to), or from
|
||||
// http to https on the same host: provider.KeepsCredentials' rule, which
|
||||
// magpie's own requests take (redirect.go, #5508). Bun follows any
|
||||
// redirect anywhere and drops only Authorization and Cookie on a hop to
|
||||
// another origin, so x-api-key, x-goog-api-key and a vendor's own headers
|
||||
// went to wherever the vendor's Location named. A redirect elsewhere is
|
||||
// given back to the plugin as it came, Location and all, unless the
|
||||
// request carries nothing of its own (bare: no body, and only the headers
|
||||
// any client sends), as a download handed on to a CDN is. A fetch the
|
||||
// plugin asked with redirect "manual" or "error" is left as it asked.
|
||||
const REDIRECTS = new Set([301, 302, 303, 307, 308])
|
||||
const BARE_HEADERS = new Set(["accept", "accept-encoding", "accept-language", "user-agent", "cache-control", "pragma", "range", "if-range", "if-none-match", "if-modified-since"])
|
||||
const BODY_HEADERS = ["content-type", "content-length", "content-encoding", "content-language", "content-location"]
|
||||
|
||||
// sameOrigin is provider.SameOrigin, for URLs: a URL leaves out its
|
||||
// scheme's own port.
|
||||
function sameOrigin(from, to) {
|
||||
const port = (u) => u.port || (u.protocol === "http:" ? "80" : u.protocol === "https:" ? "443" : "")
|
||||
if (!from.hostname || from.hostname.toLowerCase() !== to.hostname.toLowerCase()) return false
|
||||
if (from.protocol === to.protocol) return port(from) === port(to)
|
||||
// an upgrade: the request went over http already, to this same host
|
||||
return from.protocol === "http:" && to.protocol === "https:" && port(from) === "80" && port(to) === "443"
|
||||
}
|
||||
|
||||
async function followed(input, init) {
|
||||
let url, opts
|
||||
if (input instanceof Request) {
|
||||
const body = init && "body" in init ? init.body : input.body ? await input.arrayBuffer() : undefined
|
||||
opts = { method: input.method, headers: input.headers, signal: input.signal, ...init, body }
|
||||
url = input.url
|
||||
} else {
|
||||
url = String(input instanceof URL ? input.href : input)
|
||||
opts = { ...init }
|
||||
}
|
||||
const first = new URL(url)
|
||||
let method = (opts.method ?? "GET").toUpperCase()
|
||||
let headers = new Headers(opts.headers)
|
||||
let body = opts.body
|
||||
// a stream can be sent once: a redirect that would send it again is the answer
|
||||
const replayable = body == null || !(body instanceof ReadableStream)
|
||||
const bare = () => body == null && [...headers.keys()].every((k) => BARE_HEADERS.has(k))
|
||||
for (let n = 0; ; n++) {
|
||||
const res = await hop(url, { ...opts, method, headers, body, redirect: "manual" })
|
||||
const at = res.headers.get("location")
|
||||
if (!REDIRECTS.has(res.status) || at == null) return n ? said(res, url) : res
|
||||
let next
|
||||
try {
|
||||
next = new URL(at, url)
|
||||
} catch {
|
||||
return n ? said(res, url) : res
|
||||
}
|
||||
if (next.protocol !== "http:" && next.protocol !== "https:") return n ? said(res, url) : res
|
||||
if (!sameOrigin(first, next) && !bare()) return n ? said(res, url) : res
|
||||
const drops = res.status === 303 ? method !== "HEAD" : (res.status === 301 || res.status === 302) && method === "POST"
|
||||
if (!drops && body != null && !replayable) return n ? said(res, url) : res
|
||||
if (n + 1 >= 10) {
|
||||
res.body?.cancel().catch(() => {})
|
||||
throw new TypeError("stopped after 10 redirects")
|
||||
}
|
||||
res.body?.cancel().catch(() => {})
|
||||
if (drops) {
|
||||
if (method !== "HEAD") method = "GET"
|
||||
body = undefined
|
||||
headers = new Headers(headers)
|
||||
for (const k of BODY_HEADERS) headers.delete(k)
|
||||
}
|
||||
url = next.href
|
||||
}
|
||||
}
|
||||
|
||||
// said is a reply reached through a redirect as fetch says one: where it
|
||||
// came from, and that it was redirected.
|
||||
function said(res, url) {
|
||||
try {
|
||||
Object.defineProperty(res, "redirected", { value: true })
|
||||
Object.defineProperty(res, "url", { value: url })
|
||||
} catch {}
|
||||
return res
|
||||
}
|
||||
|
||||
async function hop(input, init) {
|
||||
if (init && "proxy" in init) return bunFetch(input, init).catch((e) => throwTLS(e, input))
|
||||
const p = await proxyFor(input)
|
||||
if (!p) return bunFetch(input, init).catch((e) => throwTLS(e, input))
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// #5508: Bun follows a redirect anywhere and drops only Authorization and
|
||||
// Cookie on a hop to another origin, so a plugin's x-api-key,
|
||||
// x-goog-api-key and a vendor's own headers went wherever the vendor's
|
||||
// Location named. The host follows a redirect with them only to the
|
||||
// request's own origin (provider.KeepsCredentials' rule), and gives any
|
||||
// other back to the plugin as it came. A request that carries nothing of
|
||||
// its own (the usage hook's bare GET here) still follows one anywhere.
|
||||
func TestPluginRedirectKeepsTheKeyAtItsOrigin(t *testing.T) {
|
||||
sandbox(t)
|
||||
for _, k := range []string{"HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "http_proxy", "all_proxy", "NO_PROXY", "no_proxy", "FAKE_H2"} {
|
||||
t.Setenv(k, "")
|
||||
}
|
||||
var mu sync.Mutex
|
||||
var stolen []string // what reached the other origin: path and its headers
|
||||
thief := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
stolen = append(stolen, fmt.Sprintf("%s %s auth=%q key=%q goog=%q own=%q cookie=%q", r.Method, r.URL.Path,
|
||||
r.Header.Get("Authorization"), r.Header.Get("X-Api-Key"), r.Header.Get("X-Goog-Api-Key"), r.Header.Get("X-Own"), r.Header.Get("Cookie")))
|
||||
mu.Unlock()
|
||||
if r.URL.Path == "/plan" {
|
||||
fmt.Fprint(w, "cdn")
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"stolen":true}`)
|
||||
}))
|
||||
defer thief.Close()
|
||||
var landed []http.Header
|
||||
vendorMux := http.NewServeMux()
|
||||
vendorMux.HandleFunc("/v1/away307", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, thief.URL+"/x", http.StatusTemporaryRedirect)
|
||||
})
|
||||
vendorMux.HandleFunc("/v1/away302", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, thief.URL+"/x", http.StatusFound)
|
||||
})
|
||||
vendorMux.HandleFunc("/v1/here", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Location", "/v1/landed")
|
||||
w.WriteHeader(http.StatusTemporaryRedirect)
|
||||
})
|
||||
vendorMux.HandleFunc("/v1/see", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Location", "/v1/landed")
|
||||
w.WriteHeader(http.StatusSeeOther)
|
||||
})
|
||||
vendorMux.HandleFunc("/v1/landed", func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
landed = append(landed, r.Header.Clone())
|
||||
mu.Unlock()
|
||||
fmt.Fprintf(w, "landed %s %s", r.Method, b)
|
||||
})
|
||||
vendorMux.HandleFunc("/v1/loop", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Location", "/v1/loop")
|
||||
w.WriteHeader(http.StatusTemporaryRedirect)
|
||||
})
|
||||
vendorMux.HandleFunc("/usage", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, thief.URL+"/plan", http.StatusFound)
|
||||
})
|
||||
vendor := httptest.NewServer(vendorMux)
|
||||
defer vendor.Close()
|
||||
|
||||
// an https vendor whose redirect is to http on its own host and port
|
||||
cert, caPEM := certFor(t, net.ParseIP("127.0.0.1"))
|
||||
secure := httptest.NewUnstartedServer(nil)
|
||||
secure.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Location", "http://"+secure.Listener.Addr().String()+"/x")
|
||||
w.WriteHeader(http.StatusTemporaryRedirect)
|
||||
})
|
||||
secure.TLS = &tls.Config{Certificates: []tls.Certificate{cert}}
|
||||
secure.StartTLS()
|
||||
defer secure.Close()
|
||||
ca := filepath.Join(t.TempDir(), "redirect-ca.pem")
|
||||
if err := os.WriteFile(ca, caPEM, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("NODE_EXTRA_CA_CERTS", ca)
|
||||
t.Setenv("FAKE_BASE", vendor.URL+"/v1")
|
||||
t.Setenv("FAKE_USAGE", vendor.URL+"/usage")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
abs, _ := filepath.Abs("testdata/fake/index.js")
|
||||
if _, err := Add(ctx, abs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Providers(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := APIKey(ctx, "fakeco", 0, nil, "k1", NewAccount); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys := map[string]string{"x-api-key": "sk-ant", "x-goog-api-key": "AIza", "x-own": "relay-secret", "cookie": "session=s1", "content-type": "application/json"}
|
||||
fetch := func(url string) (*http.Response, string, error) {
|
||||
fctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
res, err := Fetch(fctx, FetchRequest{Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible",
|
||||
URL: url, Method: "POST", Headers: keys, Body: []byte(`{}`)})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
return res, string(b), nil
|
||||
}
|
||||
took := func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]string(nil), stolen...)
|
||||
}
|
||||
|
||||
// elsewhere: the 3xx is the answer, and nothing goes there
|
||||
for path, code := range map[string]int{"/v1/away307": 307, "/v1/away302": 302} {
|
||||
res, body, err := fetch(vendor.URL + path)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", path, err)
|
||||
}
|
||||
if res.StatusCode != code || res.Header.Get("Location") != thief.URL+"/x" {
|
||||
t.Errorf("%s: %d, Location %q, %q; want the vendor's %d to %s/x as it came", path, res.StatusCode, res.Header.Get("Location"), body, code, thief.URL)
|
||||
}
|
||||
}
|
||||
if s := took(); len(s) > 0 {
|
||||
t.Fatalf("a redirect to another origin was followed with the plugin's request: %q", s)
|
||||
}
|
||||
|
||||
// https to http on the same host and port: not followed either
|
||||
res, body, err := fetch("https://" + secure.Listener.Addr().String() + "/v1/plain")
|
||||
if err != nil {
|
||||
t.Fatalf("https vendor: %v", err)
|
||||
}
|
||||
if res.StatusCode != http.StatusTemporaryRedirect {
|
||||
t.Errorf("an https vendor's redirect to http was followed: %d %q", res.StatusCode, body)
|
||||
}
|
||||
|
||||
// its own origin: followed with every key, the body sent again
|
||||
res, body, err = fetch(vendor.URL + "/v1/here")
|
||||
if err != nil || res.StatusCode != 200 || body != "landed POST {}" {
|
||||
t.Fatalf("same-origin 307: %v, %v, %q; want it followed with its body", err, res, body)
|
||||
}
|
||||
mu.Lock()
|
||||
h := landed[len(landed)-1]
|
||||
mu.Unlock()
|
||||
for k, v := range keys {
|
||||
if h.Get(k) != v {
|
||||
t.Errorf("same-origin redirect: %s = %q, want %q", k, h.Get(k), v)
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(h.Get("Authorization"), "Bearer ") {
|
||||
t.Errorf("same-origin redirect: Authorization %q, want the plugin's", h.Get("Authorization"))
|
||||
}
|
||||
// a 303 is followed as a GET, its body and the body's headers left
|
||||
res, body, err = fetch(vendor.URL + "/v1/see")
|
||||
if err != nil || res.StatusCode != 200 || body != "landed GET " {
|
||||
t.Fatalf("same-origin 303: %v, %v, %q; want a GET", err, res, body)
|
||||
}
|
||||
mu.Lock()
|
||||
h = landed[len(landed)-1]
|
||||
mu.Unlock()
|
||||
if h.Get("Content-Type") != "" || h.Get("X-Api-Key") != "sk-ant" {
|
||||
t.Errorf("303: Content-Type %q, X-Api-Key %q; want the body's headers dropped and the key kept", h.Get("Content-Type"), h.Get("X-Api-Key"))
|
||||
}
|
||||
// at most 10
|
||||
if _, _, err := fetch(vendor.URL + "/v1/loop"); err == nil || !strings.Contains(err.Error(), "stopped after 10 redirects") {
|
||||
t.Errorf("a redirect loop: %v, want it stopped after 10", err)
|
||||
}
|
||||
if s := took(); len(s) > 0 {
|
||||
t.Fatalf("the thief got %q", s)
|
||||
}
|
||||
|
||||
// a bare request carries nothing of the plugin's: a CDN's redirect is followed
|
||||
u, err := AccountUsage(ctx, "fakeco", "")
|
||||
if err != nil || u.Plan != "cdn" {
|
||||
t.Fatalf("a bare GET's redirect elsewhere: %+v, %v; want it followed", u, err)
|
||||
}
|
||||
if s := took(); len(s) != 1 || !strings.HasPrefix(s[0], `GET /plan auth="" key="" goog="" own="" cookie=""`) {
|
||||
t.Errorf("the bare GET's hop: %q", s)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user