redact: a file's lines, a path, a skill and a name in code after token: are no secret

Three reports on X (10-28), each a value the SECRET rule took (Insights >
Masking: 机密, 规则). The rule takes a name with token, secret, password
or api_key in it, then : or =, then 8 characters or more with a letter and
a digit. Prompts and code have that shape where nothing is secret:

- AlpsNowX: L643-669. was masked, in two requests. A file whose name has
  one of those words, then :L643-669. (internal/auth/token.go:L643-669.)
  read as a field token.go and its value, and once masked the lines went
  as {{SECRET_…}} wherever they came again (by known). Now a name that is
  a source file's (.go, .ts, .py, .md, .json …, not .txt/.env/.key) or a
  path's last part is no field, and a line or range (L643, L643-669,
  L12-L40, 643:12) is no value. Siblings: token.go:643-669 and #L643-L669
  were never masked (no letter / no colon); file.go:L12-40 was, and isn't.
- binary4cat: function names masked. access_token = get_access_token_v2,
  max_tokens=max_tokens_v3, secret: env.SECRET_V2, refreshToken2;,
  fn(token=token_v2), secretKey:=base64Encode(raw) all masked the name.
  A value written as code writes a name (lower-case start, or _ or .
  between words) of two words or more, one of them token/secret/password/
  key/credential, is a name now; a value starting with = is Go's :=.
- AkinoNya: folders and skills with a random string replaced. Found two
  routes: a path after such a name (PRIVATE_KEY_PATH=~/.ssh/id_ed25519,
  token_dir=/private/tmp/claude-501/x7k2p9q1-skill,
  GOOGLE_APPLICATION_CREDENTIALS=/Users/…/legacy_credentials/x7k2p9q1/…,
  私钥 ~/.ssh/…), and Claude Code's plugin:skill when the plugin's name
  has one of the words (design-tokens:generate-v2, secret-scan:
  audit-x7k2p9q1). A path from ~/, ./, ../ or a root folder (/Users,
  /tmp, /private …) with no + or = goes as written, in the CJK key rules
  too; slug:slug with no space is a skill. The ~1100 real folder and skill
  names on this machine (~/.claude, ~/.codex, $TMPDIR, Claude's
  claude-501 dirs) in five contexts masked nothing before or after, so
  the reporter's exact names are not reproduced.

Still masked (TestSecretsBesideLinesAndNames): password=hunter2pass9,
API_KEY=AbC123dEf456GhI789, token=t0k3nValue2, Passw0rd123, password123,
SuperSecret2024 (PascalCase stays a password), token: Lk8x9QmP2vR4,
secret.txt:hunter2pass9, x-api-key:k9x2mp4qr7st1vw3 and :ab12cd34ef56,
Password=Abc12345; in a connection string, 密钥为12231241, 私钥 ab12…,
django-insecure-…; vendorchecks and the existing code tests unchanged.

Run (mote): go vet ./internal/redact for darwin, linux, windows; go test
-count=1 ./internal/redact ./internal/masking ./internal/pii/...
./internal/otlp ./internal/sessions ./internal/settings ./internal/gateway
at base ea53eb126: all ok (gateway 551s). After the rebase onto
bc3ddc661 (zhname): vet (3 OSes) and redact, masking ok. gofmt -l clean.
Broken by hand: the two SECRET rules back on notCode and keyAt without
the path check: 28 of the new tests' cases red (every reported shape),
the still-masked test green.

