Files
magpie/internal/redact/scrub.go
T
yetoneandggbdpq 243594410d redact: a tool call's arguments stay JSON when a value follows an escape (#3022)
A history tool call's function.arguments is JSON text inside a string.
MaskJSON masked it as plain text, so the n of a \n started a match:
"\n@mcp.tool()" became "\{{EMAIL_…}}()", the arguments were no longer
JSON, and Ollama Cloud refused every turn that replayed the call with
400 "invalid tool call arguments". Reported by xiaobaifly7 and reproduced
independently by Shane-Meng (\n\n\n@pytest.mark…).

Where a string holds JSON text (asJSON), mask now reads it the way the
vendor reads it once it is unescaped:
- unescapedView: a same-length view in which \n, \r, \t, \b and \f read
  as control characters and a \u escape reads as line breaks, so no word
  starts or ends on an escape's letter. \" \\ \/ stay as written, so the
  SECRET rule's \"-aware quote and Windows paths read as before.
- outsideEscapes: any span (rule, word, model, known) that starts or
  ends inside an escape is cut back to the escape's edges, so the JSON
  holds and what the span held is still masked. A span left empty is
  dropped.
- unescapedPut: the value kept for Restore is the unescaped one, so
  Restore (which escapes it again in arguments) gives the agent exactly
  what it wrote. Before this, a private key's \n came back as \\n.

Ported from ggbdpq's hunt53-f-redact-json-escape. Their test
TestMaskJSONKeepsArgumentsJSON is kept verbatim. Their guard alone let
"\njo@quill.dev" through unmasked, so this port also adds the view, the
trimming and the restore.

Run at base 673651e8d (origin/main) plus this change:
- gofmt -l: clean
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok
- go test -tags nogui -race -count=3 ./internal/redact: ok
- go test -tags nogui -count=1 -timeout 45m ./internal/redact/...
  ./internal/gateway/...: ok (redact 3.7s, gateway 423s; internal/masking has no tests)
- Full suite NOT run: another session's `go test -timeout 45m ./...`
  was already running on this machine (one suite per machine).

Broken by hand (each run against the new tests in escape_test.go):
- old code (origin/main's redact.go, json.go and scrub.go, with a no-op
  outsideEscapes shim): all 4 tests red. TestMaskJSONKeepsArgumentsJSON
  "2 masked, want 1"; Escapes "invalid character '{' in string escape
  code" with \{{EMAIL_…}}; Restore gets \\n back; CutShort red.
- unescapedView off: KeepsArgumentsJSON, Escapes and CutShort red.
- unescapedPut off: TestRestoreArgumentsFromArguments red.
- outsideEscapes call off: CutShort red (a user rule
  `REL-[a-z\\]+` ending on the backslash of \" breaks the JSON).
- trimming replaced by dropping: CutShort's unit check red.

Fixtures come from the reporters' bytes: xiaobaifly7's \n@mcp.tool() and
Shane-Meng's \n\n\n@pytest.mark…. They also cover an address after \n,
\t, \" or \r\n, after a Windows path, and after é/—; an npm key
after \n; a key-context password; and cut-short arguments. Each checks
that the arguments still parse, the values are gone and the decorators
are unchanged.

Not tried / not covered:
- No real Ollama Cloud round trip, and nothing end to end on Windows.
- A user rule that reads past the string's closing quote (e.g. \S+ over
  JSON text) can still break arguments. That was true before this change
  and is not an escape case.
- Allow-list matching and a Hit's hint use the escaped text as written.
  A value remembered earlier with real newlines is not found by
  knownSpans in arguments unless a rule finds it again.
- A personal value written as a JSON number in arguments is not masked
  (masking it would break the JSON).

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-23 18:01:26 +08:00

181 lines
5.1 KiB
Go

