Files
magpie/internal/redact/known.go
T
yetone d7a1b02032 redact: more kinds of personal data, each with its own switch: SSNs, passports, IBANs, birthdays, MAC addresses and serial numbers on by default; home-folder names, user@host, public IPs and cloud buckets off (lc on Discord)
lc asked in #feedback (message 1558300896142696549) for magpie's masking
to cover more of what identifies a person or a machine. Under Settings >
Privacy > Mask personal data, each kind now has its own Off/On
(settings.redactKinds, redact.Options.Kinds). What each one masks:

- US SSNs: dashed numbers, except ones never issued (000, 666 and 9xx
  areas) and well-known examples. Undashed ones only next to "SSN" or
  "social security".
- Passport numbers, next to passport, Reisepass, 护照 or パスポート.
- IBANs: compact or in groups of four, with the country's length and the
  mod-97 check.
- Birthdays: a date only next to birthday, DOB, born, 生日 and the like.
  A date on its own stays.
- MAC addresses, but not documentation examples or all-decimal groups.
- Serial numbers, next to S/N, serial or 序列号.
- The user name in /Users/x, /home/x and C:\Users\x. The name is masked
  and the path is kept.
- User and host in a shell prompt or an ssh/scp/rsync target (user@host
  goes out as two placeholders, not as an email address), and on
  hostname/user lines whose value ends the line. Code such as
  `hostname = socket.gethostname()` is left alone.
- Public IPv4 and IPv6 addresses. Private, loopback, link-local, CGNAT,
  documentation, multicast and well-known resolver addresses stay, and so
  do version numbers.
- Cloud bucket names in s3://, gs://, oss://, cos://, abfss:// and
  storage URLs. The object path is kept.

The last four are off by default. Agents send their working folder, the
prompt and log lines in nearly every request, and the model then has to
copy the placeholder exactly inside a path or URL. The first six are
rare and sensitive, so they are on. Each placeholder is restored in
replies, in streamed text and in tool-call JSON. Context rules run only
in a window around their words (rule.matches), so masking with the
defaults on 400KB of app.js takes 136ms (112ms before; 222ms with every
kind on).

Tests, run at this head:
- gofmt -l is clean. go vet passes on darwin, GOOS=linux and
  GOOS=windows (-tags nogui) for internal/redact, gateway, gui and
  settings.
- go test -tags nogui ./... under a temp HOME with pinned caches passed
  everywhere except internal/proc's TestNoCommandBypassesProc. That
  failure came from 2da8fbe4, and b934d64a fixed it on main. After the
  rebase, the changed packages and internal/proc were run again and
  passed. New tests:
  - internal/redact TestMoreKinds, TestMoreKindsLeaveAlone (versions,
    timestamps, hashes, UUIDs, model ids, code, ordinary dates, URLs in
    code), TestCategoryDefaults, TestMoreKindsKnown, TestMoreKindsJSON.
  - internal/gateway TestRedactedKinds.
  - internal/gui TestRedactKindsAreRedacts.
- I broke the IBAN checksum by hand and TestMoreKindsLeaveAlone went
  red.
- GUI tests pass in Chromium and WebKit:
  - the new redact-kinds.test.cjs (en, zh, zh-TW, ja and de, at 1100
    and 640 px);
  - i18n-keys, gui-de, gui-ja, gui-zh-tw, redact-rule-row,
    privacy-hides-accounts, privacy-usage-stats, settings-groups,
    settings-sections and mobile-web;
  - 29 more files that open the Privacy page (252 tests).
  privacy-usage-stats now scrolls with the wheel to reach Count me as a
  user, which the new rows push below its 760px window. WebKit doesn't
  let a script scroll Settings.
- Real gateway check: a `magpie serve` built from this tree, under a
  sandbox HOME, on 127.0.0.1:3492, with a fake OpenAI upstream on 3491.
  An Anthropic /v1/messages request went to the upstream with each kind
  as a placeholder. Turning SSNs off and home folders on changed what
  was sent the same way. The streamed reply came back with every value
  restored.
2026-10-10 11:29:03 +08:00

188 lines
5.7 KiB
Go

