gateway: what Jev is told of a turn is masked unless Jev itself may have it unmasked
A routing group whose every member the user set to go unmasked
(unredactedRoute, provider.SkipsRedaction) hands its rules the body as the
agent wrote it. That was right for the members, but a group's Jev is none
of them: askJev sent the message, and since the commit before also the
user's message before it and the reply, to a remote decision provider
unmasked. The chat-model classifier was not affected (it goes through
serve, which masks).
askJev now masks the state's three texts with maskedText (maskedState)
unless Jev's own provider skips redaction, and fails closed when the
masker can't serve, as redacted does. Found by the agent writing the
commit before, on reading unredactedRoute's callers.
TestJevIsToldTheTurnMaskedWhenTheGroupGoesUnmasked: both members
Unredacted on local addresses, mask personal data on, an email in the
message and the one before; no state value Jev gets holds it. Broken by
hand (the SkipsRedaction check made `false &&`): red, "previous_user_message
went to Jev unmasked". gateway-routing.md says it beside unredactedRoute.
Full suite at bf2018807 (89521b03d + both commits): go test -p 3 -tags nogui -timeout 45m ./... under a sandbox HOME: 65 packages ok, gateway among them; internal/agent hit the 45m timeout (#2544, as on main under load ~330). gofmt -l clean; go vet -tags nogui, GOOS=windows go vet of internal/gateway ok.
This commit is contained in:
@@ -74,7 +74,7 @@ recorded as a prediction failure (`noPrediction`).
|
||||
## Runtime path
|
||||
|
||||
1. `handle(proto)` reads the body and the model (`requestBody`, `requestModel`), then calls `serveAgent`. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it through `readBoundedRequestBody` in [`request_bounds.go`](../../internal/gateway/request_bounds.go). It decodes a `Content-Encoding` of `gzip` or `zstd` (`decodedBody`; Codex sends zstd to a custom provider's `/v1/responses` too, #1223) and drops the header, so the provider is sent plain JSON, with one exception: a ChatGPT account's turn (POST `CodexBase`/responses, from the accounts loop in `forwardOnce` or relayed by `codexUpstreamOn`) is compressed again with zstd, as Codex's own client sends it (`provider.CodexCompressed`; openai/codex `responses_request_compression`). It is compressed once the body is final, and again on each try. `/responses/compact`, an API key's requests and every other provider stay plain. Sent plain, a 1.1 MB text-only turn was answered 503 (ylorn on X). The plain body is what magpie keeps and shows, and `codexDropped` judges a reset by the bytes that went on the wire. `codexDropped` also reads Envoy's 507 "exceeded request buffer limit while retrying upstream" (the backend failed and the front couldn't retry a body that large) as that reset, at any size, told as a 503 so magpie, Codex and pi ask again and nobody rests (#2034). The size limit (`defaultBodyLimit`, 512 MB) holds for the decoded bytes (413), and any other encoding is refused 415. It was 128 MB until a long Codex session that had read many images went past it decoded, its inline screenshots resent each turn, and got the 413 on all five of Codex's retries (#1422, `TestImageHeavyCodexTurnIsRead`). magpie's own 413 says it is magpie's gateway limit, with the size, and that the provider was not asked (`overLimit`); `writeError` adds to any 413 it isn't holding that this is a byte limit, not the model's context, and to `/compact` or start a new conversation (`TestOverLimitSaysWhoseAndWhatToDo`). Every shape but Gemini's types a 413 `request_too_large`, Anthropic's own type, which pi's overflow table knows: pi compacts and tries once more rather than stopping on an OpenAI-shaped `api_error` (@wilsonxuuuu on X, `TestPayloadTooLargeSaysRequestTooLargeToPi`). `keyLimited` reads a limited key's compressed body the same way, so its reservation is the decoded size. `serveAgent` runs the [middleware](gateway-middleware.md) chain, then `serve`.
|
||||
2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone; the request's tool definitions and output schemas, found by their place in each protocol (top-level `tools`, `tool_choice`, `response_format`, `text`, `generationConfig` and the like, and the tools of a Responses `additional_tools` or `tool_search_output` item), go as written save their descriptions, so a word the user masks can't break a grammar or an enum (#1911); and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, `redact/known.go`), resolves the model to a provider or a group, and refuses what can't be served. The reply has the values put back on its way to the agent (`redact.Writer`, a stream event by event, a whole body at its end): a placeholder the model wrote as it was given, or as models rewrite one (spaces inside the braces, a brace or both dropped, another case), is the value again when what is left names one magpie made, and one split across events is held until it is whole (`redact.Restore`, `partialTail`, [`internal/redact/redact.go`](../../internal/redact/redact.go)). A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, with every address on this machine or the local network) goes to them as the agent wrote it; the log and recent calls keep the masked body. count_tokens and embeddings follow the same rule. The masking is the built-in plugin `redact`'s (`gwmw.Masker`, [Plugin runtime](plugin-runtime.md)); when the settings ask for masking and no masker serves, or it fails, the request is a 503 and nothing is sent (`redacted`, `gwmw.Masking`).
|
||||
2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone; the request's tool definitions and output schemas, found by their place in each protocol (top-level `tools`, `tool_choice`, `response_format`, `text`, `generationConfig` and the like, and the tools of a Responses `additional_tools` or `tool_search_output` item), go as written save their descriptions, so a word the user masks can't break a grammar or an enum (#1911); and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, `redact/known.go`), resolves the model to a provider or a group, and refuses what can't be served. The reply has the values put back on its way to the agent (`redact.Writer`, a stream event by event, a whole body at its end): a placeholder the model wrote as it was given, or as models rewrite one (spaces inside the braces, a brace or both dropped, another case), is the value again when what is left names one magpie made, and one split across events is held until it is whole (`redact.Restore`, `partialTail`, [`internal/redact/redact.go`](../../internal/redact/redact.go)). A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, with every address on this machine or the local network) goes to them as the agent wrote it; the log and recent calls keep the masked body. count_tokens and embeddings follow the same rule. What a routing group's Jev is told of the turn (the message, the user's message before it and the reply to it) is masked all the same unless Jev's own provider skips redaction too (`maskedState` in `askJev`, [`decide.go`](../../internal/gateway/decide.go)): a remote Jev is none of the group's members. The masking is the built-in plugin `redact`'s (`gwmw.Masker`, [Plugin runtime](plugin-runtime.md)); when the settings ask for masking and no masker serves, or it fails, the request is a 503 and nothing is sent (`redacted`, `gwmw.Masking`).
|
||||
- With *Mask personal data* on, each kind in `redact.Categories` ([`internal/redact/more.go`](../../internal/redact/more.go)) is masked unless the user turned it off (`redactKinds` in settings, `Options.Kinds`). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so, MAC addresses, and serial numbers next to S/N or the like. Off by default: the user name in a home folder, user@host in a prompt or ssh command, public IPv4 and IPv6 addresses (never private, loopback, link-local, CGNAT or documentation ranges) and cloud bucket names, since agents send them in nearly every request and the model must copy the placeholder exactly inside a path or URL. Context rules run only near their words (`rule.matches`). The Settings rows come from `REDACT_KINDS` in app.js, which `TestRedactKindsAreRedacts` holds to the same ids and defaults.
|
||||
- With *Mask secrets* on, the user's own masking rules (`redactRules`, `redact.Rule`: a placeholder name and a prefix or an RE2 pattern, [`internal/redact/rules.go`](../../internal/redact/rules.go)) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (`POST /api/settings/redact-rule` with the rule's index and its current value, `editRedactRule` in [`internal/gui/api.go`](../../internal/gui/api.go)). Every rule is checked by `redact.CheckRules` when settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The gateway reads the rules from settings on each request (`redactionOptions`), so a change applies to the next request.
|
||||
- `DecidesModel` gives a 400.
|
||||
|
||||
@@ -233,3 +233,37 @@ func TestJevSeesTheTurnBefore(t *testing.T) {
|
||||
t.Fatalf("previous_user_message %q", u)
|
||||
}
|
||||
}
|
||||
|
||||
// A group whose every member the user set to go unmasked hands its rules
|
||||
// the body as the agent wrote it; Jev, which isn't one of them, is still
|
||||
// told the turn masked.
|
||||
func TestJevIsToldTheTurnMaskedWhenTheGroupGoesUnmasked(t *testing.T) {
|
||||
s, _, _, j := jevved(t, "", provider.Rule{Use: "b/big", Intent: "debugging"})
|
||||
if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, id := range []string{"a/small", "b/big"} {
|
||||
p, _, ok := provider.Resolve(id)
|
||||
if !ok {
|
||||
t.Fatalf("no %s", id)
|
||||
}
|
||||
p.Unredacted = true
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p, _, _ := provider.Resolve(id); !p.SkipsRedaction() {
|
||||
t.Fatalf("%s doesn't skip redaction", id)
|
||||
}
|
||||
}
|
||||
postOK(t, s, "s1", chat("mail moon.shard@proton.me why the parser crashes", []string{"tell sun.ray@proton.me 继续"}, 0, ""))
|
||||
turns := j.turns()
|
||||
st := turns[len(turns)-1]["state"].(map[string]any)
|
||||
for k, v := range st {
|
||||
if s, _ := v.(string); strings.Contains(s, "@proton.me") {
|
||||
t.Fatalf("%s went to Jev unmasked: %q", k, s)
|
||||
}
|
||||
}
|
||||
if u, _ := st["previous_user_message"].(string); !strings.Contains(u, "why the parser crashes") {
|
||||
t.Fatalf("state %v", st)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -357,6 +357,16 @@ func (s *Server) askJev(p provider.Provider, model string, intents []string, pre
|
||||
if model == "" {
|
||||
model = p.Jev()
|
||||
}
|
||||
// what Jev reads goes masked unless Jev is itself where the user set
|
||||
// requests to go unmasked: a group whose every member skips redaction
|
||||
// hands rules the body as the agent wrote it (unredactedRoute), and a
|
||||
// remote Jev is none of those members
|
||||
if !p.SkipsRedaction() {
|
||||
var err error
|
||||
if text, prev.User, prev.Reply, err = maskedState(text, prev.User, prev.Reply); err != nil {
|
||||
return verdict{}, err // fails closed: never sent unmasked
|
||||
}
|
||||
}
|
||||
var l levelling
|
||||
if len(intents) > 1 { // one kind is a topic: a message may be none of it
|
||||
var err error
|
||||
@@ -371,6 +381,22 @@ func (s *Server) askJev(p provider.Provider, model string, intents []string, pre
|
||||
return readJev(b, intents, l.levels, prev)
|
||||
}
|
||||
|
||||
// maskedState masks what Jev is told of a turn, each as maskedText does.
|
||||
func maskedState(text, user, reply string) (string, string, string, error) {
|
||||
out := [3]string{text, user, reply}
|
||||
for i, v := range out {
|
||||
if v == "" {
|
||||
continue
|
||||
}
|
||||
m, _, err := maskedText(v)
|
||||
if err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
out[i] = m
|
||||
}
|
||||
return out[0], out[1], out[2], nil
|
||||
}
|
||||
|
||||
// systemOne posts body to p's System One API and returns the answer,
|
||||
// counting it in the usage as magpie's own. A gateway serving Jev is asked
|
||||
// and answers in its own way (decideAsk, decideAnswer).
|
||||
|
||||
Reference in New Issue
Block a user