redact: a package's name goes as written where it was masked before, and in manifests and errors (dniray on Discord)
dniray, on v0.1.1965 after v0.1.1932's fix: "问题还在", with
import { and, eq } from ' drizzle-orm ' still going out as
from ' {{SECRET_o2tu7vej}} '.
v0.1.1932 let the module an import loads go as written only where the
local model found it on that line (moduleAt in modelFits). A value
masked once is known (knownSpans) and masked wherever it is, with no
look at what is around it. So once the model took drizzle-orm for a
secret anywhere in a request (package.json's dependencies, a tsc
error, a sentence: none of those was exempt), the import line was
masked as known: in the same request (MaskJSON walks the texts in
order) and in every later one.
- knownSpans skips a known value where packageAt says it is a
package's name.
- packageAt: moduleAt, plus a manifest's dependency pinned at a version
("drizzle-orm": "^0.36.4", workspace:*, TOML x = "9";
dependencyAt), a folder under node_modules or site-packages, the
module an error could not find (Cannot find module 'x', No module
named 'x', Can't resolve 'x'; missingModuleAt), a package an install
names (pnpm add x, npm i -D x, pip install x, cargo add x;
installedAt, not after a --token-like flag), one pinned with @
(x@0.36.4, lower case, not an IPv4 address; pinnedAt). A piece of a
name (drizzle-orm of drizzle-orm/pg-core, of @acme/drizzle-orm) is
judged as the whole name.
- moduleAt reads past an editor's line number and a diff's mark
(codeHead): Claude Code's Read gives " 1→import drizzle from
'drizzle-orm'", and a default import there wasn't an import line.
Tests: package_known_test.go.
TestKnownPackageNameGoesAsWrittenWhereCodeLoadsIt has the reporter's
literal line in a Claude Code tool_result after a sentence with the
name, in one Anthropic body, then alone (Mask, no model) and in a
second body: red on the old code at all three
(from ' {{SECRET_…}} '). TestModelPackageNamesInManifestsAndOutput: 22
shapes, red on the old code. TestPackageShapesKeepSecrets: a JSON key
with a non-version value, a password before @ip, a quoted secret on a
numbered line, prose with "install", a known secret in prose and on a
numbered line are masked still.
Run, at 936bdccfa + this change, on mote:
- go test -count=1 -timeout 45m ./internal/redact/... ./internal/masking/...
./internal/otlp/... ./internal/pii/... ./internal/sessions/...
./internal/settings/... ./internal/gwmw/...: ok (TestMaskEval's
recordings pass unchanged)
- go test -run "Redact|Mask|Privacy|Unredact|Known|Restore"
./internal/gateway ./internal/gui: ok
- go vet darwin, GOOS=linux -tags nogui, GOOS=windows on
./internal/redact/... ./internal/masking/...: ok; gofmt -l: clean
- the real AstrLink Guard and Privacy Filter on mote (zzcache), at
their default thresholds, over 12 texts: the literal line, a
numbered Read of a drizzle file, package.json, pnpm add, a tsc
error, node_modules path, prose, a .env: neither model found
drizzle-orm anywhere, and the .env's password and JWT secret were
still masked with the change.
Broken by hand, each red: the packageAt check in knownSpans off
(TestKnownPackageNameGoesAsWrittenWhereCodeLoadsIt, all three);
codeHead off and missingModuleAt/installedAt/pinnedAt off
(TestModelPackageNamesInManifestsAndOutput, 11 cases).
Not tried: what made the model take drizzle-orm for a secret on
dniray's machine. Neither real model does on any text tried, so the
fix is held by the fake model; the known path is the one way found
that v0.1.1932's check is passed by. No eval case added (recordings not
re-recorded); the full ./internal/gateway and ./internal/gui suites;
Windows and Linux runs (vet only).
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -205,6 +205,12 @@ func knownSpans(s string, o Options) []span {
|
||||
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
|
||||
}
|
||||
if packageAt(s, i, i+len(k.v)) {
|
||||
// the module an import loads, a manifest's dependency:
|
||||
// what masked it before had taken a package's name for a
|
||||
// secret (dniray, v0.1.1965)
|
||||
continue
|
||||
}
|
||||
best = &known[s[i:i+minKnown]][j]
|
||||
}
|
||||
if best != nil {
|
||||
|
||||
+202
-2
@@ -319,7 +319,7 @@ func modelFits(s string, a, b int, kind string) bool {
|
||||
// 10-28). A key is 64 hex digits; one called a key is masked still.
|
||||
return kind == "SECRET" && secretCued(s, a)
|
||||
}
|
||||
if moduleAt(s, a, b) {
|
||||
if packageAt(s, a, b) {
|
||||
return false
|
||||
}
|
||||
switch kind {
|
||||
@@ -403,7 +403,7 @@ func moduleAt(s string, a, b int) bool {
|
||||
return false
|
||||
}
|
||||
line := strings.LastIndexByte(s[:a], '\n') + 1
|
||||
head := strings.TrimLeft(s[line:a], " \t")
|
||||
head := codeHead(s[line:a])
|
||||
end := strings.IndexByte(s[b:], '\n')
|
||||
if end < 0 {
|
||||
end = len(s) - b
|
||||
@@ -439,6 +439,206 @@ func moduleAt(s string, a, b int) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// codeHead is a line of code up to a value, without what a tool puts
|
||||
// before the code: an editor's or cat -n's line number (Claude Code's
|
||||
// Read gives " 1→import drizzle from 'drizzle-orm'", cat -n a tab,
|
||||
// grep -n a colon) and a diff's + or -. With the number before it, a
|
||||
// default import was no import line (dniray, v0.1.1965).
|
||||
func codeHead(h string) string {
|
||||
h = strings.TrimLeft(h, " \t")
|
||||
i := 0
|
||||
for i < len(h) && h[i] >= '0' && h[i] <= '9' {
|
||||
i++
|
||||
}
|
||||
if i > 0 {
|
||||
for _, sep := range []string{"→", "\t", ":", "|"} {
|
||||
if strings.HasPrefix(h[i:], sep) {
|
||||
h = strings.TrimLeft(h[i+len(sep):], " \t")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if h != "" && (h[0] == '+' || h[0] == '-') {
|
||||
h = strings.TrimLeft(h[1:], " \t")
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// packageAt says s[a:b] is a package's or a module's name by where it is:
|
||||
// the module code loads (moduleAt), a dependency a manifest pins
|
||||
// (dependencyAt), a folder under node_modules or site-packages, the
|
||||
// module an error could not find (missingModuleAt), a package an install
|
||||
// names (installedAt) or one pinned at its version with @
|
||||
// (drizzle-orm@0.36.4, pinnedAt). The local model took drizzle-orm for a
|
||||
// secret in package.json, a tsc error or a sentence; masked there, the
|
||||
// name was known (knownSpans) and masked on the import line too, which
|
||||
// moduleAt had let go when the model found it there (dniray on Discord,
|
||||
// v0.1.1965: from ' {{SECRET_o2tu7vej}} ' still). knownSpans asks this
|
||||
// too: no secret is a name code loads or a manifest pins, whatever
|
||||
// found it before.
|
||||
func packageAt(s string, a, b int) bool {
|
||||
// the whole of a name a piece of it was found in: drizzle-orm of
|
||||
// drizzle-orm/pg-core, name of @scope/name
|
||||
for b+1 < len(s) && s[b] == '/' && moduleByte(s[b+1]) {
|
||||
for b++; b < len(s) && moduleByte(s[b]); b++ {
|
||||
}
|
||||
}
|
||||
if a > 2 && s[a-1] == '/' {
|
||||
i := a - 1
|
||||
for i > 0 && moduleByte(s[i-1]) {
|
||||
i--
|
||||
}
|
||||
if i < a-2 && s[i] == '@' {
|
||||
a = i
|
||||
}
|
||||
}
|
||||
if !moduleRe.MatchString(s[a:b]) {
|
||||
return false
|
||||
}
|
||||
return moduleAt(s, a, b) || dependencyAt(s, a, b) || underPackages(s, a) ||
|
||||
missingModuleAt(s, a, b) || installedAt(s, a, b) || pinnedAt(s, a, b)
|
||||
}
|
||||
|
||||
func moduleByte(c byte) bool { return wordByte(c) || c == '.' || c == '-' || c == '~' || c == '@' }
|
||||
|
||||
// dependencyAt says s[a:b] is a dependency's name as a manifest pins it:
|
||||
// a JSON key whose value is a version or a range ("drizzle-orm":
|
||||
// "^0.36.4", "x": "workspace:*") or TOML's at a line's start (jsonwebtoken
|
||||
// = "9.2.0"). A key whose value is no version ({"Zq8v…": "hunter2"}) is
|
||||
// judged as before.
|
||||
func dependencyAt(s string, a, b int) bool {
|
||||
rest := ""
|
||||
if a > 0 && s[a-1] == '"' && b < len(s) && s[b] == '"' {
|
||||
rest = strings.TrimLeft(s[b+1:], " \t")
|
||||
if !strings.HasPrefix(rest, ":") {
|
||||
return false
|
||||
}
|
||||
rest = strings.TrimLeft(rest[1:], " \t")
|
||||
} else {
|
||||
line := strings.LastIndexByte(s[:a], '\n') + 1
|
||||
if strings.Trim(s[line:a], " \t") != "" {
|
||||
return false
|
||||
}
|
||||
rest = strings.TrimLeft(s[b:], " \t")
|
||||
if !strings.HasPrefix(rest, "=") || strings.HasPrefix(rest, "==") {
|
||||
return false
|
||||
}
|
||||
rest = strings.TrimLeft(rest[1:], " \t")
|
||||
if strings.HasPrefix(rest, "{") {
|
||||
// jsonwebtoken = { version = "9", features = […] }
|
||||
return strings.HasPrefix(strings.TrimLeft(rest[1:], " \t"), "version")
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(rest, `"`) {
|
||||
return false
|
||||
}
|
||||
v, _, ok := strings.Cut(rest[1:], `"`)
|
||||
return ok && depVersion(v)
|
||||
}
|
||||
|
||||
// depVersion says v is what a manifest pins a dependency at: a version
|
||||
// or a range of them (^0.36.4, >=0.30.0 <1, 9, 1.x, *), a workspace's or
|
||||
// a catalog's, a tag (latest, next), or where it comes from (npm:,
|
||||
// file:, link:, git+…, github:).
|
||||
func depVersion(v string) bool {
|
||||
for _, p := range []string{"workspace:", "catalog:", "npm:", "file:", "link:", "portal:", "git+", "git:", "github:", "http://", "https://"} {
|
||||
if strings.HasPrefix(v, p) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
switch v {
|
||||
case "*", "latest", "next", "beta", "canary", "x":
|
||||
return true
|
||||
}
|
||||
for _, part := range strings.Fields(strings.NewReplacer("||", " ", " - ", " ").Replace(v)) {
|
||||
if !depRangeRe.MatchString(part) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return v != ""
|
||||
}
|
||||
|
||||
var depRangeRe = regexp.MustCompile(`^(?:[~^]|[<>]=?|=)?[vV]?\d+(?:\.(?:\d+|[xX*]))*(?:[-+][0-9A-Za-z.-]+)?$`)
|
||||
|
||||
// underPackages says the name at a is a folder packages are installed in:
|
||||
// node_modules/drizzle-orm/…, site-packages/secretstorage/….
|
||||
func underPackages(s string, a int) bool {
|
||||
return strings.HasSuffix(s[:a], "node_modules/") || strings.HasSuffix(s[:a], "node_modules\\") ||
|
||||
strings.HasSuffix(s[:a], "site-packages/") || strings.HasSuffix(s[:a], "site-packages\\")
|
||||
}
|
||||
|
||||
// missingModuleAt says s[a:b] is quoted after the words an error names a
|
||||
// module it could not load with: tsc's and Node's Cannot find module
|
||||
// 'x', Python's No module named 'x', a bundler's Can't resolve 'x'.
|
||||
func missingModuleAt(s string, a, b int) bool {
|
||||
if a == 0 || b >= len(s) || !strings.ContainsRune("'\"`", rune(s[a-1])) || s[b] != s[a-1] {
|
||||
return false
|
||||
}
|
||||
q := strings.ToLower(strings.TrimRight(s[:a-1], " \t"))
|
||||
for _, w := range []string{"find module", "find package", "module named", "resolve", "resolve import", "resolve module"} {
|
||||
if wordEnd(q, w) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// installRe is a package manager's command that names packages after it.
|
||||
var installRe = regexp.MustCompile(`(?:^|[\s;&|(` + "`" + `$])(?:npm|pnpm|yarn|bun|npx|pip|pip3|uv|poetry|pipx|cargo|gem|composer|deno|go)(?: +(?:pip|-[\w-]+))* +(?:add|install|i|remove|rm|uninstall|un|get|require|update|upgrade|up)(?: |$)`)
|
||||
|
||||
// installedAt says s[a:b] is one of the packages a command on its line
|
||||
// installs or removes: pnpm add drizzle-orm postgres, npm i -D x,
|
||||
// pip install a-lib. A value after a flag for a credential (--token,
|
||||
// --auth) is that flag's, and judged as before.
|
||||
func installedAt(s string, a, b int) bool {
|
||||
if b < len(s) && !isSpace(s[b]) && s[b] != ';' && s[b] != '&' && s[b] != '|' && s[b] != ')' {
|
||||
return false
|
||||
}
|
||||
line := strings.LastIndexByte(s[:a], '\n') + 1
|
||||
ms := installRe.FindAllStringIndex(s[line:a], -1)
|
||||
if len(ms) == 0 {
|
||||
return false
|
||||
}
|
||||
args := strings.Fields(s[line+ms[len(ms)-1][1] : a])
|
||||
if a > 0 && !isSpace(s[a-1]) {
|
||||
return false
|
||||
}
|
||||
for _, w := range args {
|
||||
if strings.ContainsAny(w, ";&|<>`$") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if n := len(args); n > 0 && strings.HasPrefix(args[n-1], "-") && credFlag(args[n-1]) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// credFlag says a command's flag names a credential (--token, --auth-key).
|
||||
func credFlag(f string) bool {
|
||||
f = strings.ToLower(f)
|
||||
for _, w := range []string{"token", "key", "pass", "secret", "auth", "cred"} {
|
||||
if strings.Contains(f, w) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// pinnedAt says s[a:b] is a package's name pinned at a version with @, as
|
||||
// npm and pnpm write one (drizzle-orm@0.36.4, js-tokens@4.0.0:): a name
|
||||
// in lower case, as npm's are, and a version of three numbers that is no
|
||||
// IPv4 address, so s3cretPass@10.0.0.5 is a password still.
|
||||
func pinnedAt(s string, a, b int) bool {
|
||||
if b >= len(s) || s[b] != '@' || strings.ToLower(s[a:b]) != s[a:b] {
|
||||
return false
|
||||
}
|
||||
m := pinVersionRe.FindString(s[b+1:])
|
||||
return m != "" && !(len(s) > b+1+len(m) && s[b+1+len(m)] == '.')
|
||||
}
|
||||
|
||||
var pinVersionRe = regexp.MustCompile(`^[\^~]?v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]*[0-9A-Za-z])?`)
|
||||
|
||||
// wordEnd says s ends in the word w.
|
||||
func wordEnd(s, w string) bool {
|
||||
return strings.HasSuffix(s, w) && (len(s) == len(w) || !wordByte(s[len(s)-len(w)-1]))
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package redact
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// dniray on Discord, v0.1.1965, after v0.1.1932's fix: "问题还在", with
|
||||
// import { and, eq } from ' drizzle-orm ' going out as
|
||||
// from ' {{SECRET_o2tu7vej}} '. The module an import loads went as
|
||||
// written only where the model found it on that line: once the model had
|
||||
// taken the name for a secret anywhere else in a request (package.json's
|
||||
// dependencies, a tsc error, a sentence), the name was known, and a known
|
||||
// value is masked wherever it is, on the import line too.
|
||||
func TestKnownPackageNameGoesAsWrittenWhereCodeLoadsIt(t *testing.T) {
|
||||
const line = "import { and, eq } from ' drizzle-orm '"
|
||||
f := &fakeModel{values: map[string]string{"drizzle-orm": "secret"}}
|
||||
o := Options{Secrets: true, Personal: true, Model: f.find}
|
||||
// a sentence the name can't be told apart in, then the import, in one
|
||||
// request: Claude Code's tool results as it sends them
|
||||
body, _ := json.Marshal(map[string]any{"model": "m", "messages": []any{
|
||||
map[string]any{"role": "user", "content": "we keep the drizzle-orm here"},
|
||||
map[string]any{"role": "assistant", "content": []any{map[string]any{"type": "tool_use", "id": "toolu_01", "name": "Read", "input": map[string]any{"file_path": "/w/src/db.ts"}}}},
|
||||
map[string]any{"role": "user", "content": []any{map[string]any{"type": "tool_result", "tool_use_id": "toolu_01", "content": line + "\n"}}},
|
||||
}})
|
||||
out, _ := MaskJSON(body, o)
|
||||
if !strings.Contains(string(out), line) {
|
||||
t.Errorf("the import was masked: %s", out)
|
||||
}
|
||||
// and in the next request, with the model finding nothing in it
|
||||
if out, n := Mask(line, Options{Secrets: true, Personal: true}); n != 0 {
|
||||
t.Errorf("as known: %q", out)
|
||||
}
|
||||
f2 := &fakeModel{values: map[string]string{"drizzle-orm": "secret"}}
|
||||
o2 := Options{Secrets: true, Personal: true, Model: f2.find}
|
||||
body2, _ := json.Marshal(map[string]any{"messages": []any{map[string]any{"role": "user", "content": line}}})
|
||||
if out, _ := MaskJSON(body2, o2); !strings.Contains(string(out), line) {
|
||||
t.Errorf("as known, in a body: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// Where else a package's name is written in what an agent reads: a
|
||||
// dependency in package.json, Cargo.toml or a lock file, a path under
|
||||
// node_modules, a compiler's "Cannot find module", an install, a pin at a
|
||||
// version, and an import with an editor's line numbers or a diff's mark
|
||||
// before it. The model took it for a secret in each, and it went as a
|
||||
// placeholder the agent can't resolve.
|
||||
func TestModelPackageNamesInManifestsAndOutput(t *testing.T) {
|
||||
for _, c := range []struct{ text, value string }{
|
||||
{"{\n \"dependencies\": {\n \"drizzle-orm\": \"^0.36.4\",\n \"jsonwebtoken\": \"~9.0.2\"\n }\n}", "drizzle-orm"},
|
||||
{"{\"devDependencies\": {\"drizzle-kit\": \"0.28.1\"}}", "drizzle-kit"},
|
||||
{"\"jsonwebtoken\": \"workspace:*\",", "jsonwebtoken"},
|
||||
{"\"drizzle-orm\": \">=0.30.0 <1\",", "drizzle-orm"},
|
||||
{"[dependencies]\njsonwebtoken = \"9\"\n", "jsonwebtoken"},
|
||||
{" 1→import drizzle from 'drizzle-orm';", "drizzle-orm"},
|
||||
{" 2\timport sql from 'postgres';\n", "postgres"},
|
||||
{" 3→import { pgTable } from 'drizzle-orm/pg-core';", "drizzle-orm"},
|
||||
{"import { z } from '@acme/drizzle-orm';", "drizzle-orm"},
|
||||
{"12: import { sql } from \"drizzle-orm\";", "drizzle-orm"},
|
||||
{"+import { and, eq } from ' drizzle-orm '", "drizzle-orm"},
|
||||
{"-const jwt = require('jsonwebtoken')", "jsonwebtoken"},
|
||||
{"node_modules/drizzle-orm/pg-core/columns/text.d.ts:12:5 - error TS2322", "drizzle-orm"},
|
||||
{"src/db.ts:1:27 - error TS2307: Cannot find module 'drizzle-orm' or its corresponding type declarations.", "drizzle-orm"},
|
||||
{"Error: Cannot find module 'jsonwebtoken'\nRequire stack:", "jsonwebtoken"},
|
||||
{"ModuleNotFoundError: No module named 'secretstorage'", "secretstorage"},
|
||||
{"pnpm add drizzle-orm postgres && pnpm add -D drizzle-kit", "drizzle-orm"},
|
||||
{"npm install --save jsonwebtoken", "jsonwebtoken"},
|
||||
{"pip install django-rest-passwordreset", "django-rest-passwordreset"},
|
||||
{"cargo add jsonwebtoken", "jsonwebtoken"},
|
||||
{"added drizzle-orm@0.36.4 to dependencies", "drizzle-orm"},
|
||||
{" drizzle-orm@0.36.4:\n resolution: {}", "drizzle-orm"},
|
||||
} {
|
||||
f := &fakeModel{values: map[string]string{c.value: "secret"}}
|
||||
if out, n := Mask(c.text, Options{Secrets: true, Personal: true, Model: f.find}); n != 0 {
|
||||
t.Errorf("%q: masked %q", c.value, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A secret beside those shapes is masked still: one the model finds under
|
||||
// a field that isn't a dependency, after an install's words in prose, and
|
||||
// a known one in an ordinary line.
|
||||
func TestPackageShapesKeepSecrets(t *testing.T) {
|
||||
for _, c := range []struct{ text, value string }{
|
||||
{"{\"password\": \"Zq8vR2mT6wLp\"}", "Zq8vR2mT6wLp"},
|
||||
{"{\"Zq8vR2mT6wLp\": \"hunter2\"}", "Zq8vR2mT6wLp"},
|
||||
{"the login is Zq8vR2mT6wLp@10.0.0.5", "Zq8vR2mT6wLp"},
|
||||
{" 1→const token = 'Zq8vR2mT6wLp';", "Zq8vR2mT6wLp"},
|
||||
{"use the code Zq8vR2mT6wLp to install it", "Zq8vR2mT6wLp"},
|
||||
} {
|
||||
f := &fakeModel{values: map[string]string{c.value: "secret"}}
|
||||
if out, _ := Mask(c.text, Options{Secrets: true, Personal: true, Model: f.find}); strings.Contains(out, c.value) {
|
||||
t.Errorf("%q left in %q", c.value, out)
|
||||
}
|
||||
}
|
||||
// a known secret in a line that isn't code loading it
|
||||
if out, _ := Mask("DB_PASSWORD=Zq8hunterPass42", Options{Secrets: true}); strings.Contains(out, "Zq8hunterPass42") {
|
||||
t.Fatalf("not masked to begin with: %q", out)
|
||||
}
|
||||
for _, s := range []string{"the password from Zq8hunterPass42 there", " 1→const p = 'Zq8hunterPass42';"} {
|
||||
if out, _ := Mask(s, Options{Secrets: true}); strings.Contains(out, "Zq8hunterPass42") {
|
||||
t.Errorf("known secret left in %q", out)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user