package redact
import (
"slices"
"strings"
)
// A value masked once is masked again wherever it is in a request, as it
// is, whatever is around it. The rules find a value by what is around it
// (DB_PASSWORD=, a bound an email may not touch), and the vendor answers
// about a placeholder in words of its own: "the password is {{SECRET_…}}",
// "write to {{EMAIL_…}}.". The agent reads the value there (Restore), and
// on the next turn that text comes back in the history, where no rule
// matches it. Matched as known, it goes as the same placeholder again.
//
// What is known is what values holds (in memory only, bounded by
// maxValues): the values of the placeholders made since magpie started,
// for every request alike, since a placeholder is the same for the same
// value whichever conversation it is in.
// minKnown is the shortest value matched as known. Shorter ones (a
// password of three letters in a URL, which the rule takes from its
// user:password@) would turn up all over ordinary text; 8 is what the rule
// for a password in an assignment asks of its value.
const minKnown = 8
type knownValue struct{ v, p, kind string }
var (
// known are the values matched as known, by their first minKnown
// bytes; guarded by mu, as values is
known = map[string][]knownValue{}
// knownBits has a bit for the first four bytes of each known value, so
// most places in a text are passed over without a map lookup
knownBits [1 << 14]uint64
)
func gram(s string, i int) uint32 {
g := uint32(s[i]) | uint32(s[i+1])<<8 | uint32(s[i+2])<<16 | uint32(s[i+3])<<24
return (g * 2654435761) >> 12 // 20 bits
}
// addKnown adds the value of placeholder p; called with mu held. The
// user's own words are left to Options.Words, which match them anywhere
// already, and are only as long as two letters.
func addKnown(p, v string) {
kind := kindOf(p)
if kind == "TERM" || len(v) < minKnown {
return
}
head := v[:minKnown]
for i, k := range known[head] {
if k.v == v {
// one value under two kinds: the same one wins whichever came
// first, so it is the same after reindexKnown
if p < k.p {
known[head][i] = knownValue{v, p, kind}
}
return
}
}
known[head] = append(known[head], knownValue{v, p, kind})
g := gram(v, 0)
knownBits[g/64] |= 1 << (g % 64)
}
// reindexKnown makes known again from values, after some were let go;
// called with mu held.
func reindexKnown() {
known = map[string][]knownValue{}
knownBits = [1 << 14]uint64{}
for p, v := range values {
addKnown(p, v)
}
}
// kindOf is the kind in a placeholder: SECRET of {{SECRET_abcdefgh}}.
func kindOf(p string) string {
if i := strings.LastIndexByte(p, '_'); i > 2 {
return p[2:i]
}
return ""
}
// kindCats are the categories each kind of personal data is found under
// (Options.covers): a user name is under both home folders and user@host.
// A kind not in it is a secret's, the user's rules' among them.
var kindCats = func() map[string][]string {
m := map[string][]string{}
for _, r := range rules {
kinds := r.groups
if len(kinds) == 0 {
kinds = []string{r.kind}
}
for _, k := range kinds {
if r.cat != "" && !slices.Contains(m[k], r.cat) {
m[k] = append(m[k], r.cat)
}
}
}
return m
}()
// coversKind says o masks a known value of kind: a personal one when one
// of the categories it is found under is on, any other when o masks
// secrets.
func (o Options) coversKind(kind string) bool {
cats, ok := kindCats[kind]
if !ok {
return o.Secrets
}
for _, c := range cats {
if o.covers(c) {
return true
}
}
return false
}
// knownSpans are where s has a known value o masks (coversKind). Where two
// start at the same place, the longer.
func knownSpans(s string, o Options) []span {
if !o.Secrets && !o.Personal || len(s) < minKnown {
return nil
}
mu.RLock()
defer mu.RUnlock()
if len(known) == 0 {
return nil
}
var out []span
for i := 0; i+minKnown <= len(s); i++ {
if g := gram(s, i); knownBits[g/64]&(1<<(g%64)) == 0 {
continue
}
var best *knownValue
for j, k := range known[s[i:i+minKnown]] {
if !o.coversKind(k.kind) {
continue
}
if best != nil && len(k.v) <= len(best.v) || !strings.HasPrefix(s[i:], k.v) || !standsAlone(k.kind, s, i, i+len(k.v)) {
continue
}
best = &known[s[i:i+minKnown]][j]
}
if best != nil {
out = append(out, span{i, i + len(best.v), best.kind})
i += len(best.v) - 1
}
}
return out
}
// standsAlone says s[a:b] is the known value itself, not a piece of a
// longer one: a number with no digit beside it, an email that is not part
// of a longer address (though a full stop may end the sentence after it),
// a secret with no letter or digit against it (twelve hex digits a rule of
// the user's took are also in the middle of a hash).
func standsAlone(kind, s string, a, b int) bool {
before, after := byte(0), byte(0)
if a > 0 {
before = s[a-1]
}
if b < len(s) {
after = s[b]
}
is := func(c byte, set string) bool { return c != 0 && strings.IndexByte(set, c) >= 0 }
switch kind {
case "PHONE", "BANK_CARD":
return !is(before, digits) && !is(after, digits)
case "ID_CARD", "IBAN", "SSN", "PASSPORT", "SERIAL":
return !is(before, alnum) && !is(after, alnum)
case "IP", "MAC":
// not a piece of a longer address or a version: 1.2.3.45, 1.2.3.4.5
if is(before, alnum+".:") || is(after, alnum+":") {
return false
}
return after != '.' || b+1 >= len(s) || !is(s[b+1], digits)
case "EMAIL":
if is(before, alnum+"._%+-") || is(after, alnum+"_%+") {
return false
}
// a.b@c.com.cn is another address; a.b@c.com. ends a sentence
return !is(after, ".-") || b+1 >= len(s) || !is(s[b+1], alnum)
}
return !(is(before, alnum) && is(s[a], alnum)) && !(is(after, alnum) && is(s[b-1], alnum))
}