redact: a user name's and an address's stand-ins come back in any case (yapechan on Discord)

yapechan (Discord #feedback): with masking on, a person's name sometimes
came back as letters that are no one's, with no {{…}} braces. A user name
in a home folder goes to the vendor as eight made-up lowercase letters
(standInOf). When the login name is the user's own name (yaobin), a model
takes those letters for the user's name and writes them as a name is
written, "作者:Tmhdfetm", "Hi Tmhdfetm,". restoreShapes put a stand-in
back only as written, so a capitalised or upper-case one reached the user
as garbage. An IP stand-in (public-ip-…), a host name that is the same in
any case, had the same gap.

Now a USERNAME or IP stand-in is put back in any ASCII case: in Restore,
RestoreJSON (hasShapes), a stream's held tail (shapeTail) and
outsideShapes. Matching uses an ASCII-lowered copy of the same length
(lowerASCII, which now returns s itself with no capital in it, so there
is no copy), and strings.Index runs once per stand-in as before. An IP
stand-in is still put back only as a whole name. A key's made-up form
(Options.Shape) is still put back only as written, because a key's case
is part of it.

The restart question: the placeholder-to-value map is in memory only.
But a placeholder is an HMAC of its value under a key kept on disk
(redact.key, 0600, SetKeyPath from the gateway), and an agent resends its
history with the values on every turn. So after a restart the same value
goes as the same placeholder and the reply comes back whole.
TestPlaceholdersOutliveARestart now guards that, using the reporter's
姚斌 as a user word. Nothing new is written to disk.

Not found in magpie: a homophone (姚斌 -> 姚兵). Nothing in redact, pii
or restore maps a name by sound. A value goes back only for its own
placeholder or stand-in. The test records that 姚兵 goes back as the
vendor wrote it. Most likely the vendor model wrote it from a
romanisation it saw (a login name, an address); this is not reproduced.

Run at 19e9f7a82 (rebased on 4fc34828e), on mote:
- go test ./internal/redact ./internal/masking ./plugins/redact: ok
- go test -run 'Redact|Mask|Placeholder|Restore' ./internal/gateway: ok
- before the rebase, the whole ./internal/gateway (-timeout 45m): one red,
  TestCodexPoolSaysTheClientsVersion, which is #4807 (another test's
  Codex identity reaches it in a full run). It passes alone -count=3 at
  this head, and it does not touch masking.
