diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index a635b43e5..0a8f2b56f 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -47,7 +47,7 @@ foreign sealed history or repair ChatGPT's response protection. ## 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. 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`). `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. 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. +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. - 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. diff --git a/internal/redact/redact.go b/internal/redact/redact.go index f7bdb1007..5a9e9c8da 100644 --- a/internal/redact/redact.go +++ b/internal/redact/redact.go @@ -243,6 +243,7 @@ func luhn(v string) bool { var ( mu sync.RWMutex values = map[string]string{} // placeholder → value + kinds = map[string]bool{} // the kinds of values, for wordTail keyOf []byte keyPath string // guarded by mu, as keyOf is ) @@ -313,6 +314,7 @@ func placeholder(kind, v string) string { reindexKnown() } values[p] = v + kinds[kind] = true addKnown(p, v) } mu.Unlock() @@ -550,24 +552,94 @@ func containsAny(s string, subs []string) bool { // ---- restoring ------------------------------------------------------------------ +// placeholderBody is a placeholder without its braces, as a model may write +// one back: API_KEY_k3v9x2mq, phone_b5puzbfv, PHONE_B5PUZBFV. +var placeholderBody = regexp.MustCompile(`[A-Za-z][A-Za-z0-9_]*_[A-Za-z2-7]{8}`) + // Restore puts the values back in s. escaped is for text that is itself // JSON (a tool call's arguments), where a value goes in escaped. +// +// A model doesn't always write a placeholder back as it was given: it +// writes {{ PHONE_b5puzbfv }} as a template has it, drops a brace, or the +// braces, or changes the case. Any of those is put back too when what is +// left names a placeholder this magpie made: its kind and the 8 of its +// hash, which no other text has by chance (shensmart on Discord). func Restore(s string, escaped bool) string { - if !strings.Contains(s, "{{") { + if !strings.Contains(s, "_") { return s } mu.RLock() defer mu.RUnlock() - return placeholderRe.ReplaceAllStringFunc(s, func(p string) string { - v, ok := values[p] + if len(values) == 0 { + return s + } + var b strings.Builder + last := 0 + for _, m := range placeholderBody.FindAllStringIndex(s, -1) { + a, z := m[0], m[1] + if a < last || a > 0 && isWordByte(s[a-1]) || z < len(s) && isWordByte(s[z]) { + continue + } + v, ok := values[canonical(s[a:z])] if !ok { - return p + continue } + a, z = braces(s, a, z) + if a < last { + continue + } + b.WriteString(s[last:a]) if escaped { - return jsonEscape(v) + v = jsonEscape(v) } - return v - }) + b.WriteString(v) + last = z + } + if last == 0 { + return s + } + b.WriteString(s[last:]) + return b.String() +} + +// canonical is the placeholder Mask wrote for body, whatever its case. +func canonical(body string) string { + cut := len(body) - 8 + return "{{" + strings.ToUpper(body[:cut]) + strings.ToLower(body[cut:]) + "}}" +} + +func isWordByte(c byte) bool { + return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_' +} + +// braces widens s[a:z], a placeholder's body, over the braces the model +// wrote around it, and the spaces inside them: both of {{ and }}, or one +// of them dropped ({{X} or {X}}), or just {{ or just }}. A single brace +// on one side alone is the text's own ({X as in code) and stays. +func braces(s string, a, z int) (int, int) { + la, l := a, 0 + for la > 0 && (s[la-1] == ' ' || s[la-1] == '\t') { + la-- + } + for l < 2 && la > 0 && s[la-1] == '{' { + la-- + l++ + } + rz, r := z, 0 + for rz < len(s) && (s[rz] == ' ' || s[rz] == '\t') { + rz++ + } + for r < 2 && rz < len(s) && s[rz] == '}' { + rz++ + r++ + } + if l == 2 || l == 1 && r >= 1 { + a = la + } + if r == 2 || r == 1 && l >= 1 { + z = rz + } + return a, z } // maxPlaceholder is the longest placeholder Mask writes: {{, a kind (a @@ -575,36 +647,78 @@ func Restore(s string, escaped bool) string { const maxPlaceholder = len("{{") + maxKind + len("_") + 8 + len("}}") // partialTail is how much of the end of s may be the start of a -// placeholder the next piece of a stream finishes. +// placeholder the next piece of a stream finishes, in any of the ways +// Restore takes one back: {{API_, {{ phone_b5, PHONE_b5puzbfv} — or, with +// no brace before it, a last word that starts as a placeholder this magpie +// made does (PHO, PHONE_b5pu), or is one whose }} may still come. func partialTail(s string) int { + if n := braceTail(s); n > 0 { + return n + } + return wordTail(s) +} + +// braceTail is a tail from {, or {{, on: then spaces, a placeholder's body +// or the start of one, then spaces and one } at most. +func braceTail(s string) int { i := strings.LastIndexByte(s, '{') if i < 0 { return 0 } - // the {{ that opens it if i > 0 && s[i-1] == '{' { i-- } t := s[i:] - if len(t) >= maxPlaceholder || strings.Contains(t, "}}") { + if len(t) >= maxPlaceholder+4 || strings.Contains(t, "}}") { return 0 } - // {, {{, {{A…, {{API_KEY_ab…, {{API_KEY_abcdefgh} - if t == "{" || t == "{{" { - return len(t) + body := strings.TrimLeft(t, "{") + body = strings.TrimLeft(body, " \t") + if body == "" { + return len(t) // {, {{, {{␠ } - if !strings.HasPrefix(t, "{{") { + if c := body[0]; !(c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { return 0 } - body := strings.TrimSuffix(t[2:], "}") - if body == "" || body[0] < 'A' || body[0] > 'Z' { + j := 0 + for j < len(body) && isWordByte(body[j]) { + j++ + } + rest := strings.TrimLeft(body[j:], " \t") + if rest != "" && rest != "}" { return 0 } - for j := 0; j < len(body); j++ { - c := body[j] - if !(c >= 'A' && c <= 'Z' || c == '_' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9') { - return 0 - } + if j < len(body) && placeholderBody.FindString(body[:j]) != body[:j] { + return 0 // a space or a brace after something that is no placeholder } return len(t) } + +// wordTail is the last word of s, where it may be a placeholder's body as +// a model writes one without braces: the start of one of the kinds this +// magpie has made placeholders of, up to the 8 of its hash. A word of +// text that only starts like a kind is held for an event and then goes +// on, unchanged. +func wordTail(s string) int { + i := len(s) + for i > 0 && isWordByte(s[i-1]) { + i-- + } + w := s[i:] + if w == "" || len(w) > maxKind+9 || !(w[0] >= 'A' && w[0] <= 'Z') { + return 0 + } + u := strings.ToUpper(w) + mu.RLock() + defer mu.RUnlock() + for k := range kinds { + k += "_" + if strings.HasPrefix(k, u) { + return len(w) + } + if strings.HasPrefix(u, k) && len(u)-len(k) <= 8 && strings.Trim(strings.ToLower(u[len(k):]), "abcdefghijklmnopqrstuvwxyz234567") == "" { + return len(w) + } + } + return 0 +} diff --git a/internal/redact/restore_test.go b/internal/redact/restore_test.go new file mode 100644 index 000000000..78d48d175 --- /dev/null +++ b/internal/redact/restore_test.go @@ -0,0 +1,156 @@ +package redact + +import ( + "encoding/json" + "net/http/httptest" + "strings" + "testing" +) + +// phonePlaceholder masks a phone number as a request has it and gives the +// placeholder the vendor saw. +func phonePlaceholder(t *testing.T, phone string) string { + t.Helper() + out, n := Mask("请回拨 "+phone+" 谢谢", Options{Personal: true}) + if n != 1 { + t.Fatalf("not masked: %q", out) + } + return strings.TrimSuffix(strings.TrimPrefix(out, "请回拨 "), " 谢谢") +} + +// A model writes a placeholder back in the ways models do: as a template's +// variable with spaces, a brace dropped, without braces, in another case. +// Each is the value again; what only looks like one stays as it is. +func TestRestoreRewrittenPlaceholder(t *testing.T) { + const phone = "13912345678" + p := phonePlaceholder(t, phone) + body := p[2 : len(p)-2] // PHONE_xxxxxxxx + lower, upper := strings.ToLower(body), body[:6]+strings.ToUpper(body[6:]) + for _, c := range []struct{ in, want string }{ + {"拨打 " + p + " 即可", "拨打 " + phone + " 即可"}, + {"拨打 {{ " + body + " }} 即可", "拨打 " + phone + " 即可"}, + {"拨打 {{" + body + "} 即可", "拨打 " + phone + " 即可"}, + {"拨打 {" + body + "}} 即可", "拨打 " + phone + " 即可"}, + {"拨打 {" + body + "} 即可", "拨打 " + phone + " 即可"}, + {"拨打 {{" + body + " 即可", "拨打 " + phone + " 即可"}, + {"拨打" + body + "即可", "拨打" + phone + "即可"}, + {"phone: `" + body + "`", "phone: `" + phone + "`"}, + {"拨打 {{" + lower + "}} 即可", "拨打 " + phone + " 即可"}, + {"拨打 {{" + upper + "}} 即可", "拨打 " + phone + " 即可"}, + {`{"to":"` + body + `"}`, `{"to":"` + phone + `"}`}, + {"a {" + body + " b", "a {" + phone + " b"}, // a lone { is the text's + // not one of magpie's: another hash, inside a longer word + {"{{PHONE_zzzzzzzz}} x" + body + " " + body + "x", "{{PHONE_zzzzzzzz}} x" + body + " " + body + "x"}, + } { + if got := Restore(c.in, false); got != c.want { + t.Errorf("Restore(%q) = %q, want %q", c.in, got, c.want) + } + } + // a tool call's arguments, a secret's lower-cased placeholder in them + masked, _ := Mask(`DB_PASSWORD=hunter2abc1`, Options{Secrets: true}) + _, ph, _ := strings.Cut(masked, "=") + got := Restore(`{"env":"{{ `+strings.ToLower(ph[2:len(ph)-2])+` }}"}`, true) + var args map[string]string + if err := json.Unmarshal([]byte(got), &args); err != nil || args["env"] != "hunter2abc1" { + t.Fatalf("args %s: %v", got, err) + } +} + +// A stream the model writes a rewritten placeholder into, token by token +// as a vendor sends it, reads as the value with nothing of the +// placeholder left: no brace whose partner came an event later, the same +// events as came. +func TestWriterStreamRewrittenPlaceholder(t *testing.T) { + const phone = "13987654321" + p := phonePlaceholder(t, phone) + body := p[2 : len(p)-2] + chat := func(s string) string { + b, _ := json.Marshal(s) + return `data: {"id":"chatcmpl-9a1","object":"chat.completion.chunk","created":1760000000,"model":"deepseek-chat","system_fingerprint":"fp_1","choices":[{"index":0,"delta":{"content":` + string(b) + `},"logprobs":null,"finish_reason":null}]}` + "\n\n" + } + // as a tokenizer splits them: the braces, the kind, the hash + pieces := []string{ + "已记录:", "{{", " ", "PH", "ONE", "_" + body[6:9], body[9:], " ", "}}", "。\n", + "备用 ", "PH", "ONE_", body[6:10], body[10:], ";", + "再次 {{", body[:8], body[8:], "}", "}", "。", + "最后 ", body, "", + } + var events []string + for _, s := range pieces { + events = append(events, chat(s)) + } + events = append(events, `data: {"id":"chatcmpl-9a1","object":"chat.completion.chunk","created":1760000000,"model":"deepseek-chat","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]}`+"\n\n", "data: [DONE]\n\n") + + rec := httptest.NewRecorder() + rec.Header().Set("Content-Type", "text/event-stream") + w := NewWriter(rec) + w.WriteHeader(200) + for _, e := range events { + w.Write([]byte(e)) + } + w.Finish() + + var text strings.Builder + for _, ev := range strings.Split(rec.Body.String(), "\n\n") { + d, ok := strings.CutPrefix(ev, "data: ") + if !ok || d == "[DONE]" { + continue + } + var e struct { + Choices []struct{ Delta struct{ Content string } } + } + if err := json.Unmarshal([]byte(d), &e); err != nil { + t.Fatalf("event %q: %v", d, err) + } + text.WriteString(e.Choices[0].Delta.Content) + } + want := "已记录:" + phone + "。\n备用 " + phone + ";再次 " + phone + "。最后 " + phone + if text.String() != want { + t.Fatalf("text:\n got %q\nwant %q", text.String(), want) + } + if strings.Count(rec.Body.String(), "\n\n") != len(events) { + t.Fatalf("events changed:\n%s", rec.Body.String()) + } +} + +// Anthropic's tool call written as it streams, the placeholder in another +// case and split in its partial_json: the arguments the agent puts +// together are JSON with the value in them. +func TestWriterStreamToolArgsRewritten(t *testing.T) { + const phone = "13911112222" + p := phonePlaceholder(t, phone) + lower := strings.ToLower(p) + args := `{"file_path":"/tmp/contact.md","content":"电话:` + lower + `\n"}` + ev := func(s string) string { + b, _ := json.Marshal(map[string]any{"type": "content_block_delta", "index": 1, "delta": map[string]any{"type": "input_json_delta", "partial_json": s}}) + return "event: content_block_delta\ndata: " + string(b) + "\n\n" + } + at := strings.Index(args, lower) + 9 + events := []string{ev(args[:at]), ev(args[at:]), "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":1}\n\n"} + rec := httptest.NewRecorder() + rec.Header().Set("Content-Type", "text/event-stream") + w := NewWriter(rec) + w.WriteHeader(200) + for _, e := range events { + w.Write([]byte(e)) + } + w.Finish() + var js strings.Builder + for _, e := range strings.Split(rec.Body.String(), "\n\n") { + _, d, ok := strings.Cut(e, "data: ") + if !ok { + continue + } + var x struct { + Delta struct { + PartialJSON string `json:"partial_json"` + } + } + json.Unmarshal([]byte(d), &x) + js.WriteString(x.Delta.PartialJSON) + } + var in map[string]string + if err := json.Unmarshal([]byte(js.String()), &in); err != nil || in["content"] != "电话:"+phone+"\n" { + t.Fatalf("args %q: %v", js.String(), err) + } +} diff --git a/internal/redact/writer.go b/internal/redact/writer.go index 42715cf80..a4058e61e 100644 --- a/internal/redact/writer.go +++ b/internal/redact/writer.go @@ -170,7 +170,7 @@ func (rw *Writer) event(ev []byte) error { rw.pending = nil } typ := "" - tailPath, tail := "", "" + tailPath, tail, cut := "", "", "" restored, _ := walk(data, func(path, key, s string) string { if path == "type" { typ = s @@ -181,11 +181,14 @@ func (rw *Writer) event(ev []byte) error { if keep(key, s) { return s } - s = Restore(s, asJSON(key, typ)) + // the tail is looked for before anything is put back, so a + // placeholder whose last brace is still to come isn't put back + // without it and the brace left behind if n := partialTail(s); n > 0 { tailPath, tail = path, s[len(s)-n:] + cut = Restore(s[:len(s)-n], asJSON(key, typ)) } - return s + return Restore(s, asJSON(key, typ)) }) full := rebuild(pre, restored, post) if tail == "" { @@ -194,7 +197,7 @@ func (rw *Writer) event(ev []byte) error { } cutData, _ := walk(restored, func(path, _, s string) string { if path == tailPath { - return strings.TrimSuffix(s, tail) + return cut } return s })