diff --git a/internal/redact/redact.go b/internal/redact/redact.go index 67963a534..9ec432c78 100644 --- a/internal/redact/redact.go +++ b/internal/redact/redact.go @@ -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' } } diff --git a/internal/redact/shape.go b/internal/redact/shape.go index 9b14f145e..9e7888544 100644 --- a/internal/redact/shape.go +++ b/internal/redact/shape.go @@ -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. diff --git a/internal/redact/standin_case_test.go b/internal/redact/standin_case_test.go new file mode 100644 index 000000000..e58610538 --- /dev/null +++ b/internal/redact/standin_case_test.go @@ -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) + } +}