- GOOS=linux and GOOS=windows go vet ./internal/redact ./internal/gateway: ok
- gofmt -l: clean
Broken by hand: with the old shape.go, both InAnyCase tests are red
(Restore, RestoreJSON and the stream at every cut). With loadKey ignoring
the key file, TestPlaceholdersOutliveARestart is red (new placeholders,
reply left as {{TERM_…}}).
Not tried: a real vendor writing a capitalised stand-in. The reporter's
own session and records were not seen. The GUI was not run (no GUI
change).
This commit is contained in:
yetone
2026-11-02 13:58:47 +08:00
parent 4fc34828e5
commit d577c184b3
3 changed files with 272 additions and 32 deletions
+12 -3
View File
@@ -1501,11 +1501,20 @@ func (r rule) matches(s, lower string) [][]int {
}
// 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.
// place in one is the same place in the other (a byte of a character
// outside ASCII is never an ASCII letter). It is s itself, not a copy,
// where s has no capital.
func lowerASCII(s string) string {
i := 0
for i < len(s) && !('A' <= s[i] && s[i] <= 'Z') {
i++
}
if i == len(s) {
return s
}
b := []byte(s)
for i, c := range b {
if 'A' <= c && c <= 'Z' {
for ; i < len(b); i++ {
if c := b[i]; 'A' <= c && c <= 'Z' {
b[i] = c + 'a' - 'A'
}
}
+81 -29
View File
@@ -194,42 +194,74 @@ func shaped(kind, v string) string {
// needs no escaping, nor does the value it stands for. An address's
// stand-in is put back only where it is a whole name: public-ip-kvxqmrtz
// is no part of public-ip-kvxqmrtzab or my-public-ip-kvxqmrtz.
//
// A user name's and an address's stand-ins are put back in any case
// (foldStandIn). A model takes a made-up login name for the user's own
// name and writes it as one: "Hi Qmzvkrta," or "作者:Qmzvkrta", which
// came back to the user as letters that are no one's (yapechan on
// Discord: a name was put back as garbage, with no braces). A host's name
// is the same in any case too. Eight made-up letters are in no other text
// by chance in any case, as a placeholder's 8 of its hash are not
// (canonical). A key's made-up form is put back only as written: a key's
// case is part of it.
func restoreShapes(s string, put map[string]int) string {
lower, stale := "", true // s in small letters, made when first needed
for f, kind := range shapes {
if kind == "IP" {
s = restoreAddr(s, f, values[f], put)
if !foldStandIn(kind) {
if n := strings.Count(s, f); n > 0 {
s = strings.ReplaceAll(s, f, values[f])
stale = true
if put != nil {
put[f] += n
}
}
continue
}
if n := strings.Count(s, f); n > 0 {
s = strings.ReplaceAll(s, f, values[f])
if put != nil {
put[f] += n
}
if stale {
lower, stale = lowerASCII(s), false
}
if !strings.Contains(lower, f) {
continue
}
whole := wholeAddr
if kind != "IP" {
whole = nil
}
if out := replaceStandIn(s, lower, f, values[f], put, whole); out != s {
s, stale = out, true
}
}
return s
}
// restoreAddr is s with each whole stand-in f in it put back as the
// address v, counted in put where put isn't nil: not where a letter, a
// digit, '-' or '_' is against it, or a dot before it or before a letter
// or digit after it, which make it a piece of another name
// (public-ip-kvxqmrtz.lan); a port, a path or a full stop may follow it.
func restoreAddr(s, f, v string, put map[string]int) string {
if !strings.Contains(s, f) {
return s
}
// foldStandIn says a made-up key of kind is a stand-in of lowercase
// letters (standInOf, ipStandIns), found in any case.
func foldStandIn(kind string) bool { return kind == "USERNAME" || kind == "IP" }
// wholeAddr says s[a:z], an address's stand-in, is a whole name: not
// where a letter, a digit, '-' or '_' is against it, or a dot before it
// or before a letter or digit after it, which make it a piece of another
// name (public-ip-kvxqmrtz.lan); a port, a path or a full stop may
// follow it.
func wholeAddr(s string, a, z int) bool {
return !(a > 0 && (nameByte(s[a-1]) || s[a-1] == '.') || z < len(s) && nameByte(s[z]) ||
z+1 < len(s) && s[z] == '.' && nameByte(s[z+1]))
}
// replaceStandIn is s with each stand-in f in it, in any case (found in
// lower, lowerASCII(s)), put back as v where whole says it may be
// (anywhere with whole nil), counted in put where put isn't nil.
func replaceStandIn(s, lower, f, v string, put map[string]int, whole func(s string, a, z int) bool) string {
var b strings.Builder
last := 0
for i := 0; ; {
j := strings.Index(s[i:], f)
j := strings.Index(lower[i:], f)
if j < 0 {
break
}
a, z := i+j, i+j+len(f)
i = a + 1
if a > 0 && (nameByte(s[a-1]) || s[a-1] == '.') || z < len(s) && nameByte(s[z]) ||
z+1 < len(s) && s[z] == '.' && nameByte(s[z+1]) {
if whole != nil && !whole(s, a, z) {
continue
}
b.WriteString(s[last:a])
@@ -259,16 +291,21 @@ func nameByte(c byte) bool {
func shapeTail(s string) int {
mu.RLock()
defer mu.RUnlock()
lower := lowerASCII(s)
whole := 0
for f := range shapes {
if i := strings.LastIndex(s, f); i >= 0 {
for f, kind := range shapes {
i := strings.LastIndex(s, f)
if foldStandIn(kind) {
i = strings.LastIndex(lower, f)
}
if i >= 0 {
whole = max(whole, i+len(f))
}
}
best := 0
for f := range shapes {
for f, kind := range shapes {
for k := min(len(f)-1, len(s)-whole); k > best; k-- {
if strings.HasSuffix(s, f[:k]) {
if strings.HasSuffix(s, f[:k]) || foldStandIn(kind) && strings.HasSuffix(lower, f[:k]) {
best = k
break
}
@@ -286,10 +323,19 @@ func hasShapes(b []byte) bool {
return false
}
s := string(b)
for f := range shapes {
lower := ""
for f, kind := range shapes {
if strings.Contains(s, f) {
return true
}
if foldStandIn(kind) {
if lower == "" {
lower = lowerASCII(s)
}
if strings.Contains(lower, f) {
return true
}
}
}
return false
}
@@ -300,13 +346,19 @@ func hasShapes(b []byte) bool {
func outsideShapes(s string, found []span) []span {
mu.RLock()
defer mu.RUnlock()
for f := range shapes {
lower := lowerASCII(s)
for f, kind := range shapes {
in := s
if foldStandIn(kind) {
in = lower
}
for i := 0; ; {
j := strings.Index(s[i:], f)
if j < 0 {
a := strings.Index(in[i:], f)
if a < 0 {
break
}
a, z := i+j, i+j+len(f)
a += i
z := a + len(f)
found = slices.DeleteFunc(found, func(x span) bool { return x.start < z && x.end > a })
i = z
}
@@ -359,7 +411,7 @@ func standInOf(v string) string {
// with no dot in it is no one's on the internet, so a stand-in the vendor
// tries itself reaches nobody. The same address gets the same stand-in
// every turn while magpie runs, and two addresses never share one; it is
// put back only as a whole name (restoreAddr).
// put back only as a whole name (wholeAddr).
// ipStandInHead starts every address's stand-in, and ipStandInLen
// letters follow it.
+179
View File
@@ -0,0 +1,179 @@
package redact
import (
"encoding/json"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
// A user name's made-up name comes back as the user's in any case the
// model writes it. Its login name was the user's own (yaobin), and a model
// took the made-up one for the user's name and wrote it as a name is
// written, capitalised; it came back to the user as letters that are no
// one's, with no braces (yapechan on Discord).
func TestUserNameStandInPutBackInAnyCase(t *testing.T) {
Forget()
t.Cleanup(Forget)
o := Options{Personal: true, Kinds: map[string]bool{"home": true}}
out, n := Mask("cd /Users/yaobin/workspace/report && git log", o)
f := standInOf("yaobin")
if n != 1 || !strings.Contains(out, "/Users/"+f+"/") {
t.Fatalf("sent %q, want the user name as %q", out, f)
}
title := strings.ToUpper(f[:1]) + f[1:]
upper := strings.ToUpper(f)
for _, c := range []struct{ s, want string }{
{"作者:" + title + ",路径 /Users/" + f + "/workspace", "作者:yaobin,路径 /Users/yaobin/workspace"},
{"Hi " + title + ", the report is done.", "Hi yaobin, the report is done."},
{"OWNER=" + upper, "OWNER=yaobin"},
{"/Users/" + title + "/x", "/Users/yaobin/x"},
} {
if got := Restore(c.s, false); got != c.want {
t.Errorf("Restore(%q) = %q, want %q", c.s, got, c.want)
}
}
if !hasShapes([]byte(`{"text":"` + title + `"}`)) {
t.Errorf("a reply with %q is not looked at", title)
}
if got := string(RestoreJSON([]byte(`{"text":"致 ` + title + `"}`))); got != `{"text":"致 yaobin"}` {
t.Errorf("RestoreJSON = %s", got)
}
// streamed, cut at every place in the capitalised name
whole := "报告作者:" + title + "。"
for cut := strings.Index(whole, title); cut <= strings.Index(whole, title)+len(title); cut++ {
ev := func(text string) string {
b, _ := json.Marshal(map[string]any{"choices": []any{map[string]any{"index": 0, "delta": map[string]any{"content": text}}}})
return "data: " + string(b) + "\n\n"
}
rec := httptest.NewRecorder()
rec.Header().Set("Content-Type", "text/event-stream")
w := NewWriter(rec)
w.WriteHeader(200)
for _, e := range []string{ev(whole[:cut]), ev(whole[cut:]), "data: [DONE]\n\n"} {
w.Write([]byte(e))
}
w.Finish()
var got strings.Builder
for _, e := range strings.Split(rec.Body.String(), "\n\n") {
d, ok := strings.CutPrefix(e, "data: ")
if !ok || d == "[DONE]" {
continue
}
var x struct {
Choices []struct{ Delta struct{ Content string } }
}
if json.Unmarshal([]byte(d), &x) == nil && len(x.Choices) > 0 {
got.WriteString(x.Choices[0].Delta.Content)
}
}
if got.String() != "报告作者:yaobin。" {
t.Errorf("cut at %d: streamed %q", cut, got.String())
}
}
}
// An address's stand-in is a host's name, the same in any case, and comes
// back so; still only where it is a whole name.
func TestIPStandInPutBackInAnyCase(t *testing.T) {
Forget()
t.Cleanup(Forget)
const ip = "47.96.123.45"
out, _ := Mask("服务器 "+ip+" 连不上", Options{Personal: true, Kinds: map[string]bool{"ip": true}})
f := strings.Fields(out)[1]
if !isIPStandIn(f) {
t.Fatalf("sent %q", out)
}
up := strings.ToUpper(f)
for _, c := range []struct{ s, want string }{
{"ssh root@" + up, "ssh root@" + ip},
{"Host " + strings.ToUpper(f[:1]) + f[1:] + ":22", "Host " + ip + ":22"},
{"my-" + up, "my-" + up},
{up + ".lan", up + ".lan"},
} {
if got := Restore(c.s, false); got != c.want {
t.Errorf("Restore(%q) = %q, want %q", c.s, got, c.want)
}
}
}
// A key's made-up form keeps its case: one that differs from it in case
// is another key, and goes back as written.
func TestShapedKeyPutBackOnlyAsWritten(t *testing.T) {
Forget()
t.Cleanup(Forget)
const key = "sk_w3axCByTQgK1Px9bLmQr7Zt"
out, _ := Mask("OPENAI_API_KEY="+key, Options{Secrets: true, Shape: true})
f := strings.TrimPrefix(out, "OPENAI_API_KEY=")
if f == key || strings.Contains(f, "{{") {
t.Fatalf("sent %q", out)
}
if got := Restore(f, false); got != key {
t.Errorf("Restore(%q) = %q", f, got)
}
if got := Restore(strings.ToLower(f), false); got != strings.ToLower(f) {
t.Errorf("a key differing in case put back as %q", got)
}
}
// What magpie remembers of placeholders is in memory, but a placeholder is
// made from its value and a key kept on disk (SetKeyPath), so after a
// restart (an update in the background) the same value goes as the same
// placeholder, and the conversation the agent sends again has its values
// put back in the reply (yapechan on Discord asked). Names from the
// reporter: 姚斌 as one of the user's own words.
func TestPlaceholdersOutliveARestart(t *testing.T) {
Forget()
mu.Lock()
oldKey, oldPath := keyOf, keyPath
keyOf, keyPath = nil, filepath.Join(t.TempDir(), "redact.key")
mu.Unlock()
t.Cleanup(func() {
Forget()
mu.Lock()
keyOf, keyPath = oldKey, oldPath
mu.Unlock()
})
path := keyPath
o := Options{Words: []string{"姚斌"}}
history := "请把周报发给姚斌,抄送姚斌的主管。"
before, n := Mask(history, o)
if n != 2 || strings.Contains(before, "姚斌") {
t.Fatalf("sent %q", before)
}
p := placeholderRe.FindString(before)
reply := "好的,已发给 " + p + ",并抄送 " + p + " 的主管。"
// magpie starts again: nothing in memory, the key read from disk
Forget()
mu.Lock()
keyOf = nil
mu.Unlock()
SetKeyPath(path)
if b, err := os.ReadFile(path); err != nil || len(b) < 32 {
t.Fatalf("key not kept: %v", err)
}
after, _ := Mask(history, o)
if after != before {
t.Errorf("after a restart the history went as %q, before as %q", after, before)
}
want := "好的,已发给 姚斌,并抄送 姚斌 的主管。"
if got := Restore(reply, false); got != want {
t.Errorf("the reply put back as %q, want %q", got, want)
}
// as a model writes it back: without its braces, in another case
bare := strings.Trim(p, "{}")
for _, s := range []string{bare, strings.ToLower(bare), "{{ " + bare + " }}", "{" + bare + "}"} {
if got := Restore("发给 "+s+"。", false); got != "发给 姚斌。" {
t.Errorf("Restore(%q) = %q", s, got)
}
}
// nothing puts back a name that sounds like it: 姚兵 is the vendor's
// own text, and goes to the user as the vendor wrote it
if got := Restore("发给姚兵。", false); got != "发给姚兵。" {
t.Errorf("Restore(姚兵) = %q", got)
}
}