Files
magpie/internal/redact/shape.go
T
yetone 189db9ba5b redact: ids, digests and 毛利 go as written; the slider reaches known values; a user name goes as a made-up name
Reports on X under the masking demo (10-28):

_kaichen: "hash类型也会被过滤…长int,假如以1为开头的…会被当作电话被mask;
"毛利低"也会被当作人名被mask。即使把匹配拉到 0.95,也是一样行为".

- Hex digests: 16 to 31 hex digits in one case, with letters and digits
  both (a cache key, a short commit), are ids now (digestShaped in
  ids.go), like UUIDs and 32+ hex. The rules' SECRET keeps one only under
  a credential's field or a CJK/prose key with no field word (密钥为…);
  the model's SECRET is dropped under a field named for something else
  (cache_key, commit, object, blob, file, content, revision, partition,
  shard, bucket, dedup, lookup, row, sort) and on a JSON object's key
  (nameOfField). A bare `key` after api/access/secret/private/signing/
  license is still a credential (keyPhrase). The IBAN case kept its mask
  through the letter/digit minimums.
- 11-digit 1x numbers (phone.go, phoneAt): a phone with +86/86, as the
  value of a field whose name says phone (phone, mobile, tel, cell,
  contact, 手机, 电话, `number`), or in prose with no id word right
  before it (order, id, no., #, 订单号, 编号, 单号, 流水号…). Under
  order_id/uid, after 订单号, or with a letter or digit against it, it
  goes as written. PHONE and BANK_CARD are bounded by alnum, not digits,
  in the rule and in known values.
- 毛利: zhWords gained 毛利, 毛重, 毛坯, 毛巾, 毛衣, so 毛利低 (a margin)
  is no surname+name. The model still finds 毛利兰 (Guard). 毛利小五郎
  (indekkusu141209) is masked by neither model nor the rules now.
- The slider: a value masked once was masked again as known whatever the
  threshold. Each value now remembers the highest score it was found
  with (rules count as sure, ruleFound), and knownSpans skips one under
  Options.MinScore, which masking sets from pii.Threshold.

eerttreeeert: with mimo-v2.6-flash the home folder went as
C:\Users\{{USERNAME_…}}; the model took it for a temp folder and set out
to delete it. With the user name switch on, it now goes as a made-up name
of 8 lowercase letters (HMAC of the name, same every turn, standIn in
shape.go), restored in replies and tool calls like any placeholder;
Preview shows the same name.

Docs: docs/subsystems/gateway-routing.md masking bullets, and the site's
masking page (en, zh, ja) on mobile ids and the user name.

Run (mote, at this tree on base 6af83172d; rebased onto b01193ef9, which
changes nothing in redact, masking or pii, and redact, masking and
pii/... run again ok at the pushed head):
- gofmt -l clean; go vet ./... and GOOS=darwin/linux/windows go vet of
  redact, masking, pii: ok.
- go test -count=1 -timeout 45m redact, masking, pii/..., gateway, otlp,
  sessions, settings: all ok but internal/gateway's
  TestPluginStreamsPastTheBudgetWait (connection reset by peer, 183 of
  192), red the same alone at fresh origin/main b01193ef9 (169 of 192);
  #3946, commented.
- Real models on mote (AstrLink Guard and Privacy Filter, cached): the
  reporter's hashes, ids and every 毛利低 sentence kept; a prose phone
  masked; 毛利兰是谁 masked by Guard; 毛利小五郎姓什么 kept by both.

Broken by hand, each red: phoneAt off; the phone bound back to digits;
digestShaped off; "cache" out of the field list; nameOfField off; the
model's field check off; 毛利 out of zhWords; the slider check out of
knownSpans; standIn off.

Not tried: a real mimo-v2.6-flash session with the made-up name; the
Windows box; the GUI suite (no GUI file changed). 毛利小五郎 stays
unmasked by rules and both models, said in the doc.
2026-10-28 16:05:19 +08:00

323 lines
8.8 KiB
Go

package redact
import (
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
"regexp"
"slices"
"strings"
)
// A key can go to the vendor as a made-up key of its own form instead of
// a placeholder (Options.Shape): sk_w3axCByTQgK1Px… as sk_hYQWRBFmdHNI…,
// with the same prefix, length and separators and the same kind of
// character in each place. An agent's or a tool's check of a key's form
// passes, and the model has no placeholder to remark on (Charles Cao on X).
// It is made from the placeholder key as a placeholder is, so one key goes
// as the same made-up one every turn and a vendor's cache still matches,
// and it comes back as it was wherever the vendor writes it.
//
// Only a secret's kind, of minShape characters or more with minRandom of
// them made up (not its prefix or separators), and only letters, digits,
// '-', '_' and '.': a made-up key like that is in no other text by chance,
// and it needs no escaping in JSON. Anything else goes as a placeholder
// still. 16 left a short key such as sk_abcdefg a placeholder, which read
// as the setting not working.
const (
minShape = 8
minRandom = 6
)
var (
// shapes are the made-up keys in values, with their kinds; guarded by
// mu, as values is
shapes = map[string]string{}
)
// keyPrefixes name a key's kind across more than one part, and are kept as
// they are; keyHead keeps one part of a few letters.
var keyPrefixes = []string{"sk-ant-api03-", "sk-ant-oat01-", "sk-ant-admin01-", "sk-proj-", "sk-svcacct-", "sk-or-v1-", "github_pat_"}
// keyHead is the start of v that names its kind and stays as it is: one of
// keyPrefixes, or up to four letters and the '-' or '_' after them (sk-,
// ghp_, xoxb-), or AWS's AKIA and ASIA. A head without its separator could
// be the key's own random letters, which stay with the user.
func keyHead(v string) string {
for _, p := range keyPrefixes {
if strings.HasPrefix(v, p) {
return p
}
}
if strings.HasPrefix(v, "AKIA") || strings.HasPrefix(v, "ASIA") {
return v[:4]
}
for i := 0; i < len(v) && i <= 4; i++ {
c := v[i]
if (c == '-' || c == '_') && i > 0 {
return v[:i+1]
}
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
break
}
}
return ""
}
// namedValue is a name before = or : and the value after it.
var namedValue = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_.-]*[ \t]*[=:][ \t]*()`)
// splitName parts a value found with its name, as 密钥
// OPENAI_API_KEY=sk_… is, into the name, which stays as written, and the
// key after it, which alone is made up and put back.
func splitName(v string) (name, key string) {
if m := namedValue.FindStringSubmatchIndex(v); m != nil {
return v[:m[2]], v[m[2]:]
}
return "", v
}
func shapeByte(c byte) bool {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_' || c == '.'
}
// shapeOf is the made-up key v of kind goes as, if it may go as one.
func shapeOf(kind, v string) (string, bool) {
if _, personal := kindCats[kind]; personal || kind == "TERM" || len(v) < minShape {
return "", false
}
for i := 0; i < len(v); i++ {
if !shapeByte(v[i]) {
return "", false
}
}
head := keyHead(v)
rest := v[len(head):]
// a hex key's characters are any hex digit, of the case it has
hexLower, hexUpper := true, true
for i := 0; i < len(rest); i++ {
c := rest[i]
switch {
case c >= '0' && c <= '9', c == '-' || c == '_' || c == '.':
case c >= 'a' && c <= 'f':
hexUpper = false
case c >= 'A' && c <= 'F':
hexLower = false
default:
hexLower, hexUpper = false, false
}
}
h := hmac.New(sha256.New, key())
h.Write([]byte("shape\x00" + kind + "\x00" + v))
seed := h.Sum(nil)
var stream []byte
n := 0
next := func(k int) byte {
if len(stream) == 0 {
h := hmac.New(sha256.New, seed)
var c [8]byte
binary.BigEndian.PutUint64(c[:], uint64(n))
n++
h.Write(c[:])
stream = h.Sum(nil)
}
b := stream[0]
stream = stream[1:]
return b % byte(k)
}
const (
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lower = "abcdefghijklmnopqrstuvwxyz"
digit = "0123456789"
)
out, made := []byte(head), 0
for i := 0; i < len(rest); i++ {
c := rest[i]
set := ""
switch {
case c == '-' || c == '_' || c == '.':
case hexLower:
set = digit + "abcdef"
case hexUpper:
set = digit + "ABCDEF"
case c >= 'A' && c <= 'Z':
set = upper
case c >= 'a' && c <= 'z':
set = lower
default:
set = digit
}
if set == "" {
out = append(out, c)
continue
}
made++
out = append(out, set[next(len(set))])
}
if made < minRandom {
return "", false
}
f := string(out)
return f, f != v
}
// shaped is put for Options.Shape: v as a made-up key of its form where it
// may go as one, else as its placeholder.
func shaped(kind, v string) string {
name, k := splitName(v)
f, ok := shapeOf(kind, k)
if !ok {
return placeholder(kind, v)
}
mu.Lock()
have, taken := values[f]
if !taken {
makeRoom()
values[f] = k
kinds[kind] = true
shapes[f] = kind
addKnown(f, k)
}
mu.Unlock()
if taken && have != k {
// another value's made-up key, which nothing ever is by chance
return placeholder(kind, v)
}
return name + f
}
// restoreShapes puts back each made-up key in s, counting it in put
// where put isn't nil; called with mu held for reading. A made-up key
// needs no escaping, nor does the value it stands for.
func restoreShapes(s string, put map[string]int) string {
for f := range shapes {
if n := strings.Count(s, f); n > 0 {
s = strings.ReplaceAll(s, f, values[f])
if put != nil {
put[f] += n
}
}
}
return s
}
// shapeTail is how much of the end of s may be the start of a made-up
// key, which the next piece of a stream goes on with: the longest end of s
// that one of them starts with, after the last whole one in s. A key that
// ends as one starts (…sqZs, sk_…) has come whole, and is put back whole.
func shapeTail(s string) int {
mu.RLock()
defer mu.RUnlock()
whole := 0
for f := range shapes {
if i := strings.LastIndex(s, f); i >= 0 {
whole = max(whole, i+len(f))
}
}
best := 0
for f := range shapes {
for k := min(len(f)-1, len(s)-whole); k > best; k-- {
if strings.HasSuffix(s, f[:k]) {
best = k
break
}
}
}
return best
}
// hasShapes says some made-up key is in b. With none made, as while
// Options.Shape is off, a whole reply isn't copied to find out.
func hasShapes(b []byte) bool {
mu.RLock()
defer mu.RUnlock()
if len(shapes) == 0 {
return false
}
s := string(b)
for f := range shapes {
if strings.Contains(s, f) {
return true
}
}
return false
}
// outsideShapes is found without what lies in a made-up key already in s,
// as a placeholder's inside is left alone: a key that came back unrestored
// is not masked again as a key of its own.
func outsideShapes(s string, found []span) []span {
mu.RLock()
defer mu.RUnlock()
for f := range shapes {
for i := 0; ; {
j := strings.Index(s[i:], f)
if j < 0 {
break
}
a, z := i+j, i+j+len(f)
found = slices.DeleteFunc(found, func(x span) bool { return x.start < z && x.end > a })
i = z
}
}
return found
}
// A user name goes to the vendor as a made-up name, not a placeholder:
// C:\Users\eerttreeeert as C:\Users\qmzvkrta, never C:\Users\{{USERNAME_…}}.
// A path with braces in it reads as a template's or a temporary folder's,
// and an agent on mimo-v2.6-flash took the user's home for a temporary
// folder and set out to delete it (eerttreeeert on X, 10-28). A made-up
// name keeps the path a home folder's, which is what it is, and still
// tells the vendor nothing of the user. It is made from the name as a
// made-up key is (shapeOf), so it is the same every turn and a vendor's
// cache still matches, and it is put back wherever the vendor writes it
// (restoreShapes), in a tool call's path too. Only USERNAME's: what the
// user chose to mask (their words) goes as they chose.
// standInLen is a made-up name's length: eight lowercase letters, which
// read as a login name and are in no other text by chance.
const standInLen = 8
// standInOf is the made-up name the user name v goes as.
func standInOf(v string) string {
h := hmac.New(sha256.New, key())
h.Write([]byte("user\x00" + v))
sum := h.Sum(nil)
out := make([]byte, standInLen)
for i := range out {
out[i] = 'a' + sum[i]%26
}
return string(out)
}
// standIn is put with a user name sent as its made-up name, which is
// kept to be put back as a made-up key is; put's own where that name is
// another value's already.
func standIn(put func(kind, v string) string) func(kind, v string) string {
return func(kind, v string) string {
if kind != "USERNAME" {
return put(kind, v)
}
f := standInOf(v)
if f == v {
return put(kind, v)
}
mu.Lock()
have, taken := values[f]
if !taken {
makeRoom()
values[f] = v
kinds[kind] = true
shapes[f] = kind
addKnown(f, v)
}
mu.Unlock()
if taken && have != v {
return put(kind, v)
}
return f
}
}