gateway: another magpie's request is masked and shown in flight under its agent (linkaww)
linkaww on Discord: Pi through a local magpie to a remote magpie with masking on. The remote's masking log named the request "magpie", while its usage already said Pi. The local magpie already sends the agent (X-Magpie-Agent / X-Magpie-Via, passOnCaller). The remote's masking log read agentOf, the real sender, instead of callerOf, the recorded label. So the fix is on the remote: only the remote magpie needs this version. There is one rule now, callerFrom/callerOf, for every place the remote says who sent a request: - the masking log (noteMasked) - the requests in flight (/v1/magpie/concurrency). counted runs before withCaller, so active.add calls callerFrom itself. - observed calls - Codex title / tool-loop answers (answeredHere) - Codex search and backend records, which recorded agentOf Usage and sessions already used callerOf. The trust rule is unchanged. The headers are taken only from a magpie/ User-Agent and are a label only: access, key limits and behaviour (middleware Info.Agent, models shown, stand-ins, group rules) still go by the key and agentOf. A client that isn't magpie is logged as itself. Run: - go test -tags nogui -count=1 -timeout 45m ./internal/gateway: ok (562s) at bdd6a6c73, this change on1cbdda25b- after rebasing onto430e3050d: go vet (darwin, GOOS=linux, GOOS=windows, -tags nogui) ./internal/gateway, gofmt -l, and -run 'TestRemoteMagpie|TestMasked|Active|Concurrency|CodexTitle|ToolLoop': ok - Two sandbox magpies on 127.0.0.1:47611 (remote, masking on, a fake upstream on :47613) and :47612 (local, a Remote magpie provider to :47611), each under its own HOME/XDG dirs. A Pi request (Bearer magpie-pi) carrying an API key went through the local. With the remote on origin/main, its masking/<day>.jsonl line said "agent":"magpie" and its usage said "pi". With the remote on this change, both said "pi". The upstream got the key masked. Broken by hand: masked.go back to agentOf made TestRemoteMagpieMaskedNamesTheAgent fail ("logged as \"magpie\", want pi"). active.go back to agentOf made TestRemoteMagpieActiveNamesTheAgent fail (Agent:magpie). Not tried: the GUI's Privacy page on the remote. It shows the record's agent field, which the jsonl above has. A remote reached through a Claude Code or Codex client User-Agent (passUserAgent): there the remote reads that agent from its own User-Agent, as before.
This commit is contained in:
@@ -144,7 +144,7 @@ recorded as a prediction failure (`noPrediction`).
|
||||
- The user's own masked words (`redactWords`, `Options.Words`; Settings → Privacy's *Masked words*) go as `{{TERM_…}}` whatever else is on, and come back as written. They match as written, inside longer words too, unless the user asks: *Masked words in any case* (`redactWordsAnyCase`, `WordsAnyCase`) matches in any capitals by Unicode simple folding, and *Whole words only* (`redactWordsWhole`, `WordsWhole`; acmilan_ on Discord) skips a match with a letter, digit or `_` beside it, and for a number a `.` and digit beside it, so `ABC` masks `name='ABC'` but not `XABCD`, and `123456` not `91234567`, `0.123456` or `123456.78` (`wholeWord` in [`redact.go`](../../internal/redact/redact.go)). Chinese and Japanese letters count as no letter there (`wordRune`): a word of theirs is found inside their text, and `ABC` in 用ABC做 is whole. Both are off by default; a page from before them that saves without the field keeps the user's choice (`api.go`). `TestWordsWhole`, `TestWordsWholeJSON`, `TestCountTokensRedacted`.
|
||||
- With *Keep a key's form* on (`settings.RedactShape`, `Options.Shape`, under *Mask secrets*; Charles Cao on X), a secret of 16 characters or more, all letters, digits, `-`, `_` or `.`, goes as a made-up key of its form instead of a placeholder: its prefix kept (`sk-proj-`, `ghp_`, `AKIA`, up to four letters and their separator; `keyHead`), the same length and separators, and each other character a random one of its kind (a hex key's any hex digit of its case), drawn from an HMAC of the value under the placeholder key, so one key goes as the same made-up one every turn and a vendor's cache still matches (`shapeOf`, `shaped` in [`internal/redact/shape.go`](../../internal/redact/shape.go)). Personal data, the user's words and anything shorter or with other characters go as placeholders still. A made-up key is kept in the masker's memory with the placeholders, so it is recorded, re-masked in what a vendor sealed, and put back wherever the reply has it, before the placeholders (`restoreShapes`); a stream holds the end of an event that may be the start of one (`shapeTail`, after the last whole one), and a made-up key the vendor sends back unrestored isn't masked again (`outsideShapes`). `TestShapeKeepsForm`, `TestShapeJSON`, `TestShapeStream`. Insights › Masking and Settings' *Try it* mark a made-up key where they mark a placeholder, matching the text against the request's own values only, so a key of the same form the user wrote isn't marked (`maskMatches` in `plugins/redact/page.js`; #3599, masking-records and mask-actions GUI tests).
|
||||
- What is done with a value found is the user's per kind (#1977, `redactActions` in settings, `Options.Actions`, set by `POST /api/settings/redact-actions`; a kind left out is masked). `redact.Warn` sends it as written: the masker tells it, with a placeholder no one remembers, and it isn't counted as masked. `redact.Block` masks it as any other, and the gateway holds the request back with a 400 that names the kind and the value's hint, never the value (`blocked`, `maskBlocked` in [`redact.go`](../../internal/gateway/redact.go)); nothing is sent and the record is kept as `Blocked` (`noteBlocked`). A value on the *Never mask* list (`redactAllow`, `Options.Allow`, `POST /api/settings/redact-allow`) goes as written when it is the whole value found, in any case, and isn't told; a longer value it is part of is masked. Settings → Privacy's *Try it* posts a text to `POST /api/masking/preview` ([`masking.go`](../../internal/gui/masking.go)), which masks it as a request would be (`redact.Preview`) and remembers nothing: its placeholders stand for nothing afterwards, its values aren't masked later as seen before, and it returns only the masked text and each hit's kind, finder, action, placeholder and hint. The page keeps the text in no storage.
|
||||
- Each request that had anything masked is recorded as it goes to the vendor (`noteMasked` in [`masked.go`](../../internal/gateway/masked.go), from chat, the Codex backend, search, images, video, System One, embeddings and audio; count_tokens is masked and not recorded). The masker says what it swapped through `gwmw.Teller` (`JSONHits`, `TextHits`: each placeholder's kind, its finder, `redact.ByRule`, `ByYours`, `ByWord`, `ByModel` or `ByKnown`, and a hint of its first characters and its length), and [`internal/maskrec`](../../internal/maskrec/maskrec.go) keeps one line per request in a file per day under `~/.config/magpie/masking`, 30 days and 100 MB in all: the agent, session, provider, model, and each placeholder with its kind, finder, action and hint, never the value. A chat, an embedding or a video whose group can pass it to another member is held in memory until the request is over (`noteMaskedUntil`, `maskrec.Hold`), and its line names the provider and model the last try went to, not the first planned, which a failover may never have reached; the list sorts each day's lines by key, since a long request's line is written after later ones. The text around each placeholder as the vendor saw it is kept in memory only, for the last 400 records, and what a placeholder stood for only in the masker's own memory (`Teller.Value`); after a restart neither is there. A recent call (`Call.Masked`) and the route trace (`Route.Masked`) carry the counts and the record's key, which the Gateway and Routing pages' badge opens in Settings → Privacy (`/api/masking/*`, [`internal/gui/masking.go`](../../internal/gui/masking.go)). A masker without `Teller`, a plugin's, masks as before and records nothing. Under a test binary testenv isolated nothing is written (`maskrec.inTest`). The page's Clear records… (after a confirm) posts `/api/masking/clear`, and `maskrec.Clear` removes every day's file whole under the store's lock, with the in-memory text around placeholders; a day it can't remove stays listed and is named in the error. What the masker holds for each placeholder stays, so a placeholder still in an agent's context is put back in its answers.
|
||||
- Each request that had anything masked is recorded as it goes to the vendor (`noteMasked` in [`masked.go`](../../internal/gateway/masked.go), from chat, the Codex backend, search, images, video, System One, embeddings and audio; count_tokens is masked and not recorded). The masker says what it swapped through `gwmw.Teller` (`JSONHits`, `TextHits`: each placeholder's kind, its finder, `redact.ByRule`, `ByYours`, `ByWord`, `ByModel` or `ByKnown`, and a hint of its first characters and its length), and [`internal/maskrec`](../../internal/maskrec/maskrec.go) keeps one line per request in a file per day under `~/.config/magpie/masking`, 30 days and 100 MB in all: the agent (the one usage records, `callerOf`, so a request another magpie passed on is named by the agent it came from, not as `magpie`; linkaww on Discord), session, provider, model, and each placeholder with its kind, finder, action and hint, never the value. A chat, an embedding or a video whose group can pass it to another member is held in memory until the request is over (`noteMaskedUntil`, `maskrec.Hold`), and its line names the provider and model the last try went to, not the first planned, which a failover may never have reached; the list sorts each day's lines by key, since a long request's line is written after later ones. The text around each placeholder as the vendor saw it is kept in memory only, for the last 400 records, and what a placeholder stood for only in the masker's own memory (`Teller.Value`); after a restart neither is there. A recent call (`Call.Masked`) and the route trace (`Route.Masked`) carry the counts and the record's key, which the Gateway and Routing pages' badge opens in Settings → Privacy (`/api/masking/*`, [`internal/gui/masking.go`](../../internal/gui/masking.go)). A masker without `Teller`, a plugin's, masks as before and records nothing. Under a test binary testenv isolated nothing is written (`maskrec.inTest`). The page's Clear records… (after a confirm) posts `/api/masking/clear`, and `maskrec.Clear` removes every day's file whole under the store's lock, with the in-memory text around placeholders; a day it can't remove stays listed and is named in the error. What the masker holds for each placeholder stays, so a placeholder still in an agent's context is put back in its answers.
|
||||
- `DecidesModel` gives a 400.
|
||||
- A gateway key held to some models (`keyHolds`, #882) gets a 403 for any other model.
|
||||
- A model the user disabled (#1867) gets a 403 for every caller (`idOff`), before anything is sent; see [Disabled models](#disabled-models).
|
||||
@@ -432,7 +432,12 @@ Conversation forwarding preserves Claude Code and Codex client headers
|
||||
(including Codex's `originator`) so relays behind the remote can recognize
|
||||
them. Decision, retrieval and media requests set magpie's User-Agent at
|
||||
their own call sites, so the remote accepts their attribution. Vendors
|
||||
receive no caller labels.
|
||||
receive no caller labels. The remote names the passed-on agent by one rule
|
||||
(`callerFrom`, `callerOf`) wherever it shows who sent a request: usage and
|
||||
sessions, recent calls and the Routing trace, the masking log and the
|
||||
requests in flight (`counted` runs before `withCaller`, so `active.add` reads
|
||||
`callerFrom` itself). The label never changes access, limits or behaviour,
|
||||
which go by the key and the real sender (`agentOf`).
|
||||
|
||||
A custom provider (no account, no preset plan's videos) makes videos the
|
||||
same OpenAI way (#1446, `customVideomakers`), but only with the models its
|
||||
|
||||
@@ -64,7 +64,7 @@ type inflights struct {
|
||||
// add counts r in and answers it with its inflight on its context, and the
|
||||
// func that counts it out.
|
||||
func (l *inflights) add(r *http.Request) (*http.Request, func()) {
|
||||
f := &inflight{agent: agentOf(r), session: sessionOf(r.Header), start: time.Now()}
|
||||
f := &inflight{agent: callerFrom(r).agent, session: sessionOf(r.Header), start: time.Now()}
|
||||
l.mu.Lock()
|
||||
if l.m == nil {
|
||||
l.m = map[int64]*inflight{}
|
||||
|
||||
@@ -970,7 +970,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
captureTitle = link != nil && isTitleKind(kind)
|
||||
turn, scan := agentTurnOf(r, kind)
|
||||
tools = scan
|
||||
tr = s.trace.beginFor(r, Route{turn: turn, dirOf: dirOf(provider.Responses, body), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, callerOf(r).agent), imageProvider: imageProvider, TitleLink: link, Time: start, Agent: agentOf(r), Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, kind), Kind: kind, Model: model, Effort: effort, Tier: bodyTier(provider.Responses, body), Provider: "openai", Subagent: subagentPickOf(r),
|
||||
tr = s.trace.beginFor(r, Route{turn: turn, dirOf: dirOf(provider.Responses, body), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, callerOf(r).agent), imageProvider: imageProvider, TitleLink: link, Time: start, Agent: callerOf(r).agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, kind), Kind: kind, Model: model, Effort: effort, Tier: bodyTier(provider.Responses, body), Provider: "openai", Subagent: subagentPickOf(r),
|
||||
Order: []Weighed{seat}, Tries: []Try{{ID: seat.ID, Model: model, Effort: effort, Start: start}}})
|
||||
if m := noteMasked(r, "chat", maskedHits, string(body), tr.ID, "openai", model); m != nil {
|
||||
s.trace.update(tr, func(t *Route) { t.Masked = m })
|
||||
@@ -1046,7 +1046,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
try.Millis, try.Again = time.Since(try.Start).Milliseconds(), wait.Milliseconds()
|
||||
})
|
||||
servedProvider, servedAccount := codexServed(base, r.Header, on)
|
||||
rec := usage.Record{RouteID: tr.ID, Time: began, Agent: agentOf(r), Provider: servedProvider, Host: provider.HostOf(base),
|
||||
rec := usage.Record{RouteID: tr.ID, Time: began, Agent: callerOf(r).agent, Provider: servedProvider, Host: provider.HostOf(base),
|
||||
ProviderAccount: servedAccount, Model: modelOf(body), Requested: modelOf(body), Effort: effort,
|
||||
Millis: time.Since(began).Milliseconds(), Status: status, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header),
|
||||
Kind: kind, Endpoint: r.URL.Path, HandedOn: true}
|
||||
@@ -1228,7 +1228,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
writeError(w, provider.Responses, res.StatusCode, codexKeyRefused(msg))
|
||||
s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
|
||||
Provider: "openai", Agent: agentOf(r), Status: res.StatusCode,
|
||||
Provider: "openai", Agent: callerOf(r).agent, Status: res.StatusCode,
|
||||
Millis: time.Since(start).Milliseconds(), Error: res.Status})
|
||||
end(res.StatusCode, res.Status, 0, 0)
|
||||
return
|
||||
@@ -1251,7 +1251,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
// (outrageous_piglet on Discord), went
|
||||
failWith(res.StatusCode, said)
|
||||
s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
|
||||
Provider: "openai", Agent: agentOf(r), Kind: callKind(r.Header), Status: res.StatusCode,
|
||||
Provider: "openai", Agent: callerOf(r).agent, Kind: callKind(r.Header), Status: res.StatusCode,
|
||||
Millis: time.Since(start).Milliseconds(), Error: said})
|
||||
end(res.StatusCode, said, 0, 0)
|
||||
return
|
||||
@@ -1352,7 +1352,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
return
|
||||
}
|
||||
call := Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
|
||||
Provider: "openai", Agent: agentOf(r), Kind: kind, Status: res.StatusCode,
|
||||
Provider: "openai", Agent: callerOf(r).agent, Kind: kind, Status: res.StatusCode,
|
||||
Millis: time.Since(start).Milliseconds(), Fallback: resetNote}
|
||||
if len(tried) > 0 {
|
||||
// the overloads it was asked again for, before the one that answered
|
||||
|
||||
@@ -164,7 +164,7 @@ func (s *Server) alphaSearchOn(w http.ResponseWriter, r *http.Request, body []by
|
||||
}
|
||||
noteSignIn(ctx, on.Account, req, res)
|
||||
c := Call{Time: start, From: provider.Responses, To: provider.Responses, Model: model, Provider: on.ID,
|
||||
Agent: agentOf(r), Kind: "web_search", Status: res.StatusCode}
|
||||
Agent: callerOf(r).agent, Via: callerOf(r).via, Kind: "web_search", Status: res.StatusCode}
|
||||
if res.StatusCode < 200 || res.StatusCode > 299 {
|
||||
msg, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10))
|
||||
res.Body.Close()
|
||||
|
||||
@@ -532,7 +532,8 @@ func (s *Server) answeredHere(r *http.Request, from provider.Protocol, body []by
|
||||
kind := requestCallKind(r.Header, metadata)
|
||||
model := modelOf(body)
|
||||
seat := Weighed{ID: "magpie", Provider: "magpie", Name: "magpie", Who: who, Kind: "provider", Model: model}
|
||||
tr := s.trace.beginFor(r, Route{Time: start, Agent: agentOf(r), Session: sessionOf(r.Header), ParentSession: titleParentSession(r.Header, metadata, kind),
|
||||
by := callerOf(r) // as it is recorded: another magpie's agent by its own name
|
||||
tr := s.trace.beginFor(r, Route{Time: start, Agent: by.agent, Session: sessionOf(r.Header), ParentSession: titleParentSession(r.Header, metadata, kind),
|
||||
Kind: kind, Model: model, Provider: "magpie", Order: []Weighed{seat}, Tries: []Try{{ID: seat.ID, Model: model, Start: start}}})
|
||||
write()
|
||||
ms := time.Since(start).Milliseconds()
|
||||
@@ -541,8 +542,8 @@ func (s *Server) answeredHere(r *http.Request, from provider.Protocol, body []by
|
||||
t.Done, t.Status, t.Error, t.Millis = true, 200, why, ms
|
||||
})
|
||||
s.record(Call{Route: tr.ID, Time: start, From: from, To: from, Model: model, Provider: "magpie",
|
||||
Agent: agentOf(r), Kind: kind, Status: 200, Millis: ms, Error: why})
|
||||
appendUsage(r, usage.Record{RouteID: tr.ID, Time: start, Agent: agentOf(r), Provider: "magpie", Model: model, Requested: model,
|
||||
Agent: by.agent, Via: by.via, Kind: kind, Status: 200, Millis: ms, Error: why})
|
||||
appendUsage(r, usage.Record{RouteID: tr.ID, Time: start, Agent: by.agent, Via: by.via, Provider: "magpie", Model: model, Requested: model,
|
||||
Millis: ms, Status: 200, Rejected: true, Error: why, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header),
|
||||
Kind: kind, Endpoint: r.URL.Path})
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ func noteMaskedUntil(r *http.Request, what string, h maskHits, sent string, rout
|
||||
}
|
||||
rec := maskrec.Record{What: what, Route: route, Provider: prov, Model: model, N: h.n}
|
||||
if r != nil {
|
||||
rec.Agent, rec.Session = agentOf(r), sessionOf(r.Header)
|
||||
rec.Agent, rec.Session = callerOf(r).agent, sessionOf(r.Header)
|
||||
}
|
||||
rec.Values = valuesOf(h.hits)
|
||||
rec.Snips = snipsOf(sent, h.hits)
|
||||
|
||||
@@ -25,7 +25,8 @@ func observeRequest(r *http.Request, kind string, body []byte) (*http.Request, *
|
||||
if len(observers) == 0 {
|
||||
return r, nil
|
||||
}
|
||||
agent := agentOf(r)
|
||||
// the agent it is recorded as, another magpie's own (callerFrom)
|
||||
agent := callerOf(r).agent
|
||||
q := usage.Request{Header: r.Header, Agent: agent, Session: observedSession(r.Header), Kind: observedKind(agent, kind, body),
|
||||
Plain: local(r) && access.Caller(r.Context()).KeyID == "" && callerOf(r).via == ""}
|
||||
o := &observed{}
|
||||
|
||||
@@ -52,26 +52,7 @@ type callerCtx struct{}
|
||||
// headers that said so off it.
|
||||
func withCaller(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
c := caller{agent: agentOf(r), session: boundedSession(r.Header.Get(SessionHeader)), ua: r.Header.Get("User-Agent")}
|
||||
if dshCompacts(r.Header) {
|
||||
c.compact = boundedSession(r.Header.Get(dshCompactHeader))
|
||||
}
|
||||
for _, h := range sessionHeaders {
|
||||
if v := boundedSession(r.Header.Get(h)); v != "" {
|
||||
c.native = [2]string{h, v}
|
||||
break
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(r.Header.Get("User-Agent"), "magpie/") {
|
||||
if a := label(r.Header.Get(AgentHeader)); a != "" {
|
||||
c.agent = usage.AgentOf(a)
|
||||
c.via = label(r.Header.Get(ViaHeader))
|
||||
if c.via == "" {
|
||||
c.via, _, _ = net.SplitHostPort(r.RemoteAddr)
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), callerCtx{}, c)
|
||||
ctx := context.WithValue(r.Context(), callerCtx{}, callerFrom(r))
|
||||
if searchingFrom(r) {
|
||||
// another magpie's search: only the model itself searches
|
||||
ctx = context.WithValue(ctx, searchingKey{}, true)
|
||||
@@ -83,6 +64,35 @@ func withCaller(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// callerFrom reads who r is recorded as from its headers, before withCaller
|
||||
// takes magpie's own off: the one rule for every place that names a
|
||||
// request's agent (usage, sessions, the routing trace, the masking log,
|
||||
// the requests in flight), so another magpie's request is shown as the
|
||||
// agent that made it there, never as "magpie" (linkaww on Discord: the
|
||||
// masking log named magpie where usage named Pi).
|
||||
func callerFrom(r *http.Request) caller {
|
||||
c := caller{agent: agentOf(r), session: boundedSession(r.Header.Get(SessionHeader)), ua: r.Header.Get("User-Agent")}
|
||||
if dshCompacts(r.Header) {
|
||||
c.compact = boundedSession(r.Header.Get(dshCompactHeader))
|
||||
}
|
||||
for _, h := range sessionHeaders {
|
||||
if v := boundedSession(r.Header.Get(h)); v != "" {
|
||||
c.native = [2]string{h, v}
|
||||
break
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(r.Header.Get("User-Agent"), "magpie/") {
|
||||
if a := label(r.Header.Get(AgentHeader)); a != "" {
|
||||
c.agent = usage.AgentOf(a)
|
||||
c.via = label(r.Header.Get(ViaHeader))
|
||||
if c.via == "" {
|
||||
c.via, _, _ = net.SplitHostPort(r.RemoteAddr)
|
||||
}
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// callerOf is who the request is recorded as.
|
||||
func callerOf(r *http.Request) caller {
|
||||
if c, ok := r.Context().Value(callerCtx{}).(caller); ok {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/maskrec"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// A request another magpie passed on is named in this magpie's masking log
|
||||
// by the agent that made it there, as its usage names it, not as "magpie"
|
||||
// (linkaww on Discord: Pi's request through a local magpie was logged on
|
||||
// the remote as magpie's). A client that isn't a magpie can't name another
|
||||
// agent with magpie's header: it is logged as itself.
|
||||
func TestRemoteMagpieMaskedNamesTheAgent(t *testing.T) {
|
||||
const key = "sk-proj-abcdEFGH1234ijklMNOP5678qrst"
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"id":"c1","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`)
|
||||
}))
|
||||
defer up.Close()
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := settings.Save(settings.Settings{Redact: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
logged := func(h map[string]string) maskrec.Record {
|
||||
t.Helper()
|
||||
before, _ := maskrec.List(0, 1, maskrec.Filter{})
|
||||
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"fake/m1","messages":[{"role":"user","content":"key `+key+`"}]}`))
|
||||
for k, v := range h {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
rs, _ := maskrec.List(0, 1, maskrec.Filter{})
|
||||
if len(rs) != 1 || len(before) == 1 && rs[0].Key == before[0].Key {
|
||||
t.Fatalf("nothing recorded: %+v", rs)
|
||||
}
|
||||
return rs[0]
|
||||
}
|
||||
// what a magpie sends on for Pi (passOnCaller)
|
||||
if r := logged(map[string]string{"User-Agent": "magpie/0.1.0", AgentHeader: "pi", ViaHeader: "laptop"}); r.Agent != "pi" {
|
||||
t.Errorf("another magpie's request for Pi is logged as %q, want pi", r.Agent)
|
||||
}
|
||||
if r := logged(map[string]string{"User-Agent": "curl/8.0", AgentHeader: "pi"}); r.Agent != "curl" {
|
||||
t.Errorf("a client's own %s was taken: logged as %q, want curl", AgentHeader, r.Agent)
|
||||
}
|
||||
}
|
||||
|
||||
// The requests in flight (/v1/magpie/concurrency) name another magpie's
|
||||
// request by its agent too: they are counted before withCaller runs.
|
||||
func TestRemoteMagpieActiveNamesTheAgent(t *testing.T) {
|
||||
s := New()
|
||||
req := httptest.NewRequest("POST", "/v1/chat/completions", nil)
|
||||
req.Header.Set("User-Agent", "magpie/0.1.0")
|
||||
req.Header.Set(AgentHeader, "pi")
|
||||
_, done := s.active.add(req)
|
||||
defer done()
|
||||
if as := s.Active(); len(as) != 1 || as[0].Agent != "pi" {
|
||||
t.Errorf("in flight: %+v, want pi's", as)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user