gateway: the request archive doesn't put an unmasked route back on masking (#3973)

wangbinyq (#3973, Discord #feedback): after v0.1.1840, with the request
archive on, a request to a provider set to go unmasked was still masked
whole before it was sent. ea53eb126 skipped masking only when
bodiesKeptAway() was false (internal/gateway/redact.go:272, called at
gateway.go:1947), and that was true whenever archiveDest() was on, or an
observer wanted bodies, so the archive put the masking pass back on
every request's way, the masked copy kept only for the archive.

Now an unmasked route is never masked on its way, whatever is on:
- The archive keeps the request as it went, as the log and recent calls
  do. Its secrets are taken out by redact.ScrubJSON in the background
  upload, as every archived body's are; the reply half was already as
  the local model wrote it.
- An observer that wants bodies (OTLP export, a JS plugin's) is handed
  them masked as before, masked once when withBodies first hands them
  over after a try (Call.maskIn, laterMasked), not before the send.
- bodiesKeptAway and serve's masked/plain swap are gone. count_tokens,
  embeddings, Jev and web search never read the archive switch.

docs/subsystems/gateway-routing.md says so.

Run on mote at this tree (rebased onto 6bec526f7):
- gofmt -l internal: none. GOOS=linux/windows go vet -tags nogui
  ./internal/gateway: ok (before the rebase, no gateway change since
  but upstream's own).
- go test -tags nogui -count=1 -timeout 45m ./...: 76 ok, no FAIL.
  (A run at the older base had TestPluginStreamsPastTheBudgetWait red,
  red alone too there; fixed upstream in 7fd77a944, green at this head.)
- Rebased again onto 9e33962c0 before the push (26 files, none in
  internal/gateway): go build -tags nogui ./... ok, and
  TestUnmaskedRouteIsNotMasked, TestArchive*, TestObserver*,
  TestPromptText* ok at the pushed head.
- TestUnmaskedRouteIsNotMasked gains "the request archive is on" and
  "the archive is on, unset", and checks what the observer and the
  bucket get.
- Broken by hand: with origin/main's gateway.go, redact.go and
  capture.go, "the request archive is on" is red ("masked 1 times,
  want masking false") and the observer case red (log masked).

Not run: a real magpie serve with the archive on against a local model
(ea53eb126's sandbox benchmark covers the archive-off case); a real S3
bucket; the GUI suite (no GUI file changed).
This commit is contained in:
yetone
2026-10-28 16:53:54 +08:00
parent e23ddddd5b
commit 7fcf642eed
5 changed files with 83 additions and 45 deletions
File diff suppressed because one or more lines are too long
+7
View File
@@ -155,6 +155,13 @@ func withBodies(rec *usage.Record, c *Call) {
if c.wholeIn != nil {
in, inCut = string(c.wholeIn), c.wholeInCut
}
if c.maskIn != nil {
if m := c.maskIn.body(); c.wholeIn != nil {
in = string(m)
} else {
in, inCut = captureRequestBody(m)
}
}
out, outCut := c.ResponseBody, c.ResponseTruncated
if c.wholeOut != nil {
out, outCut = string(c.wholeOut), c.wholeOutCut
+18 -27
View File
@@ -405,6 +405,9 @@ type Call struct {
// bodies above, which is all the Recent-calls page keeps
wholeIn, wholeOut []byte
wholeInCut, wholeOutCut bool
// maskIn: the request went as written (unredactedRoute) with masking
// on, so an observer is handed its body masked here, not as it went
maskIn *laterMasked
}
// Server is the gateway.
@@ -1701,12 +1704,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// secrets go as placeholders and come back as they were; the log has
// what the vendor saw and said. plain is the body as the agent wrote
// it, for a request that goes only where the user said it may go
// unmasked (unredactedRoute)
// unmasked (unredactedRoute). The body is masked once the route is
// known (below): one that goes as written isn't masked at all, where
// masking it took up to minutes for nothing (#3973)
// known (below): one that goes as written isn't masked on its way,
// where masking it took up to minutes for nothing (#3973)
plain := body
var masked []byte // the masked body, when plain goes instead
var maskedHits maskHits
maskDone, sentWhole := false, false
unmask := func() {}
@@ -1941,10 +1942,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
g, ms, isGroup := provider.FindGroup(asked)
g = g.Live() // a manual group's rules wait
// a model on this machine or the local network that the user set to
// go unmasked gets the request as written (lc on Discord), and it is
// masked only for an observer or the archive, which may keep it
// elsewhere
if sentWhole = unredactedRoute(p, isGroup, ms) && !bodiesKeptAway(); !sentWhole {
// go unmasked gets the request as written (lc on Discord), and it
// isn't masked on its way, the request archive on or not: the archive
// keeps it as it went, its secrets taken out as every archived body's
// are, and an observer that wants the bodies is handed a copy masked
// when it is first handed one, after the try (maskIn, #3973)
if sentWhole = unredactedRoute(p, isGroup, ms); !sentWhole {
rw, b, done, hits, err := redactedHits(r.Context(), capture.ResponseWriter, body)
if err != nil { // fails closed: never sent unmasked
log.Printf("gateway: %v", err)
@@ -1953,16 +1956,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
return
}
capture.ResponseWriter, body, unmask, maskedHits = rw, b, done, hits
if unredactedRoute(p, isGroup, ms) {
masked, body = body, plain
}
} else if usage.ObservedBodies() != usage.NoBodies {
call.maskIn = &laterMasked{ctx: context.WithoutCancel(r.Context()), plain: body}
}
maskDone = true
if masked != nil {
logBody(masked)
} else {
logBody(body)
}
logBody(body)
// a gateway key held to some models (#882) is refused another, or a
// group it doesn't name with one it may not use in it
keyWho, keyHeld := keyHolds(r)
@@ -2037,9 +2035,6 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// text (#1613)
if b, ok := withoutSealedMessages(body); ok {
body = b
if masked != nil {
masked, _ = withoutSealedMessages(masked)
}
sealedTask = hasSealedAgentMessage(body)
}
}
@@ -2463,7 +2458,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// request went as written. The record names the provider and model
// the last try went to, not the group's first member, which a
// failover may never have reached
if masked == nil && !sentWhole {
if !sentWhole {
m, done := noteMaskedUntil(r, "chat", maskedHits, string(body), tr.ID, p.ID, call.Model)
if m != nil {
s.trace.update(tr, func(t *Route) { t.Masked = m })
@@ -2472,11 +2467,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
}
// the card's text is the masked body, even where the request went
// unmasked: masked by PromptText when it went whole (#3973)
textBody := body
if masked != nil {
textBody = masked
}
promptRead := s.inspectPrompt(tr, from, body, textBody, sentWhole)
promptRead := s.inspectPrompt(tr, from, body, body, sentWhole)
var lastTried provider.Provider // the last try's, for its model's context window and the usage's endpoint
var skipped []string
sent := "" // the reasoning the last try's model was asked for
@@ -3210,7 +3201,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
failedWith(&rec, call.Status, call.Error, call.Usage.ErrType)
// what this account answered is its refusal, the reply
// captured so far being no one's yet
refusal := &Call{RequestBody: call.RequestBody, RequestTruncated: call.RequestTruncated, ResponseBody: string(hw.errBody())}
refusal := &Call{RequestBody: call.RequestBody, RequestTruncated: call.RequestTruncated, ResponseBody: string(hw.errBody()), maskIn: call.maskIn}
if call.wholeIn != nil {
refusal.wholeIn, refusal.wholeOut = call.wholeIn, hw.errBody()
}
@@ -3254,7 +3245,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
failedWith(&rec, call.Status, call.Error, call.Usage.ErrType)
// what this account answered is its refusal, the reply
// captured so far being no one's yet
refusal := &Call{RequestBody: call.RequestBody, RequestTruncated: call.RequestTruncated, ResponseBody: string(hw.errBody())}
refusal := &Call{RequestBody: call.RequestBody, RequestTruncated: call.RequestTruncated, ResponseBody: string(hw.errBody()), maskIn: call.maskIn}
if call.wholeIn != nil {
refusal.wholeIn, refusal.wholeOut = call.wholeIn, hw.errBody()
}
+17 -11
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"net/http"
"sync"
"time"
"github.com/yetone/magpie/internal/gwmw"
@@ -12,7 +13,6 @@ import (
"github.com/yetone/magpie/internal/maskrec"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/usage"
)
// redacted masks a request's secrets, as the settings say, before it goes
@@ -265,16 +265,22 @@ func maskedCopy(ctx context.Context, body []byte) []byte {
return b
}
// bodiesKeptAway says a request's body may be kept off this computer: an
// observer wants it (the OTLP export, a JS plugin's observer) or the
// request archive is on. A request sent unmasked is masked for them all
// the same.
func bodiesKeptAway() bool {
if usage.ObservedBodies() != usage.NoBodies {
return true
}
_, on := archiveDest()
return on
// laterMasked is the body of a request that went as written, masked the
// first time an observer is handed it (withBodies): after its try, never
// on its way (#3973). nil when masking fails: nothing unmasked is handed
// on in its place.
type laterMasked struct {
once sync.Once
ctx context.Context
plain []byte
b []byte
}
func (l *laterMasked) body() []byte {
l.once.Do(func() {
l.b, l.plain = maskedCopy(l.ctx, l.plain), nil
})
return l.b
}
// unredactedRoute says a request resolved to p, or to the group whose
+40 -6
View File
@@ -1,6 +1,7 @@
package gateway
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
@@ -34,22 +35,29 @@ func (c countedMasker) Writer(w http.ResponseWriter) (http.ResponseWriter, func(
// unmasked was masked all the same before it was routed, and the masked
// body thrown away, up to minutes of magpie's own time for each. Now it
// isn't masked at all, a chat or a token count, and the log has it as it
// went; one that goes to a vendor, an unknown model's, or one an observer
// keeps the bodies of is masked as before.
// went; one that goes to a vendor, or an unknown model's, is masked as
// before. With the request archive on it was masked all the same (#3973,
// wangbinyq: 请求归档开启的话, 还是会先走脱敏路径): the archive keeps it as
// it went now. An observer that keeps the bodies is handed them masked,
// masked after the try instead of before it.
func TestUnmaskedRouteIsNotMasked(t *testing.T) {
const key = "sk-proj-abcdEFGH1234ijklMNOP5678qrst"
const placeholder = "{{API_KEY_" // the key masked; the archive and an export take it out otherwise
chat := `{"model":"fake/m1","max_tokens":10,"messages":[{"role":"user","content":"my key is ` + key + `"}]}`
count := `{"model":"fake/m1","messages":[{"role":"user","content":"my key is ` + key + `"}]}`
cases := []struct {
name string
set bool
observed bool
archived bool
masks bool // the masker is asked
whole bool // the provider is sent the key
}{
{name: "set to go unmasked", set: true, whole: true},
{name: "unset", masks: true},
{name: "an observer keeps the bodies", set: true, observed: true, masks: true, whole: true},
{name: "the request archive is on", set: true, archived: true, whole: true},
{name: "the archive is on, unset", archived: true, masks: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
@@ -63,11 +71,17 @@ func TestUnmaskedRouteIsNotMasked(t *testing.T) {
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
if err := settings.Save(settings.Settings{Redact: true}); err != nil {
if err := settings.Save(settings.Settings{Redact: true, RequestArchive: tc.archived}); err != nil {
t.Fatal(err)
}
obs := &fakeObserver{watch: true, bodies: usage.CapturedBodies}
if tc.observed {
t.Cleanup(usage.Observe(&fakeObserver{bodies: usage.CapturedBodies}))
t.Cleanup(usage.Observe(obs))
}
bucket := &memBucket{objs: map[string][]byte{}}
if tc.archived {
t.Setenv("TMPDIR", t.TempDir())
archiveTo(t, bucket)
}
withoutMasker(t)
n := new(atomic.Int64)
@@ -85,12 +99,32 @@ func TestUnmaskedRouteIsNotMasked(t *testing.T) {
t.Fatalf("masked %d times, want masking %v", n.Load(), tc.masks)
}
c := s.Recent()[0]
if logged := strings.Contains(c.RequestBody, key); logged != !tc.masks {
t.Fatalf("the log has the key %v, want %v: %s", logged, !tc.masks, c.RequestBody)
if logged := strings.Contains(c.RequestBody, key); logged != tc.whole {
t.Fatalf("the log has the key %v, want %v: %s", logged, tc.whole, c.RequestBody)
}
if c.RequestBody == "" {
t.Fatal("the log has no body")
}
if tc.observed {
obs.mu.Lock()
got := obs.attempts
obs.mu.Unlock()
if len(got) == 0 || !strings.Contains(got[0].BodyIn, placeholder) || strings.Contains(got[0].BodyIn, key) {
t.Fatalf("the observer was handed %+v", got)
}
}
if tc.archived {
archivePending.Wait()
var a Archived
if err := json.Unmarshal(bucket.objs["archive/"+c.Archive+".json"], &a); err != nil {
t.Fatalf("%v: %v", keys(bucket.objs), err)
}
// as it went: masked, or as written save the secrets every
// archived body has taken out
if masked := strings.Contains(a.Request.Body, placeholder); masked == tc.whole || a.Request.Body == "" || strings.Contains(a.Request.Body, key) {
t.Fatalf("the archive kept %s", a.Request.Body)
}
}
n.Store(0)
f.reply = `{"input_tokens":17}`
if code, reply := post(t, "/v1/messages/count_tokens", count); code != 200 {