Files
magpie/internal/redact/redact.go
T
yetone 50f52b540b redact: a text masked for a vendor before is masked as it was then, so a cached prompt stays cached
With Privacy masking on, a value masked once is "known" and masked
wherever a later request has it (redact/known.go). When a rule first
finds a value in a later turn (a tool printing DB_PASSWORD=...), that
value was masked from then on in the system prompt and the turns already
sent with it as written. The prefix the vendor had cached changed, so
the whole prompt was written to the cache again and none of it was read.

Reported by audie on Discord: DeepSeek Harness on a routing group served
by a custom Anthropic-compatible provider. Adjacent turns 10s apart had
cache_read 0 and cache_write 412K to 427K.

Fix: Mask and MaskJSON (the vendor-bound paths, via masking.Masker) now
use sentKnownSpans. A text masked before gets the known values it had
the first time, keyed by a sha256 of the text and the options. Only
hashes and spans are kept, never a value, in two generations of 65536.
New text still gets every known value masked. Scrub (archives, sessions,
OTel; local only) keeps the latest known set.

Unchanged: if magpie restarts, or a text falls out of both generations,
the text is masked under the current known set once, as before.

What was run:
- internal/redact TestSentTextKeepsItsMasking and internal/gateway
  TestMaskedConversationKeepsItsCachedPrefix. The gateway test sends a
  dsh-shaped Chat Completions conversation to a group with an Anthropic
  member, and a Claude Code-shaped /v1/messages one. It checks that each
  turn's system, tools and earlier messages reach the fake upstream byte
  for byte. Both tests are red with sentKnownSpans forced back to
  knownSpans: the system prompt became "{{SECRET_...}}" on turn 3. Both
  are green with the fix.
- With masking off, a probe of the same dsh shape had the system, tools
  and earlier turns byte-identical on every turn.
- gofmt -l: clean. go vet: darwin, GOOS=linux -tags nogui ./...,
  GOOS=windows ./...: clean.
- Full suite at 8187919d7 (this tree, on origin/main bf2e067ef):
  set -o pipefail; go test -tags nogui -timeout 45m ./..., through the
  suite lock. 69 packages ok, none red (gateway 519s, agent 393s).

Not tried: audie's real setup. Their Privacy setting isn't known; with
masking off this is not the cause, and every breakpoint reading 0
(even the unchanged system block) points at the provider's own cache or
pool. Not tried against a real Anthropic or relay account. GUI not
touched, so the GUI suite was not run. Windows tests not run.
2026-10-23 20:53:53 +08:00

1081 lines
35 KiB
Go