package redact
import (
"crypto/sha256"
"regexp"
"strings"
"sync"
"sync/atomic"
)
// Scrubbing is for what is kept rather than sent — the request archive: a
// secret goes for good, as [REDACTED:KIND], with no placeholder made and
// nothing held to put it back. Everything Mask finds as a secret goes,
// and whatever is in a field or header named for one (Authorization,
// x-api-key, Cookie, access_token, client_secret…), whatever it looks like.
// Scrubbed is what a field or header named for a secret holds once scrubbed.
const Scrubbed = "[REDACTED]"
func scrubbed(kind, _ string) string { return "[REDACTED:" + kind + "]" }
// secretName is a field's or header's name that says its value is a secret.
var secretName = regexp.MustCompile(`(?i)` + secretNames.pattern() + `|authori[sz]ation|cookie|^key$`)
// SecretName says a field or header called name holds a secret: a token,
// key, password or cookie — not a count of tokens (max_tokens).
func SecretName(name string) bool {
n := strings.ToLower(name)
return secretName.MatchString(n) && !strings.HasSuffix(n, "tokens") && !strings.HasSuffix(n, "token_count")
}
// Scrub takes the secrets Mask finds out of s.
func Scrub(s string) string {
if len(s) < scrubMemoMin {
return scrub(s)
}
// What Scrub makes of s depends on s and on the values known (known.go)
// alone: a result is kept under the knownGen it was made at, and none
// made before a value became known is used again.
gen := knownGen.Load()
k := sha256.Sum256([]byte(s))
if out, ok := scrubMemo.get(k, gen, s); ok {
return out
}
out := scrub(s)
scrubMemo.put(k, gen, s, out)
return out
}
func scrub(s string) string {
if len(s) >= 256 {
scrubRuns.Add(1)
}
out, _ := mask(s, Options{Secrets: true}, scrubbed, false)
return out
}
// scrubRuns counts the strings of 256 bytes or more the rules have run
// over (a test reads it).
var scrubRuns atomic.Uint64
// Scrub remembers what it made of a long string. An agent sends its whole
// history on every turn (Codex: every item of a session, each turn), and
// what is kept of each request (the request archive, a gateway
// conversation) is scrubbed whole, so without it every turn ran each rule
// over the whole history again: a core's worth while Codex ran
// (yetone/magpie-releases#24). A short string costs less to scrub than to
// look up. Only a hash of a string is kept, and what it became when that
// is not the string itself.
const (
scrubMemoMin = 256
scrubMemoEntries = 1 << 15
scrubMemoBytes = 32 << 20
)
type scrubEntry struct {
gen uint64
same bool // s came back as it was
out string // else what it became
}
// scrubMemo holds two generations of results: when the newer is full, it
// becomes the older and the older goes, so what is in use stays and at
// most twice the bounds are held.
var scrubMemo memo
type memo struct {
sync.Mutex
cur, old map[[32]byte]scrubEntry
bytes int
}
func (m *memo) get(k [32]byte, gen uint64, s string) (string, bool) {
m.Lock()
defer m.Unlock()
e, ok := m.cur[k]
if !ok {
if e, ok = m.old[k]; ok && e.gen == gen {
m.add(k, e)
}
}
if !ok || e.gen != gen {
return "", false
}
if e.same {
return s, true
}
return e.out, true
}
func (m *memo) put(k [32]byte, gen uint64, s, out string) {
e := scrubEntry{gen: gen, same: out == s}
if !e.same {
e.out = strings.Clone(out)
}
m.Lock()
defer m.Unlock()
m.add(k, e)
}
// reset forgets everything (a test starts from nothing).
func (m *memo) reset() {
m.Lock()
defer m.Unlock()
m.cur, m.old, m.bytes = nil, nil, 0
}
// add is called with m held.
func (m *memo) add(k [32]byte, e scrubEntry) {
if m.cur == nil || len(m.cur) >= scrubMemoEntries || m.bytes+len(e.out) > scrubMemoBytes {
m.old, m.cur, m.bytes = m.cur, make(map[[32]byte]scrubEntry), 0
}
m.bytes += len(e.out) - len(m.cur[k].out)
m.cur[k] = e
}
// ScrubHeader is a header's value with its secrets taken out: all of it
// for a header named for one or a credential (Bearer, Basic), else what
// Scrub finds in it.
func ScrubHeader(name, value string) string {
v := strings.ToLower(strings.TrimSpace(value))
if SecretName(name) || strings.HasPrefix(v, "bearer ") || strings.HasPrefix(v, "basic ") {
return Scrubbed
}
return Scrub(value)
}
// ScrubJSON is a body with its secrets taken out: a JSON one string by
// string, a field named for a secret wholly; a stream's events each as
// JSON, line by line; anything else as text. A picture's data is left as
// it is.
func ScrubJSON(body []byte) []byte {
if out, ok := scrubJSON(body); ok {
return out
}
lines := strings.SplitAfter(string(body), "\n")
for i, l := range lines {
if rest, ok := strings.CutPrefix(l, "data:"); ok {
trimmed := strings.TrimSpace(rest)
if out, ok := scrubJSON([]byte(trimmed)); ok && trimmed != "" {
lines[i] = "data: " + string(out) + l[len(strings.TrimRight(l, "\r\n")):]
continue
}
}
lines[i] = Scrub(l)
}
return []byte(strings.Join(lines, ""))
}
func scrubJSON(b []byte) ([]byte, bool) {
return walk(b, func(_, key, s string) string {
switch {
case strings.HasPrefix(s, "data:"):
return s
case key != "" && SecretName(key):
return Scrubbed
}
return Scrub(s)
})
}