Not tried: the full ./... suite (mote at load ~50 with two other full
suites); the reporters' own prompts; the local-model path, unchanged.
Tradeoff: a password written as code writes a name (myPassword1,
MY_SECRET_2) now goes as written.
This commit is contained in:
yetone
2026-10-28 15:16:59 +08:00
parent f79817f572
commit f02d92c7be
3 changed files with 317 additions and 2 deletions
+208
View File
@@ -0,0 +1,208 @@
package redact
import (
"regexp"
"strings"
"unicode"
)
// What follows a secret's name and a colon or = is not always the secret.
// The SECRET rules take a name with password, secret, token or api_key in
// it, then : or =, then the value; a prompt and a session's code have that
// shape where nothing is secret:
//
// - a place in a file: internal/auth/token.go:L643-669. names lines
// 643 to 669 of token.go (AlpsNowX on X, 10-28). It went to the model
// as {{SECRET_…}}, and as a value masked once, everywhere it came
// again (L643-669. alone in the next prompt): the agent could no longer
// read the lines it was pointed at. The name is a file's, not a field's.
// - a file's or a folder's path: PRIVATE_KEY_PATH=~/.ssh/id_ed25519,
// "credentials": "/Users/…/legacy_credentials/x7k2/adc.json" name where
// a secret is kept, and the agent needs the path as written to read it
// (AkinoNya on X, 10-28: folders and skills with a random string in
// their name were replaced).
// - code naming a secret: access_token = get_access_token_v2,
// max_tokens=max_tokens_v3, secret: env.SECRET_V2 (binary4cat on X,
// 10-28: function names were masked). A key's characters are random;
// a name made of words, one of them token, secret or password, is a
// function's or a variable's.
//
// A secret written down still masks: password=hunter2pass9,
// API_KEY=AbC123dEf456GhI789, token: t0k3nValue2, a password of one word
// and digits (Passw0rd123, password123).
// fieldAt is where a value the SECRET rules found can be a secret: not
// code (notCode), and not a place in a file, a path or a name in code.
func fieldAt(s string, a, b int) bool {
if !notCode(s, a, b) {
return false
}
v := s[a:b]
if v[0] == '=' {
return false // Go's := with no space after it: secretKey:=base64Encode(raw)
}
return !fileField(s, a) && !lineRef(v) && !pathValue(v) && !namesASecret(v) && !skillName(s, a, b)
}
// skillName says s[a:b] is the second half of plugin:skill, as Claude
// Code names a plugin's skill and command (design-tokens:generate-v2,
// secret-scan:audit-x7k2p9q1): words in lower case joined by hyphens on
// both sides of a colon with no space around it. A key has a capital or
// a long random run (notASlug).
func skillName(s string, a, b int) bool {
if a < 2 || s[a-1] != ':' || !skillSlugRe.MatchString(s[a:b]) || notASlug(s[a:b]) {
return false
}
i := a - 1
for i > 0 && strings.IndexByte("abcdefghijklmnopqrstuvwxyz0123456789-", s[i-1]) >= 0 {
i--
}
return i < a-1 && (i == 0 || strings.IndexByte(alnum+"_.", s[i-1]) < 0) && skillSlugRe.MatchString(s[i:a-1])
}
// skillSlugRe is words in lower case joined by hyphens: a plugin's, a skill's
// or a command's name.
var skillSlugRe = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)+$`)
// lineRefRe is a line or a range of lines, as an editor or a review names
// them: L643, L643-669, L12-L40, 643-669, 643:12, with a sentence's
// stop after it.
var lineRefRe = regexp.MustCompile(`^L?\d+(?:[-–:]L?\d+)*[.,;:]?$`)
// lineRef says v is a line or a range of lines, never a secret.
func lineRef(v string) bool { return lineRefRe.MatchString(v) }
// fileField says the name before the value at s[a] is a file's, or a
// path's last part, not a field's: token.go:L643-669, src/secret_store.ts:…,
// skills/secret-scanner:…. It reads back over the separator (: or =, and
// the quotes and spaces around it) to the name.
func fileField(s string, a int) bool {
i := a
for i > 0 && strings.IndexByte(" \t\"'\\", s[i-1]) >= 0 {
i--
}
if i == 0 || s[i-1] != ':' && s[i-1] != '=' {
return false
}
i--
for i > 0 && strings.IndexByte(" \t\"'\\", s[i-1]) >= 0 {
i--
}
end := i
for i > 0 && strings.IndexByte(alnum+"_.-", s[i-1]) >= 0 {
i--
}
name := s[i:end]
if name == "" {
return false
}
if i > 0 && (s[i-1] == '/' || s[i-1] == '\\') {
return true // a path's last part
}
dot := strings.LastIndexByte(name, '.')
return dot > 0 && sourceExt[strings.ToLower(name[dot+1:])]
}
// sourceExt are the extensions of files an agent reads and names with a
// line after them: code, docs and configs. Not .env, .txt, .key or .pem,
// whose content is what a secret is kept in.
var sourceExt = map[string]bool{
"go": true, "ts": true, "tsx": true, "mts": true, "cts": true, "js": true, "jsx": true, "mjs": true, "cjs": true,
"py": true, "pyi": true, "rb": true, "rs": true, "java": true, "kt": true, "kts": true, "swift": true,
"c": true, "h": true, "cc": true, "cpp": true, "cxx": true, "hpp": true, "hh": true, "m": true, "mm": true,
"cs": true, "fs": true, "php": true, "scala": true, "dart": true, "lua": true, "zig": true, "nim": true,
"ex": true, "exs": true, "erl": true, "hs": true, "ml": true, "clj": true, "r": true, "jl": true,
"sh": true, "bash": true, "zsh": true, "fish": true, "ps1": true, "vue": true, "svelte": true, "astro": true,
"md": true, "mdx": true, "rst": true, "sql": true, "proto": true, "graphql": true, "gradle": true,
"html": true, "css": true, "scss": true, "less": true, "json": true, "jsonc": true, "yaml": true, "yml": true,
"toml": true, "xml": true, "tf": true, "ipynb": true,
}
// pathRoots are the folders an absolute path starts at.
var pathRoots = []string{
"Users", "home", "tmp", "private", "var", "etc", "run", "opt", "usr", "mnt", "Volumes", "root", "srv",
"data", "workspace", "workspaces", "app", "Applications", "Library", "System", "proc", "dev", "sys", "nix",
}
// pathValue says v is a file's or a folder's path: one from home (~/),
// from here (./, ../), or from a root folder (/Users/…, /tmp/…), with no
// + or = in it as base64 has.
func pathValue(v string) bool {
if strings.ContainsAny(v, "+=") {
return false
}
for _, p := range []string{"~/", "./", "../"} {
if strings.HasPrefix(v, p) && len(v) > len(p) {
return true
}
}
if !strings.HasPrefix(v, "/") {
return false
}
first, rest, ok := strings.Cut(v[1:], "/")
if !ok || rest == "" {
return false
}
for _, r := range pathRoots {
if first == r {
return true
}
}
return false
}
// secretWords are the words of a name in code that say it holds a secret.
var secretWords = map[string]bool{
"token": true, "tokens": true, "secret": true, "secrets": true, "password": true, "passwords": true,
"passwd": true, "pwd": true, "key": true, "keys": true, "apikey": true, "credential": true, "credentials": true,
}
// identRe is a name in code, read through others or not: camelCase,
// snake_case, SCREAMING_CASE, env.SECRET_V2.
var identRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$`)
// namesASecret says v is a name in code for a secret, not one: two words
// or more, one of them token, secret, password or key, written as code
// writes a name: starting in lower case, or with _ or . between its
// words. refreshToken2, generate_token_v2, env.SECRET_V2 and
// countTokens4o are names; Passw0rd123 and password123 are one word, and
// SuperSecret2024 is a password, not how code names a value.
func namesASecret(v string) bool {
if !identRe.MatchString(v) {
return false
}
if !unicode.IsLower(rune(v[0])) && !strings.ContainsAny(v, "_.") {
return false
}
words, named := 0, false
for _, w := range identWords(v) {
if strings.IndexFunc(w, unicode.IsLetter) < 0 {
continue
}
words++
if i := strings.IndexAny(w, digits); i >= 0 {
w = w[:i] // countTokens4o: Tokens
}
if secretWords[strings.ToLower(w)] {
named = true
}
}
return words >= 2 && named
}
// identWords are v's words: split at _ and ., and where a capital starts
// a word in camelCase (refreshToken2 is refresh and Token2).
func identWords(v string) []string {
var out []string
for _, part := range strings.FieldsFunc(v, func(r rune) bool { return r == '_' || r == '.' }) {
start := 0
for i := 1; i < len(part); i++ {
if part[i] >= 'A' && part[i] <= 'Z' && part[i-1] >= 'a' && part[i-1] <= 'z' {
out = append(out, part[start:i])
start = i
}
}
out = append(out, part[start:])
}
return out
}
+104
View File
@@ -0,0 +1,104 @@
package redact
import (
"strings"
"testing"
)
// A place in a file goes as written: AlpsNowX on X (10-28) saw L643-669.
// listed under Secrets, found by a rule, in two requests. A file whose
// name has token, secret or password in it, a colon and the lines were
// a field, its name and its value; and once masked, the lines were masked
// wherever they came again.
func TestLineRangeIsNoSecret(t *testing.T) {
o := Options{Secrets: true, Personal: true}
for _, in := range []string{
"看一下 internal/auth/token.go:L643-669.",
"L643-669.",
"参考 src/secret_store.ts:L643-669. 和 L12-40",
"见 tokenizer.rs:L643-669。",
"cmd/apikey/main.go:L643-669, cmd/apikey/main.go:L12-40.",
"see internal/redact/password_test.go:643-669 and #L643-L669",
"src/credentials.py:L12-L40",
"token_test.go:p2fa9c1d",
"token.go:-1-2-3a",
"internal/auth/token.go:L12-40",
} {
if out, n := Mask(in, o); n != 0 {
t.Errorf("%q: %d masked: %q", in, n, out)
}
}
}
// Code naming a secret goes as written: binary4cat on X (10-28), function
// names were masked. A name made of words, one of them token, secret or
// password, after = or : is a function's or a variable's.
func TestNameInCodeIsNoSecret(t *testing.T) {
for _, in := range []string{
"const accessToken2 = refreshToken2;",
"let secretV2 = loadSecretV2;",
"secretKey:=base64Encode(raw)",
"password = hashPassword256;",
"self.token = generate_token_v2",
`TOKEN_V2 = "TOKEN_V2"`,
"tokenCount = countTokens4o",
" secret: env.SECRET_V2",
"max_tokens=max_tokens_v3",
"access_token = get_access_token_v2",
"passwordInput.value = newPassword2",
"fn(token=token_v2)",
`const TOKEN_KEY = "access_token_v2"`,
} {
if out, n := Mask(in, Options{Secrets: true}); n != 0 {
t.Errorf("%q: %d masked: %q", in, n, out)
}
}
}
// A path to where a secret is kept goes as written, and so does a
// plugin's skill: AkinoNya on X (10-28), folders and skills with a random
// string in their name were replaced.
func TestPathAndSkillAreNoSecret(t *testing.T) {
for _, in := range []string{
"PRIVATE_KEY_PATH=~/.ssh/id_ed25519",
"GOOGLE_APPLICATION_CREDENTIALS=/Users/alice/.config/gcloud/legacy_credentials/x7k2p9q1/adc.json",
`"credentials_file": "/Users/alice/.aws/sso/cache/3f9a2c7b1e.json"`,
"私钥 ~/.ssh/id_ed25519_2024",
"token_dir=/private/tmp/claude-501/x7k2p9q1-skill",
"--token-file=/tmp/tok-a8f3k2x9/token",
"skills/secret-scanner:x7k2p9q1",
"- design-tokens:generate-v2: Generate tokens",
"/secret-scan:audit-x7k2p9q1",
} {
if out, n := Mask(in, Options{Secrets: true}); n != 0 {
t.Errorf("%q: %d masked: %q", in, n, out)
}
}
}
// A secret of the same shape still masks: a value of one word and digits,
// a random one, one starting with L, a file of secrets' content, a key in
// a header with no space, a password in a connection string.
func TestSecretsBesideLinesAndNames(t *testing.T) {
for in, v := range map[string]string{
"password=hunter2pass9": "hunter2pass9",
"API_KEY=AbC123dEf456GhI789": "AbC123dEf456GhI789",
"token=t0k3nValue2": "t0k3nValue2",
"password: Passw0rd123": "Passw0rd123",
"DB_PASSWORD=password123": "password123",
"PASSWORD=SuperSecret2024": "SuperSecret2024",
"token: Lk8x9QmP2vR4": "Lk8x9QmP2vR4",
"secret.txt:hunter2pass9": "hunter2pass9",
"x-api-key:k9x2mp4qr7st1vw3": "k9x2mp4qr7st1vw3",
"x-api-key:ab12cd34ef56": "ab12cd34ef56",
"Server=db;Password=Abc12345;User Id=sa": "Abc12345",
"api_token = 'tok-8f3a9c2e7b1d'": "tok-8f3a9c2e7b1d",
"密钥为12231241": "12231241",
"私钥 ab12cd34ef56": "ab12cd34ef56",
"SECRET_KEY=django-insecure-a1b2c3d4e5f6": "django-insecure-a1b2c3d4e5f6",
} {
if out, n := Mask(in, Options{Secrets: true}); n != 1 || strings.Contains(unmarked(out), v) {
t.Errorf("%q: %d masked: %q", in, n, out)
}
}
}
+5 -2
View File
@@ -157,12 +157,12 @@ var rules = append([]rule{
{kind: "PASSWORD", re: regexp.MustCompile(`[A-Za-z][A-Za-z0-9+.-]*://[^\s:@/?#"'<>]*:([^\s@/?#"'<>]{3,})@`), markers: []string{"://"}, ok: notAVariable},
// password = …, API_KEY: "…", as .env files and configs have them
{kind: "SECRET", re: regexp.MustCompile(`(?i)[A-Za-z0-9_.-]*(?:` + secretNames.pattern() + `)[A-Za-z0-9_.-]*` + quote + `[ \t]*[:=][ \t]*` + quote + `(` + secretCh + `{8,})`),
markers: secretNames.markers(), ok: secretValue, at: notCode},
markers: secretNames.markers(), ok: secretValue, at: fieldAt},
// a field called key and nothing more, as providers.json has one: "key":
// "oc_sk_…" (#195). Only a long value of letters and digits both, since
// code calls anything a key: a map's "key": "value", sort_key, keyboard.
{kind: "SECRET", re: regexp.MustCompile(`(?i)(?:^|[^A-Za-z0-9_.-])` + quote + `key` + quote + `[ \t]*[:=][ \t]*` + quote + `(` + secretCh + `{16,})`),
markers: fieldNames{{"key", "key"}}.markers(), ok: secretValue, at: notCode},
markers: fieldNames{{"key", "key"}}.markers(), ok: secretValue, at: fieldAt},
// a password after its name in Chinese, Japanese or Korean, as people
// write one into a message: 密码:786kih, 密碼是 hunter2, パスワード: … .
// Unlike password = in a config, nothing in code is called 密码, so
@@ -292,6 +292,9 @@ func keyValue(v string) bool {
// time.
func keyAt(s string, a, b int) bool {
v := s[a:b]
if pathValue(v) {
return false // where a key is kept: 私钥 ~/.ssh/id_ed25519 (fieldvalue.go)
}
if keyValue(v) {
return true
}