// Package redact keeps secrets on the machine. What the gateway sends a
// vendor has its secrets (API keys, private keys, tokens, passwords in
// connection strings and assignments), and when asked personal data and the
// user's own words, swapped for placeholders like {{API_KEY_k3v9x2mq}}; what
// the vendor says back has them swapped back, streams included, so the agent
// and the user see the real thing while the vendor never does.
//
// A placeholder is the same for the same value every time (a keyed hash of
// it), so a conversation's history reads the same turn after turn — what a
// vendor cached of it stays good, and a thinking block's signature still
// matches the text it was made for — and one placeholder is never two
// values. The values are held in memory only, by placeholder, as requests
// bring them; a restart loses nothing, since the next request brings them
// again. A value once masked is masked wherever a request has it, whatever
// words are around it (known.go): the vendor writes about a placeholder in
// words no rule knows, and the agent sends that text back with the value.
package redact
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base32"
"encoding/json"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"strings"
"sync"
"unicode/utf8"
)
// Options says what to mask.
type Options struct {
Secrets bool // API keys, private keys, tokens, passwords
Personal bool // emails, phone numbers, ID and bank card numbers
Words []string // the user's own: names, codenames, hosts
// WordsAnyCase matches Words in any case: Nightjar masks NIGHTJAR and
// nightjar too. Off, a word is matched as written.
WordsAnyCase bool
Rules []Rule // the user's own rules, masked with the secrets
// Kinds turns each of the Categories of personal data on or off by its
// id, where the user chose; one not in it is as its Category.On says.
// None of them is masked while Personal is off.
Kinds map[string]bool
// Model, where set, finds more in the texts to mask (model.go)
Model Model
// Actions is what is done with a value of a kind (a Hit's Kind) other
// than masking it, where the user chose: Warn sends it as written,
// Block masks it and the request is held back (the gateway's). A kind
// not in it is masked.
Actions map[string]string
// Allow are values the user lets go as written, whichever finder finds
// them: each a whole value, in any case.
Allow []string
// Seen, where set, is told of each value masked, warned of or blocked
Seen func(Hit)
// found are the spans Model found, by text, for one request's texts
found map[string][]Found
// sent is masking for a vendor (Mask, MaskJSON): a text masked
// before has the known values it had then (sentKnownSpans)
sent bool
}
// covers says o masks what a rule of category cat finds: "" are the
// secrets, catPersonal the personal data always masked with it, any other
// one of the Categories.
func (o Options) covers(cat string) bool {
switch cat {
case "":
return o.Secrets
case catPersonal:
return o.Personal
}
if !o.Personal {
return false
}
if on, ok := o.Kinds[cat]; ok {
return on
}
return categoryOn[cat]
}
// rule finds one kind of value. The match is group 1 when the pattern has
// one, else all of it; bound are the characters that may not touch it on
// either side (a key inside a longer word is no key); ok checks it further.
type rule struct {
kind string
re *regexp.Regexp
markers []string // one of these is in any text it can match
// fold are markers too, looked for in the text in lower case, for a
// pattern that matches its words in any case (Passport, PASSPORT)
fold []string
bound string
ok func(string) bool
// at checks the value at s[a:b] by what is around it: a dotted quad
// right after "version" is no address
at func(s string, a, b int) bool
// fix, where set, checks the value in place of ok and may shorten it:
// an IBAN printed in groups of four, followed by a word in capitals
fix func(s string, a, b int) (int, int, bool)
// back and ahead, where ahead is set, are how far before and after
// one of fold a match can be: the pattern is only run there, as one
// that takes its words in any case is slow over all of a long text
back, ahead int
// cat is what turns the rule on (Options.covers): "" the secrets
cat string
// yours is a rule the user wrote (customRules)
yours bool
// anyGroup takes the first group that matched, for a pattern with a
// group in each of its alternatives
anyGroup bool
// groups, where set, are the kinds of a match's groups, each masked as
// a value of its own (the user and the host of user@host), and groupOK
// checks each
groups []string
groupOK []func(string) bool
}
const (
alnum = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
tokenCh = alnum + "_-"
digits = "0123456789"
)
var rules = append([]rule{
{kind: "PRIVATE_KEY", re: regexp.MustCompile(`-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]+?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----`), markers: []string{"PRIVATE KEY"}},
{kind: "API_KEY", re: regexp.MustCompile(`sk-(?:ant-|proj-|or-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}`), markers: []string{"sk-"}, bound: tokenCh},
// a gateway's or a relay's own: oc_sk_…, or_sk_… (#195)
{kind: "API_KEY", re: regexp.MustCompile(`[a-z]{2,4}_sk_[A-Za-z0-9_-]{20,}`), markers: []string{"_sk_"}, bound: tokenCh, ok: secretValue},
{kind: "API_KEY", re: regexp.MustCompile(`(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,}|glpat-[A-Za-z0-9_-]{20,})`), markers: []string{"gh", "github_pat_", "glpat-"}, bound: tokenCh},
{kind: "API_KEY", re: regexp.MustCompile(`AIza[0-9A-Za-z_-]{35}`), markers: []string{"AIza"}, bound: tokenCh},
{kind: "API_KEY", re: regexp.MustCompile(`xox[abposr]-[0-9A-Za-z-]{10,}`), markers: []string{"xox"}, bound: tokenCh},
{kind: "API_KEY", re: regexp.MustCompile(`(?:sk|rk)_live_[0-9A-Za-z]{20,}`), markers: []string{"_live_"}, bound: tokenCh},
{kind: "API_KEY", re: regexp.MustCompile(`(?:AKIA|ASIA)[0-9A-Z]{16}`), markers: []string{"AKIA", "ASIA"}, bound: alnum},
{kind: "API_KEY", re: regexp.MustCompile(`(?:hf_[A-Za-z0-9]{30,}|gsk_[A-Za-z0-9]{40,}|xai-[A-Za-z0-9]{40,}|npm_[A-Za-z0-9]{36}|pypi-[A-Za-z0-9_-]{50,}|dop_v1_[a-f0-9]{64}|SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43})`),
markers: []string{"hf_", "gsk_", "xai-", "npm_", "pypi-", "dop_v1_", "SG."}, bound: tokenCh},
{kind: "TOKEN", re: regexp.MustCompile(`eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}`), markers: []string{"eyJ"}, bound: tokenCh},
// the password of user:password@host
{kind: "PASSWORD", re: regexp.MustCompile(`[A-Za-z][A-Za-z0-9+.-]*://[^\s:@/?#"'<>]+:([^\s@/?#"'<>]{3,})@`), markers: []string{"://"}, ok: notAVariable},
// password = …, API_KEY: "…", as .env files and configs have them
{kind: "SECRET", re: regexp.MustCompile(`(?i)[A-Za-z0-9_.-]*(?:` + secretNames.pattern() + `)[A-Za-z0-9_.-]*` + quote + `[ \t]*[:=][ \t]*` + quote + `(` + secretCh + `{8,})`),
markers: secretNames.markers(), ok: secretValue},
// a field called key and nothing more, as providers.json has one: "key":
// "oc_sk_…" (#195). Only a long value of letters and digits both, since
// code calls anything a key: a map's "key": "value", sort_key, keyboard.
{kind: "SECRET", re: regexp.MustCompile(`(?i)(?:^|[^A-Za-z0-9_.-])` + quote + `key` + quote + `[ \t]*[:=][ \t]*` + quote + `(` + secretCh + `{16,})`),
markers: fieldNames{{"key", "key"}}.markers(), ok: secretValue},
{kind: "EMAIL", re: regexp.MustCompile(`[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}`), markers: []string{"@"}, bound: alnum + "._%+-", ok: realEmail, cat: catPersonal},
{kind: "ID_CARD", re: regexp.MustCompile(`[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]`), bound: alnum, ok: chineseID, cat: catPersonal},
{kind: "PHONE", re: regexp.MustCompile(`(?:\+?86[- ]?)?1[3-9]\d{9}`), bound: digits, cat: catPersonal},
{kind: "BANK_CARD", re: regexp.MustCompile(`[3-6]\d{3}(?:[ -]?\d{4}){2,3}(?:[ -]?\d{1,3})?`), bound: digits, ok: luhn, cat: catPersonal},
}, moreRules...)
// fieldNames are what a field that holds a secret is called: a pattern for
// each name, and text that any match of it has in it, so a rule's markers
// and the names its pattern takes come from one list and can't drift apart.
type fieldNames []struct{ re, marker string }
// secretNames are what a field holding a secret has in its name:
// DB_PASSWORD, apiKey, x-api-key, client_secret.
var secretNames = fieldNames{
{"password", "pass"}, {"passwd", "pass"},
{"secret", "secret"},
{"token", "token"},
{`api[_-]?key`, "key"}, {`access[_-]?key`, "key"}, {`private[_-]?key`, "key"},
{"credential", "credential"},
}
func (f fieldNames) pattern() string {
res := make([]string, len(f))
for i, n := range f {
res[i] = n.re
}
return strings.Join(res, "|")
}
// markers are each name's marker as a name is written in lower case, in
// upper case and capitalised: password, PASSWORD, Password, apiKey.
func (f fieldNames) markers() []string {
var out []string
for _, n := range f {
for _, m := range []string{n.marker, strings.ToUpper(n.marker), strings.ToUpper(n.marker[:1]) + n.marker[1:]} {
if !slices.Contains(out, m) {
out = append(out, m)
}
}
}
return out
}
const (
// quote is a field's or a value's quote, if it has one: " or ', or \"
// in JSON written inside a string
quote = `(?:\\?["'])?`
// secretCh are the characters of a secret's value
secretCh = `[A-Za-z0-9_\-./+=~!@#%^&*]`
)
// placeholderRe is a placeholder as Mask writes it.
var placeholderRe = regexp.MustCompile(`\{\{[A-Z][A-Z0-9_]*_[a-z2-7]{8}\}\}`)
// notAVariable turns away what stands in for a value: ${PASS}, <password>, ****.
func notAVariable(v string) bool {
if strings.ContainsAny(v[:1], "$%{<[*") {
return false
}
return strings.Trim(v, "*xX.") != ""
}
// secretValue is a value that looks like a secret, not code: letters and
// digits both, and not a call, a reference or a placeholder of its own.
func secretValue(v string) bool {
if !notAVariable(v) || strings.HasPrefix(v, "process.env") || strings.HasPrefix(v, "os.") {
return false
}
return strings.ContainsAny(v, digits) && strings.IndexFunc(v, func(r rune) bool { return r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' }) >= 0
}
func realEmail(v string) bool {
host := strings.ToLower(v[strings.LastIndexByte(v, '@')+1:])
if fileHost(host) {
return false
}
for _, fake := range []string{"example.com", "example.org", "example.net", "localhost", ".test", ".invalid", ".example"} {
if host == strings.TrimPrefix(fake, ".") || strings.HasSuffix(host, fake) {
return false
}
}
return !strings.HasPrefix(host, "noreply") && !strings.Contains(v, "noreply@")
}
// fileExt are file name extensions that are no top-level domain, so
// what ends in one is a file's name and not an address: an image a Mac
// saved at twice its size, 261020_14-16-11@2x.jpg, went to the model as
// {{EMAIL_…}} and Pi could no longer read the file (#3029).
// Other files are named so too (intro@2x.mp4, strings@base.json), and
// none of these is a domain either (IANA's list, checked 2026-10-21).
var fileExt = map[string]bool{
"jpg": true, "jpeg": true, "png": true, "gif": true, "webp": true, "svg": true, "heic": true, "heif": true,
"avif": true, "bmp": true, "tif": true, "tiff": true, "ico": true, "icns": true, "pdf": true,
"svgz": true, "apng": true, "jxl": true, "psd": true, "eps": true, "lottie": true,
"mp4": true, "m4v": true, "webm": true, "mkv": true, "avi": true, "mp3": true, "m4a": true, "wav": true,
"ogg": true, "flac": true, "aac": true, "ttf": true, "otf": true, "woff": true, "woff2": true, "eot": true,
"json": true, "yaml": true, "yml": true, "toml": true, "xml": true, "txt": true, "csv": true, "tsv": true,
"log": true, "html": true, "htm": true, "css": true, "scss": true, "less": true, "js": true, "mjs": true,
"cjs": true, "jsx": true, "ts": true, "tsx": true, "doc": true, "docx": true, "xls": true, "xlsx": true,
"ppt": true, "pptx": true, "gz": true, "tgz": true, "tar": true, "rar": true, "7z": true, "dmg": true,
}
// scaleExt are file extensions that are top-level domains too (.zip,
// .mov, .md, .map): a name ending in one is a file's only with a scale
// before it, icon@2x.zip, intro@1.5x.mov, while ops@files.zip is an
// address.
var scaleExt = map[string]bool{"zip": true, "mov": true, "md": true, "map": true}
var scaleRe = regexp.MustCompile(`^[0-9]+(?:\.[0-9]+)?x$`)
// fileHost says host, what follows the @ of what looks like an address,
// is the end of a file's name: an extension no domain has (fileExt), or a
// scale and an extension that is a domain too (scaleExt).
func fileHost(host string) bool {
dot := strings.LastIndexByte(host, '.')
ext := host[dot+1:]
return fileExt[ext] || dot > 0 && scaleExt[ext] && scaleRe.MatchString(host[:dot])
}
func chineseID(v string) bool {
w := []int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
sum := 0
for i := 0; i < 17; i++ {
sum += int(v[i]-'0') * w[i]
}
return strings.ToUpper(v[17:]) == string("10X98765432"[sum%11])
}
func luhn(v string) bool {
var ds []int
for _, r := range v {
if r >= '0' && r <= '9' {
ds = append(ds, int(r-'0'))
}
}
if len(ds) < 15 || len(ds) > 19 {
return false
}
sum := 0
for i := range ds {
d := ds[len(ds)-1-i]
if i%2 == 1 {
if d *= 2; d > 9 {
d -= 9
}
}
sum += d
}
return sum%10 == 0
}
// ---- placeholders ---------------------------------------------------------------
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
)
// maxValues bounds what is held; past it the oldest half is let go, and a
// request that still has them brings them back.
const maxValues = 200_000
func key() []byte {
mu.RLock()
k := keyOf
mu.RUnlock()
if k != nil {
return k
}
mu.Lock()
defer mu.Unlock()
if keyOf != nil {
return keyOf
}
keyOf = loadKey()
return keyOf
}
// SetKeyPath chooses where the placeholder key is kept across restarts;
// "" keeps it in memory only. The gateway's owner sets it before requests
// arrive. Once the key is loaded, both it and its path stay fixed.
func SetKeyPath(path string) {
mu.Lock()
defer mu.Unlock()
if keyOf == nil {
keyPath = path
}
}
// loadKey is called with mu held.
func loadKey() []byte {
if keyPath != "" {
if b, err := os.ReadFile(keyPath); err == nil && len(b) >= 32 {
return b[:32]
}
}
b := make([]byte, 32)
_, _ = rand.Read(b)
if keyPath != "" {
_ = os.MkdirAll(filepath.Dir(keyPath), 0o700)
_ = os.WriteFile(keyPath, b, 0o600)
}
return b
}
var b32 = base32.StdEncoding.WithPadding(base32.NoPadding)
// tag is the placeholder v of kind goes as, made and not remembered: a
// value sent as written (Warn) is named by it in the record of what was
// found, and a preview names each value by it.
func tag(kind, v string) string {
h := hmac.New(sha256.New, key())
h.Write([]byte(kind + "\x00" + v))
return "{{" + kind + "_" + strings.ToLower(b32.EncodeToString(h.Sum(nil))[:8]) + "}}"
}
func placeholder(kind, v string) string {
p := tag(kind, v)
mu.Lock()
if _, ok := values[p]; !ok {
if len(values) >= maxValues {
n := 0
for k := range values {
delete(values, k)
if n++; n >= maxValues/2 {
break
}
}
reindexKnown()
}
values[p] = v
kinds[kind] = true
addKnown(p, v)
}
mu.Unlock()
return p
}
// ---- masking --------------------------------------------------------------------
type span struct {
start, end int
kind string
by string // which finder found it: one of the By constants
}
// Which finder found a value (Hit.By): magpie's rules, the user's own
// rules, the user's words, the local model (with the Chinese names it
// brings, which run only with it), or a value masked before (known.go).
const (
ByRule = "rule"
ByYours = "yours"
ByWord = "word"
ByModel = "model"
ByKnown = "known"
)
// What is done with a value of a kind (Options.Actions) other than
// masking it.
const (
Warn = "warn" // sent as written, and recorded
Block = "block" // masked, and the request held back
)
// Hit is one value found: its kind, the finder that found it, the
// placeholder it went as (or would have, for one sent as written), what
// was done with it ("" masked, Warn, Block) and its Hint. It never holds
// the value itself.
type Hit struct {
Kind, By, Placeholder, Action string
Head string
Len int
}
// Value is the value behind placeholder p, while this run of magpie
// remembers it.
func Value(p string) (string, bool) {
mu.RLock()
defer mu.RUnlock()
v, ok := values[p]
return v, ok
}
// Hint is as much of v as may be kept where v itself may not: its first
// character (the first few of a key's, which name its kind: sk-, ghp_)
// and how many characters it has.
func Hint(kind, v string) (head string, n int) {
n = utf8.RuneCountInString(v)
if n < 2 {
return "", n
}
k := 1
if _, personal := kindCats[kind]; !personal && kind != "TERM" && n >= 16 {
// a key's prefix, up to where its random part starts
k = 0
for _, c := range v {
if k >= 4 || !strings.ContainsRune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_", c) {
break
}
k++
if c == '-' || c == '_' {
break
}
}
k = max(k, 1)
}
r := []rune(v)
return string(r[:k]), n
}
// anyCases are the patterns that find a user's word in any case, by word.
var anyCases sync.Map
// anyCase finds w as written but in any case (Unicode's simple folding, so
// a word whose case changes its length in bytes is still found whole).
func anyCase(w string) *regexp.Regexp {
if re, ok := anyCases.Load(w); ok {
return re.(*regexp.Regexp)
}
re := regexp.MustCompile(`(?i)` + regexp.QuoteMeta(w))
anyCases.Store(w, re)
return re
}
// Mask swaps what o covers in s for placeholders, and says how many.
func Mask(s string, o Options) (string, int) {
o.sent = true
return mask(s, withModel(o, []string{s}), placeholder, false)
}
// Preview is Mask with nothing remembered: each value goes as the
// placeholder it would have, which isn't kept for Restore or as a value
// seen before (known.go).
func Preview(s string, o Options) string {
out, _ := mask(s, withModel(o, []string{s}), tag, false)
return out
}
// mask swaps what o covers in s for what put makes of each value.
//
// escaped says s holds JSON text of its own (asJSON: a tool call's
// arguments), which the vendor reads after one more unescaping. There the
// finders read s as the vendor does (unescapedView): the \n before
// @mcp.tool is a newline, not an n that starts an address, and the \n
// before jo@quill.dev is no letter of it either. No value starts or ends
// inside an escape (outsideEscapes), and what is kept to put back is the
// value as it reads unescaped, so Restore, which escapes it again in
// arguments, gives the agent what it wrote. Read as plain text, the n of
// a \n went as the first letter of n@mcp.tool, the backslash was left
// before the placeholder (\{{EMAIL_…}}), the arguments were JSON no
// longer, and Ollama Cloud turned away every turn that replayed the call
// with 400 "invalid tool call arguments" (#3022).
func mask(raw string, o Options, put func(kind, v string) string, escaped bool) (string, int) {
if len(raw) < 3 {
return raw, 0
}
s := raw // what the finders read: as long as raw, a place in one is the same in the other
if escaped {
s = unescapedView(raw)
put = unescapedPut(put)
}
var found []span
for _, w := range o.Words {
if w = strings.TrimSpace(w); len(w) < 2 {
continue
}
if o.WordsAnyCase {
for _, m := range anyCase(w).FindAllStringIndex(s, -1) {
found = append(found, span{m[0], m[1], "TERM", ByWord})
}
continue
}
for i := 0; ; {
j := strings.Index(s[i:], w)
if j < 0 {
break
}
found = append(found, span{i + j, i + j + len(w), "TERM", ByWord})
i += j + len(w)
}
}
all := rules
if o.Secrets && len(o.Rules) > 0 {
// the user's first: where one of theirs and one of magpie's find
// the same value, it goes by the name they gave it
all = append(customRules(o.Rules), rules...)
}
lower := ""
// split are matches a rule took apart into values of their own
// (rkato@box17 as a user and a host): what another rule found from
// the same place in them, an email, goes
var split []span
for _, r := range all {
if !o.covers(r.cat) {
continue
}
if len(r.markers) > 0 && !containsAny(s, r.markers) {
continue
}
if len(r.fold) > 0 {
if lower == "" {
lower = lowerASCII(s)
}
if !containsAny(lower, r.fold) {
continue
}
}
for _, m := range r.matches(s, lower) {
if len(r.groups) > 0 {
took := false
for g, kind := range r.groups {
if a, b := m[2*g+2], m[2*g+3]; a >= 0 && r.takes(s, a, b, r.groupOK[g]) {
found = append(found, span{a, b, kind, r.by()})
took = true
}
}
if took {
split = append(split, span{m[2], m[1], "", ""})
}
continue
}
a, b := m[0], m[1]
for g := 1; 2*g+1 < len(m); g++ {
if m[2*g] >= 0 {
a, b = m[2*g], m[2*g+1]
break
}
if !r.anyGroup {
break
}
}
ok := r.ok
if r.fix != nil {
var good bool
if a, b, good = r.fix(s, a, b); !good {
continue
}
ok = nil
}
if r.takes(s, a, b, ok) {
found = append(found, span{a, b, r.kind, r.by()})
}
}
}
for _, sp := range split {
found = slices.DeleteFunc(found, func(f span) bool {
return f.kind == "EMAIL" && f.start == sp.start && f.end <= sp.end
})
}
// after the rules', so where a rule finds the same value it keeps the
// kind it has always had
found = append(found, modelSpans(raw, o)...) // the model was asked about raw
if o.sent {
found = append(found, sentKnownSpans(s, o)...)
} else {
found = append(found, knownSpans(s, o)...)
}
if escaped {
found = outsideEscapes(raw, found)
}
return apply(raw, noDecimals(s, noIDs(s, found)), put, o)
}
// unescapedView is s, JSON text, as long as s and read as the vendor reads
// it once unescaped, as far as the finders tell: an escape that stands for
// a newline, a tab or another control character has its letter read as
// one (\n as \ and a newline), and a \u escape's u and digits as line
// breaks, so neither starts or ends a word. A backslash, a quote and a
// slash escaped stay as written: the rules read \" as a quote and C:\\Users
// as a Windows path.
func unescapedView(s string) string {
if strings.IndexByte(s, '\\') < 0 {
return s
}
b := []byte(s)
for i := 0; i+1 < len(b); i++ {
if b[i] != '\\' {
continue
}
i++
switch b[i] {
case 'n', 'b', 'f':
b[i] = '\n'
case 'r':
b[i] = '\r'
case 't':
b[i] = '\t'
case 'u':
for j := i; j < i+5 && j < len(b); j++ {
b[j] = '\n'
}
i += 4
}
}
return string(b)
}
// unescapedPut is put given each value unescaped, as the vendor and the
// agent read it: a private key's \n are newlines. A value that isn't a
// JSON string's text goes as it is.
func unescapedPut(put func(kind, v string) string) func(kind, v string) string {
return func(kind, v string) string {
if strings.IndexByte(v, '\\') >= 0 {
var u string
if json.Unmarshal([]byte(`"`+v+`"`), &u) == nil {
v = u
}
}
return put(kind, v)
}
}
// outsideEscapes is found with no value starting or ending inside one of
// the escapes of s, JSON text: after an escape's backslash, as the n of
// \n, or among a \u00e9's digits. Masked there, it would leave a
// backslash before the placeholder or cut one off from its letter, and s
// would be JSON no longer (#3022). A value is cut back to the escapes'
// edges instead, so what it holds is still masked: the zoe@quill.dev of a
// model's "nzoe@quill.dev" read in \nzoe@quill.dev, a user's rule that
// reads up to the backslash of \". One left with nothing goes. Every
// finder's values go through here: the rules', the user's words, the
// model's and those known before.
func outsideEscapes(s string, found []span) []span {
if len(found) == 0 || strings.IndexByte(s, '\\') < 0 {
return found
}
// esc[i], for i inside an escape past its backslash: where the escape
// starts and ends, plus one each so a zero is outside one
type edges struct{ from, to int }
esc := make([]edges, len(s)+1)
for i := 0; i < len(s); i++ {
if s[i] != '\\' {
continue
}
n := 2
if i+1 < len(s) && s[i+1] == 'u' {
n = 6
}
end := min(i+n, len(s))
for j := i + 1; j < end; j++ {
esc[j] = edges{i + 1, end + 1}
}
i = end - 1
}
out := found[:0]
for _, f := range found {
if e := esc[f.start]; e.to > 0 {
f.start = e.to - 1
}
if e := esc[f.end]; e.from > 0 {
f.end = e.from - 1
}
if f.start < f.end {
out = append(out, f)
}
}
return out
}
// noDecimals is found without what is a piece of a decimal number of s:
// digits right after the point of 5.13800138000, or right before the
// point of 13800138000.5. A number is judged whole, and the fraction of
// a height, a price or a coordinate is not a phone or a card number
// because its digits happen to check (willz on Discord). Only personal
// data's kinds, whoever found them (a rule, the model, a value known
// before): a secret is masked wherever it is, and what the user chose
// (their words, their rules) stays theirs.
func noDecimals(s string, found []span) []span {
return slices.DeleteFunc(found, func(f span) bool {
_, personal := kindCats[f.kind]
return personal && f.by != ByWord && f.by != ByYours && inDecimal(s, f.start, f.end)
})
}
// inDecimal says s[a:b] starts with a digit that is a decimal's fraction
// (a digit and a point before it) or ends with a digit that is its whole
// part (a point and a digit after it).
func inDecimal(s string, a, b int) bool {
isDigit := func(i int) bool { return i >= 0 && i < len(s) && s[i] >= '0' && s[i] <= '9' }
return isDigit(a) && a >= 2 && s[a-1] == '.' && isDigit(a-2) ||
isDigit(b-1) && b+1 < len(s) && s[b] == '.' && isDigit(b+1)
}
// by is the finder r is, for Hit.By.
func (r rule) by() string {
if r.yours {
return ByYours
}
return ByRule
}
// matches are r's matches in s, lower being lowerASCII(s), as
// FindAllStringSubmatchIndex has them: in all of s, or, for a rule with
// ahead set, only around its fold markers.
func (r rule) matches(s, lower string) [][]int {
if r.ahead == 0 {
return r.re.FindAllStringSubmatchIndex(s, -1)
}
var wins [][2]int
for _, f := range r.fold {
for i := 0; ; {
j := strings.Index(lower[i:], f)
if j < 0 {
break
}
at := i + j
i = at + len(f)
// from the line's start, or from where a word starts no further
// back than back: what the pattern takes for the text's start is
// where a line or a word starts in s too
start := strings.LastIndexByte(s[:at], '\n') + 1
if start < at-r.back {
start = at - r.back
for start < at && (strings.IndexByte(alnum+"_.-", s[start-1]) >= 0 || s[start]&0xc0 == 0x80) {
start++
}
if start == at && strings.IndexByte(alnum+"_", s[at-1]) >= 0 {
continue // inside a longer word
}
}
wins = append(wins, [2]int{start, min(len(s), i+r.ahead)})
}
}
sort.Slice(wins, func(i, j int) bool { return wins[i][0] < wins[j][0] })
var out [][]int
for k := 0; k < len(wins); k++ {
w := wins[k]
for k+1 < len(wins) && wins[k+1][0] <= w[1] {
k++
w[1] = max(w[1], wins[k][1])
}
for _, m := range r.re.FindAllStringSubmatchIndex(s[w[0]:w[1]], -1) {
for x := range m {
if m[x] >= 0 {
m[x] += w[0]
}
}
out = append(out, m)
}
}
return out
}
// lowerASCII is s with its ASCII letters in lower case, as long as s, so a
// place in one is the same place in the other.
func lowerASCII(s string) string {
b := []byte(s)
for i, c := range b {
if 'A' <= c && c <= 'Z' {
b[i] = c + 'a' - 'A'
}
}
return string(b)
}
// takes says s[a:b] is a value r masks: nothing it may not touch beside
// it, and its checks pass.
func (r rule) takes(s string, a, b int, ok func(string) bool) bool {
if b <= a {
return false
}
if r.bound != "" && (a > 0 && strings.IndexByte(r.bound, s[a-1]) >= 0 || b < len(s) && strings.IndexByte(r.bound, s[b]) >= 0) {
return false
}
if ok != nil && !ok(s[a:b]) {
return false
}
return r.at == nil || r.at(s, a, b)
}
// apply swaps each of found in s for what put makes of its value, the
// first and longest where they overlap, nothing inside a placeholder. A
// value o allows is left as it is, and one of a kind o warns of is left
// and told. o.Seen, where set, is told of each.
func apply(s string, found []span, put func(kind, v string) string, o Options) (string, int) {
if len(found) == 0 {
return s, 0
}
// nothing inside a placeholder already there
if strings.Contains(s, "{{") {
for _, p := range placeholderRe.FindAllStringIndex(s, -1) {
found = slices.DeleteFunc(found, func(f span) bool { return f.start < p[1] && f.end > p[0] })
}
if len(found) == 0 {
return s, 0
}
}
// the first to start, and of those the longest, wins where they overlap;
// of two the same, the rule found first, so a value's placeholder is the
// same every time (an API key in API_KEY=… is an API_KEY, not a SECRET)
sort.SliceStable(found, func(i, j int) bool {
if found[i].start != found[j].start {
return found[i].start < found[j].start
}
return found[i].end > found[j].end
})
var b strings.Builder
last, next, n := 0, 0, 0 // next: where the next value may start
for _, f := range found {
if f.start < next {
continue
}
next = f.end
v := s[f.start:f.end]
if o.allows(v) {
continue
}
act := o.Actions[f.kind]
if act != Warn && act != Block {
act = ""
}
h := Hit{Kind: f.kind, By: f.by, Action: act}
h.Head, h.Len = Hint(f.kind, v)
if act == Warn {
if o.Seen != nil {
h.Placeholder = tag(f.kind, v)
o.Seen(h)
}
continue
}
b.WriteString(s[last:f.start])
h.Placeholder = put(f.kind, v)
b.WriteString(h.Placeholder)
if o.Seen != nil {
o.Seen(h)
}
last, n = f.end, n+1
}
b.WriteString(s[last:])
return b.String(), n
}
// allows says the user lets v go as written (Options.Allow).
func (o Options) allows(v string) bool {
for _, a := range o.Allow {
if strings.EqualFold(strings.TrimSpace(a), v) {
return true
}
}
return false
}
func containsAny(s string, subs []string) bool {
for _, x := range subs {
if strings.Contains(s, x) {
return true
}
}
return false
}
// ---- 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, "_") {
return s
}
mu.RLock()
defer mu.RUnlock()
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 {
continue
}
a, z = braces(s, a, z)
if a < last {
continue
}
b.WriteString(s[last:a])
if escaped {
v = jsonEscape(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
// user's rule may name one up to maxKind long), _, the 8 of the hash, }}.
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, 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
}
if i > 0 && s[i-1] == '{' {
i--
}
t := s[i:]
if len(t) >= maxPlaceholder+4 || strings.Contains(t, "}}") {
return 0
}
body := strings.TrimLeft(t, "{")
body = strings.TrimLeft(body, " \t")
if body == "" {
return len(t) // {, {{, {{␠
}
if c := body[0]; !(c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
return 0
}
j := 0
for j < len(body) && isWordByte(body[j]) {
j++
}
rest := strings.TrimLeft(body[j:], " \t")
if rest != "" && rest != "}" {
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
}