provider: Request headers to pass, the agent's own values to its provider
A provider's fixed Headers can't say a value that changes from request
to request or from client to client. 3jRzfF52Qx on X asked for the
agent's own header values to reach the vendor. Each provider now has a
comma-separated list of request headers, saved as `passHeaders`. When the
agent's request carries one of them, its value goes to that provider as
the agent sent it.
- Where it is: the editor's "Request headers to pass" (zh 透传请求头),
under Advanced, right after Reply headers.
- The agent's value stands over a fixed Headers value of the same name.
When the agent sends none, the fixed one goes.
- Never passed on, listed or not (provider.RequestHeaderPassable):
- magpie's key: Authorization, X-Api-Key, X-Goog-Api-Key, Api-Key;
- cookies and sign-ins: Cookie, Set-Cookie(2), WWW-Authenticate,
Authentication-Info, Proxy-*;
- the connection's own fields: Host, Connection, Keep-Alive, TE,
Trailer, Transfer-Encoding, Upgrade, Expect;
- what magpie writes for the body: Content-*, Accept,
Accept-Encoding;
- Origin, Sec-* and X-Magpie-*.
Save refuses such a name with a reason (RequestHeadersOK), and so does
the editor, before the save. The editor's list is held to Go's by
TestReplyHeadersNeverAsTheProvidersAre. A name written into
providers.json by hand is dropped on read.
- Only that provider gets them. forwardOnce, which every chat,
responses, messages, count_tokens, group-member, fallback and plugin
try goes through, puts the agent's headers in the try's context under
the try's provider id (WithClientHeaders). Provider.Sign passes only
what that id lists, before an account signs, so a signed-in account's
own signing still wins. A plugin's fetch gets them in req.Header.
- Wire headers are still masked when read (5ec237568), so a passed
token header shows masked in a call's log.
Run on mote at the tree rebased on origin/main 06944e065:
- gofmt -l: clean.
- go vet: darwin (provider, gateway, gui), GOOS=linux -tags nogui
./..., and GOOS=windows ./...: ok.
- go test -timeout 45m ./internal/provider ./internal/gateway
./internal/gui: provider and gateway ok. In gui, TestCoreScriptBudget
and the i18n tests are ok and only TestMainWindowCorners/macOS_26_SDK
is red, as on main on macOS 27 (#3949).
- The core budget is not raised. This change's words, and the comments
on extra body and the never lists, were cut first. After the rebase
onto 63dc359fb it was 438 bytes over again, so three provider-editor
comments (User-Agent, balance token, plan access keys) were cut to a
line each. The core is 1,533,554 bytes, 248 under 1,533,802.
- At this head (rebased on origin/main 63dc359fb): go test -run
Budget|I18n|ReplyHeaders ./internal/gui is ok. The new provider and
gateway tests are ok. node --test pass-headers, reply-headers,
i18n-keys, header-session-hint, balance-fix and extra-body: 162 of
162 ok.
- node --test, Chromium and WebKit: pass-headers (en/zh/zh-TW/ja/de),
reply-headers, i18n-keys, provider-detect-models, header-session-hint
and extra-body: 46 of 46 ok.
- Before the budget cut, against the same base: every GUI file that
opens the provider editor and saves (45 files plus i18n-keys) had 739
of 758 ok. These were red, and red the same on a fresh origin/main
06944e065 copy: models-works-only (#4391), provider-picks-stay
(#4397) and remote-magpie (#4398). Also red: one WebKit sub-pixel
miss in provider-detect-models (#4964), which passed on main and at
this head.
New tests:
- TestRequestHeadersList: cleaning and refusals.
- TestSignPassesClientHeaders: the agent's value over the fixed one,
never magpie's key even when listed by hand, nothing for another id,
and the fixed value when nothing was sent.
- TestPassHeadersReachTheProvider: messages relayed and translated,
chat, a chat stream, responses and count_tokens.
- TestPassHeadersOnlyToTheirProvider: a fallback that lists nothing gets
nothing, the log shows the passed headers masked, and in a group the
member that lists them gets them while the one before it, which lists
nothing, doesn't.
Broken by hand, each red, then put back:
- forwardOnce without WithClientHeaders: both gateway tests red.
- RequestHeaderPassable ignoring the never list: TestRequestHeadersList
red, and TestSignPassesClientHeaders red on X-Api-Key=magpie-key
passed on.
- Sign not skipping a fixed header the agent sent: the provider test,
and the gateway test on every route, red on X-Route=route-fixed.
Not covered: embeddings, images, video and the Codex backend relay,
which don't go through forwardOnce.
Not tried:
- a real vendor or a real plugin provider with the setting;
- Windows and Linux test runs (vet only);
- a gateway test with Authorization listed by hand, which normalize
drops on read. Sign's own check is covered by
TestSignPassesClientHeaders.
Requested by 3jRzfF52Qx on X.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -27,6 +27,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Headers' conversation ids | `${sessionId}`, `${threadId}` and `${subagentId}` in a value of the provider's `Headers` (Axel Burks on Discord: a gateway in front of several Azure accounts routes one conversation to one account by a session header) are the ids extraBody gets, on every request `Sign` signs: the gateway carries the conversation to it in the request's context (`WithConversation`), on every API and `count_tokens` too. A request that is no turn of a conversation (a model list, a balance, an embedding, image or video, System One's decision model, a search) gets an id of its own, `magpie-` and 12 random letters, new each time (`OwnConversation`); Test and Detect's is their `magpie-test-` id, the same in headers and body. A literal placeholder is never sent. In a header the ids go without control characters (`headerSafe`): an agent's session id with CR or LF in it would split the header, or Go would fail the request. A value with neither placeholder goes as written (`SentHeaders`). | [`conversation.go`](../../internal/provider/conversation.go), [`account.go`](../../internal/provider/account.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codex_resume.go`](../../internal/gateway/codex_resume.go) |
|
||||
| A remote magpie's headers | Every request magpie makes to a Remote magpie carries the provider's `Headers` (Yirasumi on Discord: the Usage page's read went without the header a proxy in front of the remote asks for): its API requests and model list as any provider's (`Sign`, `listHeaders`), and its cards, a card's refresh, its quota history and each gateway key's limit (`signRemote`), the last four as no turn of a conversation (`${sessionId}` an id of its own). The key always reaches the remote as `x-api-key` (`remoteKey`), which a gateway reads beside `Authorization`: a user's `Authorization` (a proxy's own scheme) goes in place of magpie's `Bearer` copy without taking the key away, and a user's `x-api-key` is never sent to a remote magpie, so a key's limit is read with that key. A user's `Authorization` that is itself another gateway key of that magpie is read first there, as on any request. | [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`account.go`](../../internal/provider/account.go) |
|
||||
| Reply headers | `ReplyHeaders` (`replyHeaders` in providers.json, the editor's *Reply headers* under Advanced, a comma-separated list, #4145) names headers of the vendor's reply the gateway passes on to the agent, matched whatever their case and saved canonical (`cleanReplyHeaders`). `DefaultReplyHeaders` (`Request-Id`, `X-Request-Id`, `X-Oneapi-Request-Id`) go from every provider without being listed: opaque request ids, under names magpie sets nothing of its own. Never passed on, listed or not (`ReplyHeaderPassable`): the reply's framing (`Content-*`, `Transfer-Encoding`, hop-by-hop), cookies and sign-ins (`Set-Cookie`, `Authorization`, `WWW-Authenticate`, `Proxy-*`), CORS (`Access-Control-*`), `Sec-*`, redirects and browser policy (`Location`, `Strict-Transport-Security`, `Content-Security-Policy`…), `Retry-After`/`Cache-Control`/`Date`/`Server`/`Vary` (magpie writes those) and `X-Magpie-*` (the gateway reads them as notes of the try). Save refuses such a name (`ReplyHeadersOK`), the editor says so before the save (`replyHeadersOf`, its list held to Go's by `TestReplyHeadersNeverAsTheProvidersAre`), and one written into providers.json by hand is dropped on read. A preset's provider and a signed-in account's requests take it too (`withPicks`). How the gateway carries them is in [gateway routing](gateway-routing.md). | [`replyheaders.go`](../../internal/provider/replyheaders.go), [`reply_headers.go`](../../internal/gateway/reply_headers.go) |
|
||||
| Request headers to pass | `PassHeaders` (`passHeaders` in providers.json, the editor's *Request headers to pass* right after *Reply headers* under Advanced, a comma-separated list; 3jRzfF52Qx on X) names headers of the agent's request passed on to this provider as the agent sent them, matched whatever their case and saved canonical (`cleanRequestHeaders`). The agent's value stands over a fixed *Headers* value of the same name; when the agent sends none, the fixed one goes. `Sign` puts them first (`passClientHeaders`), so an account's own signing still has the last word. Never passed on, listed or not (`RequestHeaderPassable`): magpie's own key as an agent sends it (`Authorization`, `X-Api-Key`, `X-Goog-Api-Key`, `Api-Key`), cookies and sign-ins (`Cookie`, `Set-Cookie`, `WWW-Authenticate`, `Proxy-*`), the connection's fields (`Host`, hop-by-hop, `Expect`), what magpie writes for the body it sends (`Content-*`, `Accept`, `Accept-Encoding`), `Origin`, `Sec-*` and `X-Magpie-*`. Save refuses such a name (`RequestHeadersOK`), the editor says so before the save (`replyHeadersOf(…, true)`, its list held to Go's by `TestReplyHeadersNeverAsTheProvidersAre`), and one written by hand is dropped on read. Only the provider that lists them gets them: the agent's headers ride the request's context under that provider's id (`WithClientHeaders`), so a fallback, a group's other members, a side model or a searcher get none. A preset's provider, a signed-in account's requests and a plugin's fetch take it too. Wire headers are masked when read, so a passed one shows in a call's log as any header does. | [`requestheaders.go`](../../internal/provider/requestheaders.go), [`gateway.go`](../../internal/gateway/gateway.go) |
|
||||
| Native compaction | `NativeCompaction` (`nativeCompaction` in providers.json, the editor's *Compaction* row, `magpie provider set <id> compaction=native\|magpie`; #1099) has Codex's compaction asked of the provider as Codex sent it and its sealed item returned unchanged. Off by default. Only a provider whose wire carries it can be set so (`CarriesCompaction`: a Responses API, a ChatGPT account, GitHub Copilot; not another agent's sign-in or a plugin's), and `CompactsOn(model)` also needs the model asked on Responses. `SetNativeCompaction`, the CLI and the GUI's save refuse it elsewhere. An account keeps it through `Save`'s picks (`withPicks`), and `AddCopy` carries it. The gateway's half is in [gateway-routing](gateway-routing.md). | [`native_compaction.go`](../../internal/provider/native_compaction.go) |
|
||||
| providers.json | `Path` is `providers.json` in magpie's config folder. A read that fails returns `ErrUnreadable` and is never treated as empty. `store` writes atomically through a rename and drops the cached catalog (`catalog.Touched`). | [`provider.go`](../../internal/provider/provider.go) |
|
||||
| A provider renamed | `Rename` (the editor's id field, `magpie provider set <id> id=<new>`) keeps the old id in `Was`, so a model still picked by it reaches the provider. Usage is recorded under the id a call went out by and never rewritten; whatever reads it names the provider by its id now through `UsageRenames().Of(id, time)`: the summary, the Requests page (its blocks, the probe rows, other computers' days), the Sessions tab's vias, window holds, `NewPricer`/`NewCoster` and the gateway's `loggedAnswers` (cybercaius on Discord: a renamed provider was listed under both ids). `Visit` hands records out as recorded, so `Of` is taken once. An id another provider takes later (a rename onto it, or `Save` of a new provider under it) moves from the first one's `Was` to its `Gave` with the time (`giveID`): calls recorded under it before then stay the first one's, later ones are the new one's. An id held by a provider or a subscription now is never renamed (`Renamed`), and `freeID` doesn't hand out an id in any `Was`, so adding a vendor again gets `-2`. Ids reused before `Gave` existed have no time and go to whoever holds the id now. A provider deleted (`Delete`) is kept in providers.json's `deleted` with its name, `Was`, `Gave` and when (`provider.Deleted`): its calls stay under its id while no provider has that id, and once one is added under it (or a later deleted one had it) they go to `Deleted.UsageID`, `<id>~<when, UTC>`, so the new provider has only its own (cybercaius on Discord). The Usage page names either by the deleted provider's name and marks it with when it was deleted (`Renames.Gone`, `Named.Deleted`). Deletes before this was kept have no record and go to whoever holds the id now. A deleted provider's calls can be merged into a provider there is now, or named by the user, from a "…" beside the Requests page's Provider filter while it is picked (`ledProviderMore` in `plugins/usage/page.js`, `POST /api/usage/deleted`, `GET /api/usage/deleted/into`; CyberCaius on Discord, who had renamed a provider onto the old id to do it). Both are kept on its `Deleted` record, not in settings and never in the log: `MergeDeleted` sets `Into` and `MergedAt`, `NameDeleted` sets `Label` (`Deleted.Shown`), so a provider added later under the old id inherits neither. `Renames.Both(id, time)` gives the id a call is shown under (`Of`, merges followed) and the one it was made to (`Own`): a merged call is listed, filtered and summed under the target, but priced, held and answered by its own (`Record.priceID`, `block_price.go`'s `as`, window holds, `loggedAnswers`), so a merge moves no cost or token. The target's face lists what is merged into it (`Named.Merged`), and the same "…" parts each again (`into` ""). Renaming the target carries the merge; deleting it ends it (a merge older than the target's deletion is not followed). A providers.json that can't be read keeps the last renames read, not none. The summary and Requests caches key on `Renames.Key`, the vias cache too. | [`rename.go`](../../internal/provider/rename.go), [`block_price.go`](../../internal/usage/block_price.go) |
|
||||
|
||||
@@ -5104,6 +5104,9 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
|
||||
conv.Thread = threadOf(in, body)
|
||||
}
|
||||
ctx = provider.WithConversation(ctx, conv)
|
||||
// the agent's own headers the provider lists, which Sign passes on to
|
||||
// it alone (PassHeaders)
|
||||
ctx = provider.WithClientHeaders(ctx, p.ID, in)
|
||||
if !countsTokens(path) {
|
||||
// the user's own fields for the provider (#1604), last, so the
|
||||
// body is as it goes out when they fill in what it lacks, and
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// heardHeaders' sibling for a fake vendor: the headers of each request it
|
||||
// was sent.
|
||||
type sentTo struct {
|
||||
mu sync.Mutex
|
||||
seen []http.Header
|
||||
}
|
||||
|
||||
func (s *sentTo) last() http.Header {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.seen) == 0 {
|
||||
return nil
|
||||
}
|
||||
return s.seen[len(s.seen)-1]
|
||||
}
|
||||
|
||||
func (s *sentTo) answer(vendor provider.Protocol, status int) http.HandlerFunc {
|
||||
reply := vendorReply(vendor, status, "x")
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
s.mu.Lock()
|
||||
s.seen = append(s.seen, r.Header.Clone())
|
||||
s.mu.Unlock()
|
||||
reply(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// the agent's request, carrying a header to pass, one to pass that also
|
||||
// has a fixed value, magpie's key in every place an agent puts it, and a
|
||||
// header nobody lists
|
||||
func passRequest(path, body string) *http.Request {
|
||||
r := httptest.NewRequest("POST", path, strings.NewReader(body))
|
||||
r.Header.Set("X-Tenant", "tenant-from-client")
|
||||
r.Header.Set("X-Route", "route-from-client")
|
||||
r.Header.Set("X-Trace-Token", "trace-secret-0123456789")
|
||||
r.Header.Set("X-Unlisted", "no")
|
||||
r.Header.Set("Authorization", "Bearer magpie-gateway-key")
|
||||
r.Header.Set("X-Api-Key", "magpie-gateway-key")
|
||||
return r
|
||||
}
|
||||
|
||||
// 3jRzfF52Qx on X: a header the provider lists goes to it as the agent
|
||||
// sent it, on every API (relayed, translated, count_tokens), standing over
|
||||
// the provider's fixed Header of the same name; the fixed one goes when
|
||||
// the agent sends none; magpie's key never goes.
|
||||
func TestPassHeadersReachTheProvider(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name, path, body string
|
||||
vendor provider.Protocol
|
||||
}{
|
||||
{"messages relayed", "/v1/messages", `{"model":"fake/sol","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`, provider.Anthropic},
|
||||
{"messages to chat", "/v1/messages", `{"model":"fake/sol","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`, provider.Chat},
|
||||
{"chat", "/v1/chat/completions", `{"model":"fake/sol","messages":[{"role":"user","content":"hi"}]}`, provider.Chat},
|
||||
{"chat stream", "/v1/chat/completions", `{"model":"fake/sol","stream":true,"messages":[{"role":"user","content":"hi"}]}`, provider.Chat},
|
||||
{"responses to chat", "/v1/responses", `{"model":"fake/sol","input":"hi"}`, provider.Chat},
|
||||
{"count_tokens", "/v1/messages/count_tokens", `{"model":"fake/sol","messages":[{"role":"user","content":"hi"}]}`, provider.Anthropic},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
fresh(t)
|
||||
up := &sentTo{}
|
||||
p := provider.Provider{ID: "fake", Name: "Fake", Key: "sk-upstream-0123456789", Models: []string{"sol"},
|
||||
Headers: map[string]string{"X-Route": "route-fixed", "X-Fixed": "fixed"},
|
||||
PassHeaders: []string{"x-tenant", "X-ROUTE", "x-trace-token", "x-missing"}}
|
||||
rhVendor(t, p, c.vendor, up.answer(c.vendor, 200))
|
||||
s := New()
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(rec, passRequest(c.path, c.body))
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
h := up.last()
|
||||
if h == nil {
|
||||
t.Fatal("the vendor was sent nothing")
|
||||
}
|
||||
for k, want := range map[string]string{
|
||||
"X-Tenant": "tenant-from-client",
|
||||
"X-Route": "route-from-client", // the client's over the fixed one
|
||||
"X-Trace-Token": "trace-secret-0123456789",
|
||||
"X-Fixed": "fixed",
|
||||
} {
|
||||
if got := h.Values(k); len(got) != 1 || got[0] != want {
|
||||
t.Errorf("%s = %q, want %q", k, got, want)
|
||||
}
|
||||
}
|
||||
for _, k := range []string{"X-Unlisted", "X-Missing"} {
|
||||
if got := h.Get(k); got != "" {
|
||||
t.Errorf("%s = %q sent", k, got)
|
||||
}
|
||||
}
|
||||
if a := h.Get("Authorization") + h.Get("X-Api-Key"); strings.Contains(a, "magpie-gateway-key") || !strings.Contains(a, "sk-upstream-0123456789") {
|
||||
t.Errorf("the vendor's key headers %q, %q", h.Get("Authorization"), h.Get("X-Api-Key"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A listed header, and its fixed value, go to the provider that lists it
|
||||
// alone: a fallback that lists nothing is sent neither, and a group's
|
||||
// member that lists it is sent it. What the call log shows of a passed
|
||||
// header is masked as any header is.
|
||||
func TestPassHeadersOnlyToTheirProvider(t *testing.T) {
|
||||
fresh(t)
|
||||
noRests()
|
||||
t.Cleanup(noRests)
|
||||
first, spare := &sentTo{}, &sentTo{}
|
||||
rhVendor(t, provider.Provider{ID: "ag", Name: "AG", Key: "k", Models: []string{"sol"}, Fallback: []string{"spare/sol"},
|
||||
PassHeaders: []string{"X-Tenant", "X-Trace-Token"}}, provider.Anthropic, first.answer(provider.Anthropic, 429))
|
||||
rhVendor(t, provider.Provider{ID: "spare", Name: "Spare", Key: "k", Models: []string{"sol"}},
|
||||
provider.Chat, spare.answer(provider.Chat, 200))
|
||||
s := New()
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(rec, passRequest("/v1/messages", `{"model":"ag/sol","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`))
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if got := first.last().Get("X-Tenant"); got != "tenant-from-client" {
|
||||
t.Errorf("the listing provider was sent X-Tenant %q", got)
|
||||
}
|
||||
if h := spare.last(); h == nil || h.Get("X-Tenant") != "" || h.Get("X-Trace-Token") != "" {
|
||||
t.Errorf("the fallback that lists nothing was sent %v", h)
|
||||
}
|
||||
data, _ := json.Marshal(s.Recent()[0].Headers())
|
||||
if strings.Contains(string(data), "trace-secret-0123456789") {
|
||||
t.Errorf("a passed token header shown unmasked:\n%s", data)
|
||||
}
|
||||
if !strings.Contains(string(data), "tenant-from-client") {
|
||||
t.Errorf("the passed header isn't in the call's upstream headers:\n%s", data)
|
||||
}
|
||||
|
||||
// a group: its first member lists nothing and is refused, the next
|
||||
// lists it
|
||||
fresh(t)
|
||||
noRests()
|
||||
other, member := &sentTo{}, &sentTo{}
|
||||
rhVendor(t, provider.Provider{ID: "oth", Name: "Oth", Key: "k", Models: []string{"sol"}},
|
||||
provider.Chat, other.answer(provider.Chat, 429))
|
||||
rhVendor(t, provider.Provider{ID: "mem", Name: "Mem", Key: "k", Models: []string{"sol"}, PassHeaders: []string{"X-Tenant"}},
|
||||
provider.Chat, member.answer(provider.Chat, 200))
|
||||
if err := provider.SaveGroup(provider.Group{Name: "Grp", Members: []string{"oth/sol", "mem/sol"}, Routing: provider.Ordered}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
New().Handler().ServeHTTP(rec, passRequest("/v1/chat/completions", `{"model":"group/grp","messages":[{"role":"user","content":"hi"}]}`))
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("group: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if h := other.last(); h == nil || h.Get("X-Tenant") != "" {
|
||||
t.Errorf("the member that lists nothing was sent %v", h)
|
||||
}
|
||||
if h := member.last(); h == nil || h.Get("X-Tenant") != "tenant-from-client" {
|
||||
t.Errorf("the member that lists it was sent %v", h)
|
||||
}
|
||||
}
|
||||
+20
-29
@@ -7829,7 +7829,7 @@ document.addEventListener("click", (e) => {
|
||||
// advancedSet says whether a setting under the editor's Advanced is set,
|
||||
// which opens it: none hides behind a fold
|
||||
function advancedSet(d, p) {
|
||||
return (d.headers || []).some(([k]) => (k || "").trim()) || !!(d.extraBody || "").trim() || !!(d.replyHeaders || "").trim() ||
|
||||
return (d.headers || []).some(([k]) => (k || "").trim()) || !!(d.extraBody || "").trim() || !!(d.replyHeaders || d.passHeaders || "").trim() ||
|
||||
!!d.proxyMode || Object.values(d.accountProxies || {}).some((x) => x?.mode) ||
|
||||
[d.concurrency, d.maxAccounts, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) ||
|
||||
!!d.rateWindows?.length ||
|
||||
@@ -8157,29 +8157,23 @@ function setNewAPIUser(rows, id) {
|
||||
row[1] = id;
|
||||
}
|
||||
|
||||
// A provider's extra body fields (#1604): a JSON object the gateway merges
|
||||
// into the top of every request's body to the vendor, filling in what the
|
||||
// body lacks, or replacing it for a name written "!name"; ${sessionId} is
|
||||
// the conversation's id. The fields magpie sets itself — the model, stream,
|
||||
// the conversation — are refused, as provider.ExtraBodyReserved refuses
|
||||
// them on a save. The draft keeps the text as typed; extraBodyOf reads it.
|
||||
// extra body fields (#1604): provider.ExtraBodyReserved's are refused
|
||||
const EXTRA_BODY_RESERVED = ["model", "stream", "messages", "input", "contents", "system", "systemInstruction", "system_instruction", "instructions", "tools"];
|
||||
function extraBodyText(obj) {
|
||||
return obj && Object.keys(obj).length ? JSON.stringify(obj, null, 2) : "";
|
||||
}
|
||||
// Reply headers magpie never passes on to the agent, listed or not, as
|
||||
// provider.ReplyHeaderPassable refuses them on a save (reply-headers' Go
|
||||
// test holds the two lists the same): the reply's framing, cookies,
|
||||
// sign-ins, CORS and magpie's own (#4145).
|
||||
// headers never passed on: ReplyHeaderPassable's (#4145), RequestHeaderPassable's
|
||||
const REPLY_NEVER = ["alt-svc", "api-key", "authentication-info", "authorization", "cache-control", "clear-site-data", "connection", "content-security-policy", "cookie", "date", "host", "keep-alive", "link", "location", "origin", "refresh", "retry-after", "server", "set-cookie", "set-cookie2", "strict-transport-security", "te", "trailer", "transfer-encoding", "upgrade", "vary", "www-authenticate", "x-accel-buffering", "x-api-key"];
|
||||
const REPLY_NEVER_PREFIX = ["content-", "proxy-", "access-control-", "sec-", "x-magpie-"];
|
||||
// replyHeadersOf is the list a save sends, or why it can't be saved
|
||||
function replyHeadersOf(text) {
|
||||
const REQUEST_NEVER = ["accept", "accept-encoding", "api-key", "authentication-info", "authorization", "connection", "cookie", "expect", "host", "keep-alive", "origin", "set-cookie", "set-cookie2", "te", "trailer", "transfer-encoding", "upgrade", "www-authenticate", "x-api-key", "x-goog-api-key"];
|
||||
const REQUEST_NEVER_PREFIX = ["content-", "proxy-", "sec-", "x-magpie-"];
|
||||
// replyHeadersOf is the list a save sends, or why it can't
|
||||
function replyHeadersOf(text, req) {
|
||||
const value = (text || "").split(",").map((x) => x.trim()).filter(Boolean);
|
||||
for (const n of value) {
|
||||
if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(n)) return { value, error: t("\"{h}\" isn't a header name", { h: n }) };
|
||||
const k = n.toLowerCase();
|
||||
if (REPLY_NEVER.includes(k) || REPLY_NEVER_PREFIX.some((x) => k.startsWith(x))) return { value, error: t("{h} is never passed on: magpie writes it, or it would act on magpie's own address", { h: n }) };
|
||||
if ((req ? REQUEST_NEVER : REPLY_NEVER).includes(k) || (req ? REQUEST_NEVER_PREFIX : REPLY_NEVER_PREFIX).some((x) => k.startsWith(x))) return { value, error: req ? t("{h} is never passed on: it carries a key, or magpie or the connection writes it", { h: n }) : t("{h} is never passed on: magpie writes it, or it would act on magpie's own address", { h: n }) };
|
||||
}
|
||||
return { value };
|
||||
}
|
||||
@@ -9040,7 +9034,7 @@ function baseAPIOf(p) {
|
||||
|
||||
// draftOf is a saved provider as its editor's form holds it.
|
||||
function draftOf(p) {
|
||||
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) };
|
||||
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), passHeaders: (p.passHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) };
|
||||
}
|
||||
|
||||
// duplicateProvider opens the Add form on a copy of p (#268): its URLs,
|
||||
@@ -9578,6 +9572,10 @@ function drawEditor(p, presetID) {
|
||||
replyIn.classList.add("reply-headers");
|
||||
replyIn.oninput = () => { draft.replyHeaders = replyIn.value; };
|
||||
advIn.append(...field(t("Reply headers"), replyIn, t("Headers of the vendor's reply passed on to the agent, separated by commas, in any case. Request IDs (X-Request-Id, Request-Id, X-OneAPI-Request-ID) always are; cookies, CORS and the body's own headers never.")));
|
||||
const passIn = input(draft.passHeaders || "", "X-Tenant-Id");
|
||||
passIn.classList.add("pass-headers");
|
||||
passIn.oninput = () => { draft.passHeaders = passIn.value; };
|
||||
advIn.append(...field(t("Request headers to pass"), passIn, t("Headers of the agent's request passed on as sent, separated by commas. The agent's value stands over a header above. Keys, cookies and the connection's own never are.")));
|
||||
const proxies = el("div", "stack");
|
||||
proxies.append(proxyPicker());
|
||||
const perKey = keyProxyPicker(p);
|
||||
@@ -9617,11 +9615,7 @@ function drawEditor(p, presetID) {
|
||||
advIn.append(...row);
|
||||
}
|
||||
|
||||
// a coding plan that serves only agents it names knows them by their
|
||||
// User-Agent (#1851): a provider with a key may be sent the one the agent
|
||||
// gave in place of magpie's. A signed-in account, and a vendor whose own
|
||||
// client magpie goes as (OpenCode, Cline, Kilo, another magpie), keep
|
||||
// the identity they sign with
|
||||
// the agent's User-Agent (#1851); an account or ownClient keeps its own
|
||||
const uaPassable = () => !p?.account && !(p ? p.ownClient : pr?.ownClient);
|
||||
if (uaPassable()) {
|
||||
const [utk, ucb] = tick(t("Send the agent's own User-Agent"), !!draft.passUserAgent);
|
||||
@@ -9654,10 +9648,7 @@ function drawEditor(p, presetID) {
|
||||
advIn.append(...field(t("Rests"), rtk, t("Off: a 429 or an out-of-quota refusal doesn't rest its keys, and the next request is sent to it as usual. For a relay whose limits pass in a moment.")));
|
||||
}
|
||||
|
||||
// a vendor that tells the whole account's balance only to a token of its
|
||||
// own (AiHubMix's system access token), where a key knows just its own
|
||||
// — or a custom provider's, whose Balance URL may not be named yet: a
|
||||
// token pasted there says at once which URL it wants (balanceFix)
|
||||
// a balance token of the vendor's own (AiHubMix), or a custom one's (balanceFix)
|
||||
let balFix = null;
|
||||
if (p?.balanceToken?.takes || custom) {
|
||||
const saved = !!p?.balanceToken?.set;
|
||||
@@ -9706,11 +9697,8 @@ function drawEditor(p, presetID) {
|
||||
ed.append(...field(t("Team project ID"), proj, t("Only for a key on a team's GLM Coding Plan: both are in {p}'s console, under the team's organization and project. With them the Usage page shows the team's 5-hour and weekly windows.", { p: pr?.name || p.name })));
|
||||
}
|
||||
|
||||
// Volcengine Ark tells a Coding or Agent Plan's windows only to the
|
||||
// account's access key, never to the plan's key (#1427), and Tencent
|
||||
// Cloud a Token Plan 企业版's only to its SecretId and SecretKey (#1574),
|
||||
// asked only at the regions that are that plan; the saved Secret is
|
||||
// never sent back here, only that one is saved
|
||||
// plan windows told only to an access key (Volcengine #1427, Tencent #1574);
|
||||
// the saved Secret never comes back here
|
||||
const access = p ? p.accessKey : pr?.accessKey ? { vendor: pr.accessKeyVendor || "volcengine", id: "", secretSet: false } : null;
|
||||
let accessAt = () => {}, accessShown = () => !!access;
|
||||
if (access) {
|
||||
@@ -9988,6 +9976,9 @@ function drawEditor(p, presetID) {
|
||||
const rh = replyHeadersOf(draft.replyHeaders);
|
||||
if (rh.error) { shown(ed.querySelector(".reply-headers"))?.focus(NO_SCROLL); return editorError(t("Reply headers: {why}", { why: rh.error }), "warn"); }
|
||||
body.replyHeaders = rh.value;
|
||||
const ph = replyHeadersOf(draft.passHeaders, true);
|
||||
if (ph.error) { shown(ed.querySelector(".pass-headers"))?.focus(NO_SCROLL); return editorError(t("Request headers to pass: {why}", { why: ph.error }), "warn"); }
|
||||
body.passHeaders = ph.value;
|
||||
if (decides || custom) body.decide = (custom && draft.api !== "decide" && !p?.decide ? "" : draft.decide || "").trim();
|
||||
if ((body.decide || "").includes(WORKSPACE)) { ed.querySelector(".workspace-id")?.focus(NO_SCROLL); return editorError(t("Give the workspace ID your API key belongs to, or pick the Token Plan"), "warn"); }
|
||||
if (custom) {
|
||||
|
||||
@@ -2354,9 +2354,13 @@ const I18N = {
|
||||
"Extra body": "额外请求体",
|
||||
"JSON fields added to the body of every request to the vendor. A field the request has already is kept; write \"!name\" to replace it. ${sessionId} is the conversation's id; ${threadId} is the thread's, where the agent names one (Codex), else the same.": "加进发往供应商的每个请求体里的 JSON 字段。请求里已有的字段会保留;写成 \"!name\" 则替换它。${sessionId} 是会话的 ID;${threadId} 是线程的 ID(智能体单独给出时,如 Codex),否则与会话 ID 相同。",
|
||||
"Reply headers": "透传响应头",
|
||||
"\"{h}\" isn't a header name": "“{h}”不是有效的响应头名称",
|
||||
"\"{h}\" isn't a header name": "“{h}”不是有效的头名称",
|
||||
"{h} is never passed on: magpie writes it, or it would act on magpie's own address": "{h} 永不透传:它由 magpie 自己写入,或会作用于 magpie 自身的地址",
|
||||
"Reply headers: {why}": "透传响应头:{why}",
|
||||
"Request headers to pass": "透传请求头",
|
||||
"Headers of the agent's request passed on as sent, separated by commas. The agent's value stands over a header above. Keys, cookies and the connection's own never are.": "agent 请求中要按原值透传给供应商的请求头,用逗号分隔,不区分大小写。与上方「请求头」同名时,以 agent 发来的值为准。密钥、Cookie 和连接自身的头永不透传。",
|
||||
"{h} is never passed on: it carries a key, or magpie or the connection writes it": "{h} 永不透传:它带着 magpie 的密钥,或由 magpie 或连接自己写入",
|
||||
"Request headers to pass: {why}": "透传请求头:{why}",
|
||||
"Headers of the vendor's reply passed on to the agent, separated by commas, in any case. Request IDs (X-Request-Id, Request-Id, X-OneAPI-Request-ID) always are; cookies, CORS and the body's own headers never.": "供应商响应中要透传给 agent 的响应头,用逗号分隔,不区分大小写。请求 ID(X-Request-Id、Request-Id、X-OneAPI-Request-ID)总会透传;Cookie、CORS 和响应体自身的头永不透传。",
|
||||
"not valid JSON": "不是有效的 JSON",
|
||||
"write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}": "请写一个 JSON 对象,例如 {\"prompt_cache_key\": \"${sessionId}\"}",
|
||||
@@ -6838,6 +6842,10 @@ const I18N = {
|
||||
"\"{h}\" isn't a header name": "「{h}」不是有效的標頭名稱",
|
||||
"{h} is never passed on: magpie writes it, or it would act on magpie's own address": "{h} 一律不透傳:它由 magpie 自己寫入,或會作用於 magpie 自身的位址",
|
||||
"Reply headers: {why}": "透傳回應標頭:{why}",
|
||||
"Request headers to pass": "透傳請求頭",
|
||||
"Headers of the agent's request passed on as sent, separated by commas. The agent's value stands over a header above. Keys, cookies and the connection's own never are.": "agent 請求中要按原值透傳給供應商的請求頭,以逗號分隔,不分大小寫。與上方「請求頭」同名時,以 agent 送來的值為準。金鑰、Cookie 和連線本身的標頭一律不透傳。",
|
||||
"{h} is never passed on: it carries a key, or magpie or the connection writes it": "{h} 一律不透傳:它帶著 magpie 的金鑰,或由 magpie 或連線自己寫入",
|
||||
"Request headers to pass: {why}": "透傳請求頭:{why}",
|
||||
"Headers of the vendor's reply passed on to the agent, separated by commas, in any case. Request IDs (X-Request-Id, Request-Id, X-OneAPI-Request-ID) always are; cookies, CORS and the body's own headers never.": "供應商回應中要透傳給 agent 的標頭,以逗號分隔,不分大小寫。請求 ID(X-Request-Id、Request-Id、X-OneAPI-Request-ID)一律透傳;Cookie、CORS 與回應本體自身的標頭一律不透傳。",
|
||||
"not valid JSON": "不是有效的 JSON",
|
||||
"write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}": "請寫一個 JSON 物件,例如 {\"prompt_cache_key\": \"${sessionId}\"}",
|
||||
@@ -11295,6 +11303,10 @@ const I18N = {
|
||||
"\"{h}\" isn't a header name": "「{h}」はヘッダー名ではありません",
|
||||
"{h} is never passed on: magpie writes it, or it would act on magpie's own address": "{h} は決して渡しません:magpie 自身が書くか、magpie 自身のアドレスに作用するためです",
|
||||
"Reply headers: {why}": "レスポンスヘッダー: {why}",
|
||||
"Request headers to pass": "引き継ぐリクエストヘッダー",
|
||||
"Headers of the agent's request passed on as sent, separated by commas. The agent's value stands over a header above. Keys, cookies and the connection's own never are.": "エージェントのリクエストのこれらのヘッダーを、送られたままベンダーへ渡します。カンマ区切り、大文字小文字は問いません。上の同名ヘッダーよりエージェントの値が優先されます。キー、Cookie、接続自身のヘッダーは決して渡しません。",
|
||||
"{h} is never passed on: it carries a key, or magpie or the connection writes it": "{h} は決して渡しません:magpie のキーを運ぶか、magpie か接続自身が書くためです",
|
||||
"Request headers to pass: {why}": "引き継ぐリクエストヘッダー: {why}",
|
||||
"Headers of the vendor's reply passed on to the agent, separated by commas, in any case. Request IDs (X-Request-Id, Request-Id, X-OneAPI-Request-ID) always are; cookies, CORS and the body's own headers never.": "ベンダーのレスポンスからエージェントへ渡すヘッダー。カンマ区切りで、大文字小文字は問いません。リクエスト ID(X-Request-Id、Request-Id、X-OneAPI-Request-ID)は常に渡し、Cookie、CORS、ボディ自身のヘッダーは決して渡しません。",
|
||||
"not valid JSON": "有効な JSON ではありません",
|
||||
"write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}": "JSON オブジェクトを書いてください(例: {\"prompt_cache_key\": \"${sessionId}\"})",
|
||||
@@ -15783,6 +15795,10 @@ const I18N = {
|
||||
"\"{h}\" isn't a header name": "„{h}“ ist kein Header-Name",
|
||||
"{h} is never passed on: magpie writes it, or it would act on magpie's own address": "{h} wird nie weitergegeben: magpie schreibt ihn selbst, oder er würde auf magpies eigene Adresse wirken",
|
||||
"Reply headers: {why}": "Antwort-Header: {why}",
|
||||
"Request headers to pass": "Weiterzugebende Anfrage-Header",
|
||||
"Headers of the agent's request passed on as sent, separated by commas. The agent's value stands over a header above. Keys, cookies and the connection's own never are.": "Header der Anfrage des Agenten, die unverändert an den Anbieter weitergehen, durch Kommas getrennt, Groß-/Kleinschreibung egal. Der Wert des Agenten gilt vor einem gleichnamigen Header oben. Schlüssel, Cookies und die Header der Verbindung selbst nie.",
|
||||
"{h} is never passed on: it carries a key, or magpie or the connection writes it": "{h} wird nie weitergegeben: er trägt magpies Schlüssel, oder magpie oder die Verbindung schreibt ihn selbst",
|
||||
"Request headers to pass: {why}": "Weiterzugebende Anfrage-Header: {why}",
|
||||
"Headers of the vendor's reply passed on to the agent, separated by commas, in any case. Request IDs (X-Request-Id, Request-Id, X-OneAPI-Request-ID) always are; cookies, CORS and the body's own headers never.": "Header der Antwort des Anbieters, die an den Agenten weitergegeben werden, durch Kommas getrennt, Groß- und Kleinschreibung egal. Anfrage-IDs (X-Request-Id, Request-Id, X-OneAPI-Request-ID) immer; Cookies, CORS und die Header des Bodys selbst nie.",
|
||||
"not valid JSON": "kein gültiges JSON",
|
||||
"write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}": "schreib ein JSON-Objekt, etwa {\"prompt_cache_key\": \"${sessionId}\"}",
|
||||
|
||||
@@ -101,6 +101,8 @@ type providerJSON struct {
|
||||
ExtraBody provider.ExtraBody `json:"extraBody,omitempty"`
|
||||
// headers of the vendor's reply passed on (provider.ReplyHeaders, #4145)
|
||||
ReplyHeaders []string `json:"replyHeaders,omitempty"`
|
||||
// headers of the agent's request passed on (provider.PassHeaders)
|
||||
PassHeaders []string `json:"passHeaders,omitempty"`
|
||||
// the API the user gave a custom provider's Base URL as (BaseAPI)
|
||||
BaseAPI string `json:"baseAPI,omitempty"`
|
||||
// the vendor searches the web by itself (provider.Searches)
|
||||
@@ -681,7 +683,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
|
||||
ID: p.ID, Name: p.Name, Icon: p.Icon, IconFrom: p.IconFrom, Preset: p.Preset, Host: p.Host(),
|
||||
Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(),
|
||||
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
|
||||
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL,
|
||||
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL,
|
||||
Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)),
|
||||
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
|
||||
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate,
|
||||
@@ -1619,6 +1621,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
pr.BestInFamily = in.BestInFamily
|
||||
pr.ExtraBody = in.ExtraBody
|
||||
pr.ReplyHeaders = in.ReplyHeaders
|
||||
pr.PassHeaders = in.PassHeaders
|
||||
pr.SecretAccessKey = in.SecretAccessKey
|
||||
pr.Vertex = in.Vertex
|
||||
pr.Searches = in.Searches
|
||||
@@ -1662,6 +1665,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
fail(rw, errors.New(why))
|
||||
return
|
||||
}
|
||||
// and request headers that carry magpie's key or the
|
||||
// connection's own
|
||||
if why := provider.RequestHeadersOK(in.PassHeaders); why != "" {
|
||||
fail(rw, errors.New(why))
|
||||
return
|
||||
}
|
||||
cc, keepCC, err := concurrencyOf(req.MaxConcurrency)
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
@@ -1884,6 +1893,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
if in.ReplyHeaders == nil && old != nil {
|
||||
in.ReplyHeaders = old.ReplyHeaders
|
||||
}
|
||||
if in.PassHeaders == nil && old != nil {
|
||||
in.PassHeaders = old.PassHeaders
|
||||
}
|
||||
// Select none likewise, while nothing is picked (#1818)
|
||||
if req.NoModels == nil && old != nil {
|
||||
in.NoModels = old.NoModels
|
||||
|
||||
@@ -11,8 +11,9 @@ import (
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// The editor refuses the reply headers a save would (#4145): its lists are
|
||||
// provider.ReplyHeaderPassable's.
|
||||
// The editor refuses the reply headers, and the request headers to pass, a
|
||||
// save would (#4145): its lists are provider.ReplyHeaderPassable's and
|
||||
// RequestHeaderPassable's.
|
||||
func TestReplyHeadersNeverAsTheProvidersAre(t *testing.T) {
|
||||
js, err := os.ReadFile("assets/app.js")
|
||||
if err != nil {
|
||||
@@ -45,4 +46,12 @@ func TestReplyHeadersNeverAsTheProvidersAre(t *testing.T) {
|
||||
if got, want := listOf("REPLY_NEVER_PREFIX"), lower(prefixes); !slices.Equal(got, want) {
|
||||
t.Errorf("app.js REPLY_NEVER_PREFIX %q, provider %q", got, want)
|
||||
}
|
||||
// and the request headers to pass, provider.RequestHeaderPassable's
|
||||
names, prefixes = provider.RequestHeadersNever()
|
||||
if got, want := listOf("REQUEST_NEVER"), lower(names); !slices.Equal(got, want) {
|
||||
t.Errorf("app.js REQUEST_NEVER %q, provider %q", got, want)
|
||||
}
|
||||
if got, want := listOf("REQUEST_NEVER_PREFIX"), lower(prefixes); !slices.Equal(got, want) {
|
||||
t.Errorf("app.js REQUEST_NEVER_PREFIX %q, provider %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A provider's Request headers to pass (3jRzfF52Qx on X: the agent's own
|
||||
// header values, not a fixed one), right after Reply headers: the editor
|
||||
// shows the saved list, a Save sends what is typed as a list, refuses a
|
||||
// name that carries magpie's key or the connection's own (Authorization,
|
||||
// x-api-key, Host, Content-*, a name that isn't one) and says why, and an
|
||||
// emptied box clears it ([]). It fits a narrow window. In English,
|
||||
// Chinese, Traditional Chinese, Japanese and German, Chromium and WebKit.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const relay = {
|
||||
id: "relay", name: "Relay", preset: "", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", baseAPI: "chat",
|
||||
models: [{ id: "gpt-5.1", name: "gpt-5.1", on: true }], agents: [], fallback: [], headers: {},
|
||||
passHeaders: ["X-Tenant"],
|
||||
key: { set: true, masked: "sk-…one" }, keyList: [{ id: "k1", name: "", masked: "sk-…one", on: true, active: true }],
|
||||
balanceToken: { takes: false, set: false }, proxy: "",
|
||||
};
|
||||
|
||||
function serve(lang, calls) {
|
||||
const providers = { providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } };
|
||||
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/providers") return json(providers);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname.startsWith("/api/provider/")) {
|
||||
calls.push([url.pathname.slice(14), route.request().postDataJSON()]);
|
||||
if (url.pathname === "/api/provider/save") return json(providers);
|
||||
}
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { label: "Request headers to pass", reply: "Reply headers", save: "Save", never: "carries a key", name: "isn't a header name" },
|
||||
zh: { label: "透传请求头", reply: "透传响应头", save: "保存", never: "带着 magpie 的密钥", name: "不是有效的头名称" },
|
||||
"zh-TW": { label: "透傳請求頭", reply: "透傳回應標頭", save: "儲存", never: "帶著 magpie 的金鑰", name: "不是有效的標頭名稱" },
|
||||
ja: { label: "引き継ぐリクエストヘッダー", reply: "レスポンスヘッダー", save: "保存", never: "magpie のキーを運ぶ", name: "ヘッダー名ではありません" },
|
||||
de: { label: "Weiterzugebende Anfrage-Header", reply: "Antwort-Header", save: "Speichern", never: "trägt magpies Schlüssel", name: "ist kein Header-Name" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(words)) {
|
||||
const w = words[lang];
|
||||
test(`${engine} ${lang}: Request headers to pass are shown, refused, saved and cleared`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width: 900, height: 900 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const calls = [];
|
||||
await page.route("**/*", serve(lang, calls));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
const open = async () => {
|
||||
await page.locator(".row.provider", { hasText: "Relay" }).click();
|
||||
const ed = page.locator(".editor");
|
||||
await ed.locator("input.pass-headers").waitFor();
|
||||
return ed;
|
||||
};
|
||||
const save = async (ed) => {
|
||||
await ed.locator(".bar").getByRole("button", { name: w.save, exact: true }).click();
|
||||
for (let i = 0; i < 20 && !calls.some((c) => c[0] === "save"); i++) await page.waitForTimeout(50);
|
||||
};
|
||||
let ed = await open();
|
||||
const box = ed.locator("input.pass-headers");
|
||||
assert.equal(await page.locator(`label[for="${await box.getAttribute("id")}"]`).textContent(), w.label, "labelled");
|
||||
assert.equal(await box.inputValue(), "X-Tenant", "the saved list is shown");
|
||||
// right after Reply headers
|
||||
const after = await box.evaluate((b) => {
|
||||
const fields = [...document.querySelectorAll(".editor label")].map((l) => l.textContent);
|
||||
return fields[fields.indexOf(document.querySelector(`label[for="${b.id}"]`).textContent) - 1];
|
||||
});
|
||||
assert.equal(after, w.reply, "beside Reply headers");
|
||||
|
||||
// refused before a Save, with why, the box focused
|
||||
for (const [text, want] of [["x-tenant, Authorization", w.never], ["x-api-key", w.never], ["Host", w.never], ["Content-Length", w.never], ["x tenant", w.name]]) {
|
||||
await box.fill(text);
|
||||
await save(ed);
|
||||
assert.deepEqual(calls.map((c) => c[0]), [], `${text}: nothing saved`);
|
||||
const said = await ed.locator(".editor-error").textContent();
|
||||
assert.ok(said.includes(want) && said.includes(w.label), `${text}: ${said}`);
|
||||
assert.ok(await box.evaluate((e) => e === document.activeElement), "the box is focused");
|
||||
}
|
||||
|
||||
// the narrow window: the box stays inside the editor
|
||||
await page.setViewportSize({ width: 420, height: 900 });
|
||||
const fits = await page.evaluate(() => {
|
||||
const ed = document.querySelector(".editor").getBoundingClientRect();
|
||||
const r = document.querySelector("input.pass-headers").getBoundingClientRect();
|
||||
return r.left >= ed.left - 0.5 && r.right <= ed.right + 0.5;
|
||||
});
|
||||
assert.ok(fits, "fits a narrow window");
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth), "no sideways scroll");
|
||||
await page.setViewportSize({ width: 900, height: 900 });
|
||||
|
||||
await box.fill(" x-tenant ,X-Session-Route,, ");
|
||||
await save(ed);
|
||||
const saved = calls.find((c) => c[0] === "save");
|
||||
assert.ok(saved, "saved");
|
||||
assert.deepEqual(saved[1].passHeaders, ["x-tenant", "X-Session-Route"], "saved as a list");
|
||||
|
||||
// emptied: a Save clears it
|
||||
calls.length = 0;
|
||||
await page.locator(".editor").waitFor({ state: "hidden" });
|
||||
ed = await open();
|
||||
await ed.locator("input.pass-headers").fill("");
|
||||
await save(ed);
|
||||
assert.deepEqual(calls.find((c) => c[0] === "save")?.[1].passHeaders, [], "an empty box clears it");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ function serve(lang, calls) {
|
||||
|
||||
const words = {
|
||||
en: { label: "Reply headers", save: "Save", never: "is never passed on", name: "isn't a header name" },
|
||||
zh: { label: "透传响应头", save: "保存", never: "永不透传", name: "不是有效的响应头名称" },
|
||||
zh: { label: "透传响应头", save: "保存", never: "永不透传", name: "不是有效的头名称" },
|
||||
"zh-TW": { label: "透傳回應標頭", save: "儲存", never: "一律不透傳", name: "不是有效的標頭名稱" },
|
||||
ja: { label: "レスポンスヘッダー", save: "保存", never: "決して渡しません", name: "ヘッダー名ではありません" },
|
||||
de: { label: "Antwort-Header", save: "Speichern", never: "wird nie weitergegeben", name: "ist kein Header-Name" },
|
||||
|
||||
@@ -219,6 +219,9 @@ func (p Provider) Sign(ctx context.Context, req *http.Request, proto Protocol, b
|
||||
return errAccountDiscoveryOff
|
||||
}
|
||||
ctx = p.Via(ctx) // a sign-in refreshed on the way goes through its proxy
|
||||
// the agent's own headers the provider lists (PassHeaders), before an
|
||||
// account's signing, which has the last word on its own
|
||||
passed := p.passClientHeaders(ctx, req.Header)
|
||||
if p.Account != nil && p.Account.sign != nil {
|
||||
return p.Account.sign(ctx, req, body)
|
||||
}
|
||||
@@ -249,6 +252,9 @@ func (p Provider) Sign(ctx context.Context, req *http.Request, proto Protocol, b
|
||||
// ${sessionId} and ${threadId} in a value are the conversation's
|
||||
// (conversation.go).
|
||||
for k, v := range p.SentHeaders(ctx) {
|
||||
if slices.ContainsFunc(passed, func(n string) bool { return strings.EqualFold(n, k) }) {
|
||||
continue // the agent sent its own, which stands over the user's fixed one
|
||||
}
|
||||
if ListHeader(k) {
|
||||
MergeList(req.Header, k, v)
|
||||
continue
|
||||
|
||||
@@ -274,6 +274,16 @@ type Provider struct {
|
||||
// act on magpie's address, never is (ReplyHeaderPassable).
|
||||
ReplyHeaders []string `json:"replyHeaders,omitempty"`
|
||||
|
||||
// PassHeaders are headers of the agent's request passed on to the
|
||||
// vendor as it sent them, whatever their case (3jRzfF52Qx on X): a
|
||||
// value that changes per request or per client, which a fixed Header
|
||||
// can't give. The client's stands over a Header of the same name;
|
||||
// with none sent the Header goes. Every API, count_tokens, a group's
|
||||
// member, a plugin's fetch; a signed-in account's signing has the
|
||||
// last word. One that carries magpie's key or the connection's own
|
||||
// never is (RequestHeaderPassable).
|
||||
PassHeaders []string `json:"passHeaders,omitempty"`
|
||||
|
||||
// Searches says the vendor answers a web search tool offered on its
|
||||
// Anthropic or Responses API by itself (web_search_20250305,
|
||||
// web_search): a relay in front of Anthropic's or OpenAI's API, which
|
||||
@@ -775,6 +785,7 @@ func (p Provider) clone() Provider {
|
||||
p.Headers = maps.Clone(p.Headers)
|
||||
p.ExtraBody = maps.Clone(p.ExtraBody)
|
||||
p.ReplyHeaders = slices.Clone(p.ReplyHeaders)
|
||||
p.PassHeaders = slices.Clone(p.PassHeaders)
|
||||
p.AccountProxies = maps.Clone(p.AccountProxies)
|
||||
p.AccountCaps = maps.Clone(p.AccountCaps)
|
||||
p.AccountNames = maps.Clone(p.AccountNames)
|
||||
@@ -912,6 +923,8 @@ func accountSettings(a, pk Provider) Provider {
|
||||
a.HiddenDrawers = pk.HiddenDrawers
|
||||
// and the headers of its replies passed on (#4145)
|
||||
a.ReplyHeaders = pk.ReplyHeaders
|
||||
// and the headers of the agent's requests passed on
|
||||
a.PassHeaders = pk.PassHeaders
|
||||
return a
|
||||
}
|
||||
|
||||
@@ -1656,6 +1669,7 @@ func normalize(p Provider) Provider {
|
||||
p.Headers = cleanHeaders(p.Headers)
|
||||
p.ExtraBody = cleanExtraBody(p.ExtraBody)
|
||||
p.ReplyHeaders = cleanReplyHeaders(p.ReplyHeaders)
|
||||
p.PassHeaders = cleanRequestHeaders(p.PassHeaders)
|
||||
if pr := Preset(p.Preset); pr != nil {
|
||||
if p.Icon == "" {
|
||||
p.Icon = pr.Icon
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"slices"
|
||||
"testing"
|
||||
@@ -36,3 +37,55 @@ func TestReplyHeadersList(t *testing.T) {
|
||||
t.Error("passed headers nobody listed")
|
||||
}
|
||||
}
|
||||
|
||||
// A provider's request headers to pass are kept canonical and once each,
|
||||
// never one that carries magpie's key or the connection's own (3jRzfF52Qx
|
||||
// on X).
|
||||
func TestRequestHeadersList(t *testing.T) {
|
||||
got := cleanRequestHeaders([]string{" x-tenant ", "X-TENANT", "authorization", "x-api-key", "host", "content-length", "x-magpie-agent", "bad name", "", "x-trace"})
|
||||
if want := []string{"X-Tenant", "X-Trace"}; !slices.Equal(got, want) {
|
||||
t.Errorf("cleaned %q, want %q", got, want)
|
||||
}
|
||||
for _, bad := range [][]string{{"Authorization"}, {"x-api-key"}, {"X-Goog-Api-Key"}, {"api-key"}, {"Cookie"}, {"Host"}, {"Content-Length"},
|
||||
{"Connection"}, {"Transfer-Encoding"}, {"Proxy-Authorization"}, {"Accept-Encoding"}, {"X-Magpie-Session"}, {"a b"}} {
|
||||
if RequestHeadersOK(bad) == "" {
|
||||
t.Errorf("%q passed as OK", bad)
|
||||
}
|
||||
}
|
||||
if msg := RequestHeadersOK([]string{"x-tenant", " ", "User-Agent", "Anthropic-Beta"}); msg != "" {
|
||||
t.Errorf("OK list refused: %s", msg)
|
||||
}
|
||||
}
|
||||
|
||||
// Sign passes on what the provider lists, the agent's over the fixed
|
||||
// Header, to that provider alone, and never magpie's key, even listed in a
|
||||
// file written by hand (3jRzfF52Qx on X).
|
||||
func TestSignPassesClientHeaders(t *testing.T) {
|
||||
in := http.Header{"X-Tenant": {"t1"}, "Authorization": {"Bearer magpie-key"}, "X-Api-Key": {"magpie-key"}, "x-route": {"r1"}}
|
||||
p := Provider{ID: "fake", Key: "sk-up", Chat: "https://up.example/v1", Headers: map[string]string{"X-Route": "fixed", "X-Only": "o"},
|
||||
PassHeaders: []string{"X-Tenant", "Authorization", "X-Api-Key", "X-Route"}}
|
||||
sign := func(p Provider, ctx context.Context) http.Header {
|
||||
req, _ := http.NewRequest("POST", "https://up.example/v1/chat/completions", nil)
|
||||
if err := p.Sign(ctx, req, Chat, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return req.Header
|
||||
}
|
||||
h := sign(p, WithClientHeaders(context.Background(), "fake", in))
|
||||
if h.Get("X-Tenant") != "t1" || h.Get("X-Route") != "r1" || h.Get("X-Only") != "o" || len(h.Values("X-Route")) != 1 {
|
||||
t.Errorf("sent %v", h)
|
||||
}
|
||||
if h.Get("Authorization") != "Bearer sk-up" || h.Get("X-Api-Key") == "magpie-key" {
|
||||
t.Errorf("magpie's key passed on: %v", h)
|
||||
}
|
||||
// the agent's headers carried for another provider
|
||||
h = sign(p, WithClientHeaders(context.Background(), "other", in))
|
||||
if h.Get("X-Tenant") != "" || h.Get("X-Route") != "fixed" {
|
||||
t.Errorf("another's request passed on %v", h)
|
||||
}
|
||||
// none sent: the fixed Header goes
|
||||
h = sign(p, context.Background())
|
||||
if h.Get("X-Route") != "fixed" || h.Get("X-Tenant") != "" {
|
||||
t.Errorf("with nothing sent %v", h)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
package provider
|
||||
|
||||
// Headers of the agent's request passed on to the vendor (PassHeaders,
|
||||
// 3jRzfF52Qx on X): a value that changes from request to request or from
|
||||
// client to client, which a provider's fixed Headers can't say, goes as the
|
||||
// agent sent it. The mirror of ReplyHeaders (replyheaders.go).
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// requestHeadersNever are never passed on, listed or not: magpie's own key
|
||||
// as an agent sends it (Authorization, x-api-key, x-goog-api-key, api-key)
|
||||
// and the sign-ins and cookies beside it, the connection's own fields, and
|
||||
// what magpie writes for the body it sends (a translated body has another
|
||||
// type, length and encoding, and the transport asks for compression
|
||||
// itself). The prefixes below go with them.
|
||||
var requestHeadersNever = map[string]bool{
|
||||
"Authorization": true, "X-Api-Key": true, "X-Goog-Api-Key": true, "Api-Key": true,
|
||||
"Cookie": true, "Set-Cookie": true, "Set-Cookie2": true, "Www-Authenticate": true, "Authentication-Info": true,
|
||||
"Host": true, "Connection": true, "Keep-Alive": true, "Te": true, "Trailer": true, "Transfer-Encoding": true,
|
||||
"Upgrade": true, "Expect": true, "Accept": true, "Accept-Encoding": true, "Origin": true,
|
||||
}
|
||||
|
||||
// requestHeadersNeverPrefix: Content-Length, -Type and the rest;
|
||||
// Proxy-Authorization and the rest; Sec- fetch metadata; and magpie's own,
|
||||
// which carry who asked and the conversation to a plugin or another
|
||||
// magpie.
|
||||
var requestHeadersNeverPrefix = []string{"Content-", "Proxy-", "Sec-", "X-Magpie-"}
|
||||
|
||||
// RequestHeaderPassable says whether a header of the agent's request may be
|
||||
// passed on to the vendor at all.
|
||||
func RequestHeaderPassable(name string) bool {
|
||||
k := http.CanonicalHeaderKey(strings.TrimSpace(name))
|
||||
if !validHeaderName(k) || requestHeadersNever[k] {
|
||||
return false
|
||||
}
|
||||
for _, p := range requestHeadersNeverPrefix {
|
||||
if strings.HasPrefix(k, p) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// RequestHeadersOK says what is wrong with a list of request headers to
|
||||
// pass on, "" when nothing is.
|
||||
func RequestHeadersOK(names []string) string {
|
||||
for _, n := range names {
|
||||
n = strings.TrimSpace(n)
|
||||
if n == "" {
|
||||
continue
|
||||
}
|
||||
if !validHeaderName(n) {
|
||||
return "\"" + n + "\" isn't a header name"
|
||||
}
|
||||
if !RequestHeaderPassable(n) {
|
||||
return n + " is never passed on: it carries a key, or magpie or the connection writes it"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// cleanRequestHeaders is the list as saved: names trimmed and canonical,
|
||||
// each once, what can't be passed on dropped; nil when nothing is left.
|
||||
func cleanRequestHeaders(names []string) []string {
|
||||
var out []string
|
||||
for _, n := range names {
|
||||
k := http.CanonicalHeaderKey(strings.TrimSpace(n))
|
||||
if RequestHeaderPassable(k) && !slices.Contains(out, k) {
|
||||
out = append(out, k)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// RequestHeadersNever are the names and prefixes RequestHeaderPassable
|
||||
// refuses, for the GUI's own check of a list typed.
|
||||
func RequestHeadersNever() (names, prefixes []string) {
|
||||
for k := range requestHeadersNever {
|
||||
names = append(names, k)
|
||||
}
|
||||
slices.Sort(names)
|
||||
return names, slices.Clone(requestHeadersNeverPrefix)
|
||||
}
|
||||
|
||||
type agentHeadersKey struct{}
|
||||
|
||||
type agentHeaders struct {
|
||||
id string
|
||||
h http.Header
|
||||
}
|
||||
|
||||
// WithClientHeaders is ctx carrying h, the headers of the agent's request,
|
||||
// for Sign to pass on to the provider id those it lists (PassHeaders):
|
||||
// that provider's request alone, never another's made under the same ctx.
|
||||
func WithClientHeaders(ctx context.Context, id string, h http.Header) context.Context {
|
||||
if len(h) == 0 {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, agentHeadersKey{}, agentHeaders{id: id, h: h})
|
||||
}
|
||||
|
||||
// passClientHeaders puts into h the headers of the agent's request ctx
|
||||
// carries that p lists, as sent, in place of any value h has under the
|
||||
// name in any case. It gives the names it put.
|
||||
func (p Provider) passClientHeaders(ctx context.Context, h http.Header) []string {
|
||||
if len(p.PassHeaders) == 0 {
|
||||
return nil
|
||||
}
|
||||
c, ok := ctx.Value(agentHeadersKey{}).(agentHeaders)
|
||||
if !ok || c.id != p.ID {
|
||||
return nil
|
||||
}
|
||||
var put []string
|
||||
for _, n := range p.PassHeaders {
|
||||
k := http.CanonicalHeaderKey(strings.TrimSpace(n))
|
||||
if slices.Contains(put, k) || !RequestHeaderPassable(k) {
|
||||
continue
|
||||
}
|
||||
vs := valuesFold(c.h, k)
|
||||
if len(vs) == 0 {
|
||||
continue
|
||||
}
|
||||
for hk := range h {
|
||||
if strings.EqualFold(hk, k) {
|
||||
delete(h, hk)
|
||||
}
|
||||
}
|
||||
h[k] = slices.Clone(vs)
|
||||
put = append(put, k)
|
||||
}
|
||||
return put
|
||||
}
|
||||
|
||||
// valuesFold is h's values under k, whatever the case of h's keys (a
|
||||
// header map filled by hand).
|
||||
func valuesFold(h http.Header, k string) []string {
|
||||
if vs := h.Values(k); len(vs) > 0 {
|
||||
return vs
|
||||
}
|
||||
for hk, hv := range h {
|
||||
if strings.EqualFold(hk, k) {
|
||||
return hv
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user