Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(inventory): redact auth-scheme credentials and secrets inside definition strings (#1076)

Rudy Mizrahi Celekli647a5395416f
diff --git a/cli/beacon/internal/endpoint/inventory/content.go b/cli/beacon/internal/endpoint/inventory/content.go
index 4d29dcb1..203e5deb 100644
--- a/cli/beacon/internal/endpoint/inventory/content.go
+++ b/cli/beacon/internal/endpoint/inventory/content.go
@@ -12,24 +12,29 @@ import (
// truncated to a UTF-8 rune boundary and flagged as truncated.
const DefaultMaxContentBytes = 64 * 1024
-const redactedPlaceholder = "***REDACTED***"
-
-// secretMarkers are the substring markers that identify sensitive config keys.
-// They are shared by the env-key filter and the content/definition redactors so
-// captured contents and summarized metadata stay consistent.
-var secretMarkers = []string{"TOKEN", "SECRET", "PASSWORD", "KEY", "AUTH", "CREDENTIAL"}
-
-// secretAssignmentRE matches a `key: value` or `key = value` assignment where
-// the key contains a secret marker, across JSON, TOML, YAML, and shell-style
-// content. The value is captured separately so it can be replaced while
-// preserving the surrounding key, separator, and quote style.
+// redactedPlaceholder is what asymptoteobserve.RedactString puts in place of a secret, so a value
+// redacted for its key and one redacted for its shape read the same.
+const redactedPlaceholder = "[REDACTED]"
+
+// secretKeyCandidate is a key that may be named for a secret: every word
+// asymptoteobserve.IsSecretKeyName takes for a credential's holds one of these, and that predicate
+// decides.
+const secretKeyCandidate = `"?[A-Za-z0-9_.\-]*(?:token|secret|pass|key|auth|credential|cookie)[A-Za-z0-9_.\-]*"?`
+
+// secretAssignmentRE matches a `key: value` or `key = value` assignment to a
+// secretKeyCandidate, across JSON, TOML, YAML, and shell-style content. Config
+// files name secrets more loosely than the labels asymptoteobserve.RedactString
+// knows (`OPENAI_KEY`, `X_AUTH`, `SECRET_KEY_BASE`), so these values are
+// redacted for their key alone. The value is captured separately so it can be
+// replaced while preserving the surrounding key, separator, and quote style; an
+// unquoted one runs through a placeholder RedactString left in it.
var secretAssignmentRE = regexp.MustCompile(
- `(?i)("?[A-Za-z0-9_.\-]*(?:` + strings.ToLower(strings.Join(secretMarkers, "|")) + `)[A-Za-z0-9_.\-]*"?)(\s*[:=]\s*)` +
- "(\"(?:[^\"\\\\]|\\\\.)*\"|'[^']*'|`[^`]*`|[^\\s,}\\]\\n#]+)",
+ `(?i)(` + secretKeyCandidate + `)(\s*[:=]\s*)` +
+ "(\"(?:[^\"\\\\]|\\\\.)*\"|'[^']*'|`[^`]*`|(?:" + regexp.QuoteMeta(redactedPlaceholder) + "|[^\\s,}\\]\\n#])+)",
)
var yamlSecretBlockScalarHeaderRE = regexp.MustCompile(
- `(?i)^([ \t]*(?:-\s*)?"?[A-Za-z0-9_.\-]*(?:` + strings.ToLower(strings.Join(secretMarkers, "|")) + `)[A-Za-z0-9_.\-]*"?\s*:\s*)` +
+ `(?i)^([ \t]*(?:-\s*)?` + secretKeyCandidate + `\s*:\s*)` +
`([|>](?:[+-]?[0-9]|[0-9][+-]?)?[ \t]*(?:#.*)?)(\r?\n?)$`,
)
@@ -74,34 +79,33 @@ func captureContent(data []byte, maxBytes int) *CapturedContent {
}
}
-// redactSecrets replaces the values of secret-looking assignments with a
-// placeholder and returns the redacted text plus the number of redactions.
+// redactSecrets redacts captured text and returns it with the number of values replaced. Block
+// scalars under a secret-looking key go first, whole, since RedactString would take the `|` for
+// the value and keep the lines under it. RedactString then replaces what it recognizes anywhere
+// (credential formats, Authorization headers, secret flags, URL passwords, labeled assignments),
+// and what is left under a secret-looking key goes last.
func redactSecrets(text string) (string, int) {
- out, count := redactYAMLBlockScalarSecrets(text)
+ out := asymptoteobserve.RedactString(redactYAMLBlockScalarSecrets(text))
out = secretAssignmentRE.ReplaceAllStringFunc(out, func(match string) string {
sub := secretAssignmentRE.FindStringSubmatch(match)
- if len(sub) != 4 {
- return match
- }
- if isRedactedValueLiteral(sub[3]) {
+ // A value RedactString already handled (`"Bearer [REDACTED]"`) stays as it is.
+ if len(sub) != 4 || strings.Contains(sub[3], redactedPlaceholder) || !asymptoteobserve.IsSecretField(sub[1], strings.Trim(sub[3], "\"'`")) {
return match
}
- count++
return sub[1] + sub[2] + redactValueLiteral(sub[3])
})
- return out, count
+ return out, max(0, strings.Count(out, redactedPlaceholder)-strings.Count(text, redactedPlaceholder))
}
-func redactYAMLBlockScalarSecrets(text string) (string, int) {
+func redactYAMLBlockScalarSecrets(text string) string {
lines := splitLinesKeepEnd(text)
if len(lines) == 0 {
- return text, 0
+ return text
}
var out strings.Builder
- count := 0
for i := 0; i < len(lines); i++ {
sub := yamlSecretBlockScalarHeaderRE.FindStringSubmatch(lines[i])
- if len(sub) != 4 {
+ if len(sub) != 4 || !asymptoteobserve.IsSecretKeyName(sub[1]) {
out.WriteString(lines[i])
continue
}
@@ -138,10 +142,9 @@ func redactYAMLBlockScalarSecrets(text string) (string, int) {
out.WriteString(sub[1])
out.WriteString(redactedPlaceholder)
out.WriteString(sub[3])
- count++
i = bodyEnd - 1
}
- return out.String(), count
+ return out.String()
}
// redactValueLiteral replaces a captured value with the placeholder while
@@ -159,26 +162,16 @@ func redactValueLiteral(value string) string {
}
}
-func isRedactedValueLiteral(value string) bool {
- switch value {
- case redactedPlaceholder,
- `"` + redactedPlaceholder + `"`,
- "'" + redactedPlaceholder + "'",
- "`" + redactedPlaceholder + "`":
- return true
- default:
- return false
- }
-}
-
-// redactStructured walks a parsed config value and replaces string values held
-// under secret-looking keys with the placeholder, leaving structure intact.
+// redactStructured walks a parsed config value and replaces values held under
+// secret-looking keys with the placeholder, leaving structure intact. Strings
+// get the same redaction as captured file text, and an argument after a flag
+// named for a secret is one: `"args": ["--api-key", "x"]`.
func redactStructured(value interface{}) interface{} {
switch typed := value.(type) {
case map[string]interface{}:
out := make(map[string]interface{}, len(typed))
for key, val := range typed {
- if containsSecretMarker(key) {
+ if asymptoteobserve.IsSecretField(key, val) {
out[key] = redactedPlaceholder
continue
}
@@ -188,14 +181,26 @@ func redactStructured(value interface{}) interface{} {
case []interface{}:
out := make([]interface{}, len(typed))
for i, item := range typed {
+ if arg, ok := item.(string); ok && arg != "" && i > 0 && followsSecretFlag(typed[i-1]) {
+ out[i] = redactedPlaceholder
+ continue
+ }
out[i] = redactStructured(item)
}
return out
+ case string:
+ redacted, _ := redactSecrets(typed)
+ return redacted
default:
return value
}
}
+func followsSecretFlag(previous interface{}) bool {
+ flag, ok := previous.(string)
+ return ok && asymptoteobserve.IsSecretFlag(flag)
+}
+
// redactStructuredMap redacts a definition block and returns it as a map.
func redactStructuredMap(def map[string]interface{}) map[string]interface{} {
if m, ok := redactStructured(def).(map[string]interface{}); ok {
@@ -204,16 +209,6 @@ func redactStructuredMap(def map[string]interface{}) map[string]interface{} {
return nil
}
-func containsSecretMarker(key string) bool {
- upper := strings.ToUpper(key)
- for _, marker := range secretMarkers {
- if strings.Contains(upper, marker) {
- return true
- }
- }
- return false
-}
-
func splitLinesKeepEnd(s string) []string {
if s == "" {
return nil
diff --git a/cli/beacon/internal/endpoint/inventory/inventory.go b/cli/beacon/internal/endpoint/inventory/inventory.go
index 1cbd4211..9320fb6a 100644
--- a/cli/beacon/internal/endpoint/inventory/inventory.go
+++ b/cli/beacon/internal/endpoint/inventory/inventory.go
@@ -21,6 +21,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/hermessession"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)
const (
@@ -1022,7 +1023,7 @@ func valuesForEnvKeys(keys []string, redaction string) []string {
}
func safeEnvKey(key string) bool {
- return !containsSecretMarker(key)
+ return !asymptoteobserve.IsSecretKeyName(key)
}
func mapKeys(raw interface{}) []string {
@@ -1222,7 +1223,7 @@ func localEndpointText(text string) bool {
// command name, a timestamp, or a whole config file's bytes. A secret value must not be hashed
// here -- a digest over one short, low-entropy secret is a lookup table away from the secret
// itself -- so route anything that may hold a secret through redactStructured first, the way
-// serverFromDefinition does. Secret-looking keys are stripped by containsSecretMarker.
+// serverFromDefinition does. Secret-looking keys are stripped by asymptoteobserve.IsSecretKeyName.
func hashString(value string) string {
if value == "" {
diff --git a/cli/beacon/internal/endpoint/inventory/inventory_test.go b/cli/beacon/internal/endpoint/inventory/inventory_test.go
index 3d7e2740..c8fbe6e4 100644
--- a/cli/beacon/internal/endpoint/inventory/inventory_test.go
+++ b/cli/beacon/internal/endpoint/inventory/inventory_test.go
@@ -1042,7 +1042,17 @@ func TestRedactSecretsAcrossFormats(t *testing.T) {
{"toml", "GITHUB_TOKEN = \"tk_x\"\nname = \"ok\"", "tk_x", 1},
{"yaml", "password: hunter2\nuser: bob", "hunter2", 1},
{"shell", "export AWS_SECRET_ACCESS_KEY=abc123\nexport PATH=/bin", "abc123", 1},
+ {"env key named only for a key", `{"env": {"OPENAI_KEY": "plainvalue99"}}`, "plainvalue99", 1},
+ {"secret word inside a key", "SECRET_KEY_BASE: plainvalue99\n", "plainvalue99", 1},
+ {"tokens key that holds no count", "GITHUB_TOKENS: plainvalue99\nmax_tokens: 4096\n", "plainvalue99", 1},
+ {"pass key", "export DB_PASS=plainvalue99\n", "plainvalue99", 1},
+ {"yaml bearer header", "headers:\n Authorization: Bearer ghp_headertoken\n Accept: json", "ghp_headertoken", 1},
+ {"yaml basic header", "Authorization: Basic dXNlcjpodW50ZXIy\n", "dXNlcjpodW50ZXIy", 1},
+ {"curl line in a skill", "curl -H 'Authorization: Bearer sk-live-curltoken' https://api.example.com", "sk-live-curltoken", 1},
+ {"api key flag in args", `{"args": ["-y", "@upstash/context7-mcp", "--api-key", "ctx7sk-abcdef0123456789"]}`, "ctx7sk-abcdef0123456789", 1},
+ {"bare github token", "export it first: ghp_0123456789abcdefghijABCDEFGHIJ0123", "0123456789abcdefghijABCDEFGHIJ0123", 1},
{"none", `{"host": "example.com", "port": 8080}`, "", 0},
+ {"flags and keys that name no secret", "max_tokens: 4096\nauthor: alice\nAUTH_MODE=token npm start\n" + `{"args": ["--max-tokens=4096", "--author=alice"], "env": {"AUTH_MODE": "token"}}`, "", 0},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
@@ -1057,6 +1067,25 @@ func TestRedactSecretsAcrossFormats(t *testing.T) {
}
}
+func TestRedactStructuredCoversSecretsInsideStringValues(t *testing.T) {
+ def := map[string]interface{}{
+ "command": "npx",
+ "args": []interface{}{"-y", "@example/mcp", "--token=ghp_argsecret", "--api-key", "ctx7sk-abcdef0123456789", "--max-tokens=4096"},
+ "url": "https://mcp.example.com/sse?api_key=ghp_urlsecret",
+ "env": map[string]interface{}{"GH_HOST": "github.com", "AUTH_MODE": "token", "OPENAI_KEY": "plainkey", "SECRET_KEY_BASE": "plainbase", "MAX_TOKENS": float64(4096), "GITHUB_TOKENS": "plaintokens"},
+ }
+ raw, err := json.Marshal(redactStructuredMap(def))
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := `{"args":["-y","@example/mcp","--token=[REDACTED]","--api-key","[REDACTED]","--max-tokens=4096"],"command":"npx",` +
+ `"env":{"AUTH_MODE":"token","GH_HOST":"github.com","GITHUB_TOKENS":"[REDACTED]","MAX_TOKENS":4096,"OPENAI_KEY":"[REDACTED]","SECRET_KEY_BASE":"[REDACTED]"},` +
+ `"url":"https://mcp.example.com/sse?api_key=[REDACTED]"}`
+ if string(raw) != want {
+ t.Fatalf("redacted definition = %s\nwant %s", raw, want)
+ }
+}
+
func TestCaptureContentRedactsYAMLBlockScalarSecrets(t *testing.T) {
content := captureContent([]byte("api_token: |\n ghp_first\n ghp_second\nuser: bob"), DefaultMaxContentBytes)
if content == nil {
diff --git a/docs/cli/endpoint-inventory.mdx b/docs/cli/endpoint-inventory.mdx
index 525c46fd..40c243b5 100644
--- a/docs/cli/endpoint-inventory.mdx
+++ b/docs/cli/endpoint-inventory.mdx
@@ -49,7 +49,7 @@ Add `--contents` when you need to see the **full definitions** of config, hook,
Captured contents are always passed through local redaction and a size limit:
-- Values held under secret-looking keys (matching `TOKEN`, `SECRET`, `PASSWORD`, `KEY`, `AUTH`, or `CREDENTIAL`) are replaced with `***REDACTED***`. The `content.redacted_count` field reports how many values were redacted.
+- Secrets are replaced with `[REDACTED]` by the same redaction Beacon applies to session telemetry: recognizable credentials (GitHub, AWS, Slack, OpenAI and Anthropic keys, JWTs), `Authorization` header credentials, values of secret flags such as `--token=…` or `"--api-key", "…"`, and URL passwords. Values held under a key with a word naming a secret (`token`, `key`, `auth`, `secret`, `password`, `credential`, as in `GITHUB_TOKEN`, `OPENAI_KEY` or `SECRET_KEY_BASE`) are replaced whatever they look like. The `content.redacted_count` field reports how many values were redacted.
- Bodies are truncated to a per-file byte cap (64 KiB by default) and flagged with `content.truncated`. The `content.bytes` field always reports the original file size.
```bash title="Show full, redacted MCP definitions"
diff --git a/docs/security/data-inventory.mdx b/docs/security/data-inventory.mdx
index 12c9cf54..50ef9a2d 100644
--- a/docs/security/data-inventory.mdx
+++ b/docs/security/data-inventory.mdx
@@ -56,7 +56,7 @@ page.
By default, inventory is metadata- and hash-only. Beacon hashes config, hook, and `SKILL.md` files for change detection but does not retain file bodies, full MCP server definitions, or skill instruction bodies in inventory JSON, dashboard responses, or inventory snapshot events.
-Operators can opt into capturing full definitions with the `--contents` flag (CLI) or the `include_contents` config setting (snapshot telemetry). When enabled, configs, hooks, and skills gain a redacted `content` block and MCP servers gain a full `definition` block. Captured contents always pass through local secret redaction and a per-file size cap (64 KiB by default, configurable with `max_content_bytes`). Redaction replaces values under keys matching `TOKEN`, `SECRET`, `PASSWORD`, `KEY`, `AUTH`, or `CREDENTIAL` with `***REDACTED***`.
+Operators can opt into capturing full definitions with the `--contents` flag (CLI) or the `include_contents` config setting (snapshot telemetry). When enabled, configs, hooks, and skills gain a redacted `content` block and MCP servers gain a full `definition` block. Captured contents always pass through local secret redaction and a per-file size cap (64 KiB by default, configurable with `max_content_bytes`). Redaction is the one Beacon applies to session telemetry (recognizable credentials, `Authorization` header credentials, secret flag values, URL passwords, and values under a key with a word naming a secret, such as `token`, `key`, `auth`, `secret`, `password` or `credential`), each replaced with `[REDACTED]`.
Inventory heartbeat telemetry uses a separate local JSONL file, `inventory_state.jsonl`, so `runtime.jsonl` stays scoped to agent runtime activity. A scheduled local job (every 6 hours, and once at install, boot, or upgrade) writes:
diff --git a/pkg/asymptoteobserve/privacy.go b/pkg/asymptoteobserve/privacy.go
index 1472e1cf..7184c44e 100644
--- a/pkg/asymptoteobserve/privacy.go
+++ b/pkg/asymptoteobserve/privacy.go
@@ -101,9 +101,11 @@ const redactUnquoted = `(?:[^"'` + "`" + `,\s\\]|\\[^"'` + "`" + `])[^"'` + "`"
// structure around it.
const redactBare = `[^"'` + "`" + `\\\s,{}\[\]][^"'` + "`" + `\\\s,{}\[\]]*`
-// redactFlag is a command-line flag named for a secret and its separator: `--password `,
-// `--token=`, `-api-key `.
-const redactFlag = `(?:^|\s)--?[a-z0-9-]*(?:password|passwd|passphrase|token|secret|api-?key|access-?key)(?:=|\s+)`
+// redactFlagName is a command-line flag named for a secret: `--password`, `--token`, `-api-key`.
+const redactFlagName = `--?[a-z0-9-]*(?:password|passwd|passphrase|token|secret|api-?key|access-?key)`
+
+// redactFlag is a redactFlagName and its separator: `--password `, `--token=`, `-api-key `.
+const redactFlag = `(?:^|\s)` + redactFlagName + `(?:=|\s+)`
// redactionRule is one redaction. ${1} and ${3}, when the pattern has them, are kept around the
// value.
@@ -231,10 +233,41 @@ var redactFlagNeedles = func() *redactNeedles {
return set
}()
+// redactListedFlagNeedles gate the rule for a flag and its value written as two quoted items of a
+// list: the flag's name is opened by a quote and a dash, and closed by a quote, a comma and the
+// quote opening the value.
+var redactListedFlagNeedles = func() *redactNeedles {
+ set := newRedactNeedles(true, redactFlagWords...)
+ set.followedBy = func(rest string) bool {
+ if rest == "" || (rest[0] != '"' && rest[0] != '\'') {
+ return false
+ }
+ rest = strings.TrimLeft(rest[1:], regexpSpace)
+ if !strings.HasPrefix(rest, ",") {
+ return false
+ }
+ rest = strings.TrimLeft(rest[1:], regexpSpace)
+ return rest != "" && (rest[0] == '"' || rest[0] == '\'')
+ }
+ set.precededBy = func(before string) bool {
+ start, ok := flagStart(before)
+ return ok && start > 0 && (before[start-1] == '"' || before[start-1] == '\'')
+ }
+ return set
+}()
+
// startsFlag reports whether the text before a flag word ends in what redactFlag puts ahead of it:
-// `(?:^|\s)--?[a-z0-9-]*`. That run of letters, digits and dashes can only begin where the
-// maximal one does, because the character before it must be whitespace, which the run excludes.
+// `(?:^|\s)--?[a-z0-9-]*`.
func startsFlag(before string) bool {
+ start, ok := flagStart(before)
+ return ok && (start == 0 || strings.ContainsRune(regexpSpace, rune(before[start-1])))
+}
+
+// flagStart finds the dash that opens the flag the text before a flag word ends in: the start of
+// the run of letters, digits and dashes at its end. A pattern's `--?[a-z0-9-]*` can only begin
+// where that maximal run does, because what it requires before the dash (whitespace, a quote) is
+// not part of the run.
+func flagStart(before string) (int, bool) {
start := len(before)
for start > 0 {
c := before[start-1]
@@ -244,9 +277,9 @@ func startsFlag(before string) bool {
start--
}
if start == len(before) || before[start] != '-' {
- return false
+ return 0, false
}
- return start == 0 || strings.ContainsRune(regexpSpace, rune(before[start-1]))
+ return start, true
}
// redactQuotes are the quote characters redactSeparator and quotedValues know.
@@ -331,8 +364,8 @@ var redactionRules = concatRules([]redactionRule{
// keeps its public `eyJ` prefix, as the shape rules below keep theirs, so `Bearer eyJ[REDACTED]`
// still says a token was there where `Bearer [REDACTED]` may only have been the word "token" or
// a `$VARIABLE`.
- foldedRule(`(?i)(authorization["']?\s*[:=]\s*["']?(?:bearer|basic|token|digest)\s+(?-i:eyJ)?)([^"'\s,]+)()`, "${1}"+redactedValue, nil, "authorization"),
- foldedRule(`(?i)(\bbearer\s+(?-i:eyJ)?)(?P<value>[a-z0-9._~+/=-]+)`, "${1}"+redactedValue, isRedactedJWTPrefix, "bearer"),
+ foldedRule(`(?i)(authorization["']?\s*[:=]\s*["']?(?:bearer|basic|token|digest)[ \t]+(?-i:eyJ)?)([^"'\s,]+)()`, "${1}"+redactedValue, nil, "authorization"),
+ foldedRule(`(?i)(\bbearer[ \t]+(?-i:eyJ)?)(?P<value>[a-z0-9._~+/=-]+)`, "${1}"+redactedValue, isRedactedJWTPrefix, "bearer"),
// A labeled assignment in prose, shell, env files, YAML, TOML or JSON: `token=x`,
// `export GITHUB_TOKEN="x"`, `{"api_key": "x"}`. The closing quote of a quoted label is allowed
// between the label and the separator. A quoted value runs to its closing quote; the unquoted
@@ -354,6 +387,12 @@ var redactionRules = concatRules([]redactionRule{
// usually write arguments: `--password "x y"`, `--token='x'`.
}, quotedRules(quotedFlag, nil), []redactionRule{
{pattern: lazyPattern(`(?i)(` + redactFlag + `)([^\s"'-][^\s"']*)`), replacement: "${1}" + redactedValue, needles: redactFlagNeedles},
+ // A flag and its value as two quoted items of an argument list, the way an MCP server's args
+ // are written in JSON, TOML and YAML: `"args": ["--api-key", "x"]`.
+ {
+ pattern: lazyPattern(`(?i)(["']` + redactFlagName + `["']\s*,\s*["'])(?P<value>(?:[^"'\n\\]|\\[^\n])+)`),
+ replacement: "${1}" + redactedValue, keep: isRedactedValue, needles: redactListedFlagNeedles,
+ },
// curl's basic-auth credentials: `-u user:pass`, `-uuser:pass`, `--user user:pass` and
// `--proxy-user user:pass`. The user name and the colon stay. A bare `-u user` (curl prompts for
// the password) has nothing to redact, and the rule is limited to curl lines so `docker run -u
@@ -519,12 +558,59 @@ func replaceAssigned(value string, assigned map[string]struct{}) string {
return strings.NewReplacer(pairs...).Replace(value)
}
-// IsSecretKeyName reports whether a structured field's name says its value is a credential, the
-// rule SanitizeMap applies, for callers that walk structured values of their own.
+// IsSecretKeyName reports whether a structured field's name has a word naming a credential, for
+// callers that judge a field by its name alone. IsSecretField judges a value held under it.
func IsSecretKeyName(key string) bool {
- return isSecretKeyName(key)
+ secret, _ := secretKeyName(key)
+ return secret
+}
+
+// IsSecretField reports whether a value is a credential by the name of the field holding it, the
+// rule SanitizeMap applies, for callers that walk structured values of their own. A value that
+// only names an auth scheme (`token_type: bearer`) is none, and nor is a number under a name whose
+// only credential word is "tokens", which is how a count of model tokens is named
+// (`max_tokens: 4096`, `input_tokens: "1200"`), where `GITHUB_TOKENS: abc` is a credential.
+func IsSecretField(key string, value interface{}) bool {
+ secret, onlyTokens := secretKeyName(key)
+ if !secret || onlyTokens && isNumber(value) {
+ return false
+ }
+ text, ok := value.(string)
+ return !ok || !isAuthScheme(text)
+}
+
+// isNumber reports whether a value is a number, or a string that only spells one.
+func isNumber(value interface{}) bool {
+ switch typed := value.(type) {
+ case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, json.Number:
+ return true
+ case string:
+ digits, point := 0, false
+ for i := range len(typed) {
+ switch c := typed[i]; {
+ case c >= '0' && c <= '9':
+ digits++
+ case c == '.' && !point:
+ point = true
+ case c == '-' && i == 0:
+ default:
+ return false
+ }
+ }
+ return digits > 0
+ }
+ return false
}
+// IsSecretFlag reports whether an argument is a flag named for a secret written on its own, so the
+// next argument is its value: `--api-key`, `--token`, `-password`. SanitizeSlice redacts that next
+// argument, for callers that walk argument lists of their own.
+func IsSecretFlag(arg string) bool {
+ return strings.HasPrefix(arg, "-") && redactSecretFlagPattern().MatchString(arg)
+}
+
+var redactSecretFlagPattern = lazyPattern(`(?i)^` + redactFlagName + `$`)
+
// redactGate answers whether text holds any of a set of needles, lower-casing it and searching for
// each set at most once per version of the text.
type redactGate struct {
@@ -589,26 +675,69 @@ func (g *redactGate) holds(set *redactNeedles) bool {
return false
}
-// isSecretKeyName reports whether a structured field's name says its value is a credential:
-// `password`, `api_key`, `apiKey`, `X-Api-Key`, `GITHUB_TOKEN`, `AWS_SECRET_ACCESS_KEY`,
-// `client_secret`, `Cookie`. The name must end in the marker, so `input_tokens`, `token_type`,
-// `author` and `PWD` are not secrets.
-func isSecretKeyName(key string) bool {
- var normalized strings.Builder
- for _, r := range strings.ToLower(key) {
- if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
- normalized.WriteRune(r)
+// secretKeyName reports whether a structured field's name says its value is a credential, and
+// whether the only word that says so is "tokens". The name is split into words at punctuation and
+// at camelCase, and a word naming a credential marks it wherever it stands: `GITHUB_TOKEN`,
+// `apiKey`, `X-Api-Key`, `X_AUTH`, `SECRET_KEY_BASE`, `DB_PASS`, `client_secret`, `Cookie`. A
+// name that runs one into the words before it (`PGPASSWORD`, `githubtoken`) is marked by how it
+// ends. `author`, `keyboard` and `PWD` are not secrets.
+func secretKeyName(key string) (secret, onlyTokens bool) {
+ var name strings.Builder
+ name.Grow(len(key))
+ start := 0
+ // endWord reports whether the word that ends here names a credential other than "tokens", and
+ // starts the next one.
+ endWord := func() bool {
+ word := name.String()[start:]
+ start = name.Len()
+ if word == "tokens" {
+ onlyTokens = true
+ return false
+ }
+ return slices.Contains(redactKeyWords, word)
+ }
+ for i := range len(key) {
+ c := key[i]
+ switch {
+ case c >= 'a' && c <= 'z' || c >= '0' && c <= '9':
+ name.WriteByte(c)
+ case c >= 'A' && c <= 'Z':
+ // A capital starts a word after a lower-case letter or a digit (`apiKey`), and after
+ // other capitals when a lower-case letter follows it (`APIKey`).
+ if i > 0 && (isLowerOrDigit(key[i-1]) || isUpper(key[i-1]) && i+1 < len(key) && key[i+1] >= 'a' && key[i+1] <= 'z') && endWord() {
+ return true, false
+ }
+ name.WriteByte(c + 'a' - 'A')
+ default:
+ if endWord() {
+ return true, false
+ }
}
}
- name := normalized.String()
+ if endWord() {
+ return true, false
+ }
+ whole := name.String()
for _, suffix := range redactKeySuffixes {
- if strings.HasSuffix(name, suffix) {
- return true
+ if strings.HasSuffix(whole, suffix) {
+ return true, false
}
}
- return false
+ return onlyTokens, onlyTokens
+}
+
+func isLowerOrDigit(c byte) bool { return c >= 'a' && c <= 'z' || c >= '0' && c <= '9' }
+
+func isUpper(c byte) bool { return c >= 'A' && c <= 'Z' }
+
+// redactKeyWords are the words of a field name that make it a credential's, with "tokens", which
+// secretKeyName reports apart. "pwd" is not one: PWD is the working directory.
+var redactKeyWords = []string{
+ "password", "passwords", "passwd", "pass", "passphrase", "secret", "secrets", "token", "key", "keys", "apikey",
+ "accesskey", "secretkey", "privatekey", "auth", "authorization", "credential", "credentials", "cookie",
}
+// redactKeySuffixes mark a field name that runs a credential's word into the words before it.
var redactKeySuffixes = []string{
"password", "passwd", "passphrase", "secret", "token", "apikey", "accesskey", "secretkey",
"privatekey", "authorization", "credential", "credentials", "cookie",
@@ -675,7 +804,7 @@ func SanitizeMap(input map[string]interface{}, opts PrivacyOptions) map[string]i
case string:
// A value whose field is named for a credential is one, whatever it looks like:
// `{"password": "hunter2"}` has no shape a pattern could recognize.
- if opts.RedactSecrets && typed != "" && isSecretKeyName(key) {
+ if opts.RedactSecrets && typed != "" && IsSecretField(key, typed) {
out[key] = redactedValue
continue
}
@@ -685,7 +814,7 @@ func SanitizeMap(input map[string]interface{}, opts PrivacyOptions) map[string]i
case []interface{}:
// A multi-valued header (`{"Cookie": ["sid=1"]}`, OTel's http.request.header.*) is as
// much a credential as a single value.
- if opts.RedactSecrets && isSecretKeyName(key) {
+ if opts.RedactSecrets && IsSecretKeyName(key) {
out[key] = redactAllStrings(typed, opts)
continue
}
@@ -729,6 +858,11 @@ func SanitizeSlice(input []interface{}, opts PrivacyOptions) []interface{} {
for index, value := range input {
switch typed := value.(type) {
case string:
+ // A flag named for a secret has its value in the next item: `["--api-key", "x"]`.
+ if opts.RedactSecrets && typed != "" && index > 0 && followsSecretFlag(input[index-1]) {
+ out[index] = redactedValue
+ continue
+ }
out[index] = CleanString(typed, limit, opts.RedactSecrets)
case map[string]interface{}:
out[index] = SanitizeMap(typed, opts)
@@ -741,6 +875,11 @@ func SanitizeSlice(input []interface{}, opts PrivacyOptions) []interface{} {
return out
}
+func followsSecretFlag(previous interface{}) bool {
+ flag, ok := previous.(string)
+ return ok && IsSecretFlag(flag)
+}
+
func SanitizeEvent(event Event, maxBytes int) Event {
event.Message = CleanString(event.Message, DefaultStringLimit, true)
if event.Tool != nil {
diff --git a/pkg/asymptoteobserve/privacy_gate_test.go b/pkg/asymptoteobserve/privacy_gate_test.go
index 0064ad48..cfc0965c 100644
--- a/pkg/asymptoteobserve/privacy_gate_test.go
+++ b/pkg/asymptoteobserve/privacy_gate_test.go
@@ -41,7 +41,7 @@ func TestRedactGateNeverChangesAResult(t *testing.T) {
"export GITHUB_TOKEN=ghp_0123456789abcdefghijklmnopqrstuvwxyz",
"curl -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abcdefghijk'",
"mysql --password hunter2 -u root", "postgres://user:pw@host/db", "input_tokens: 812",
- "ſecret=abcdefgh12345678", "KEY=abcdefgh12345678", "toKen\\\"=\"abc\"",
+ "ſecret=abcdefgh12345678", "KEY=abcdefgh12345678", "toKen\\\"=\"abc\"", `["--api-key", "abcdefgh12345678"]`,
"-----BEGIN RSA PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC\n-----END RSA PRIVATE KEY-----",
}
r := rand.New(rand.NewSource(1))
diff --git a/pkg/asymptoteobserve/privacy_test.go b/pkg/asymptoteobserve/privacy_test.go
index 7564a39d..533a6f36 100644
--- a/pkg/asymptoteobserve/privacy_test.go
+++ b/pkg/asymptoteobserve/privacy_test.go
@@ -120,6 +120,8 @@ func TestRedactStringRedactsCommonCredentialFormats(t *testing.T) {
{"bare url password without a user", "redis-cli -u redis://:pa55w0rd@localhost:6379 ping", "pa55w0rd"},
{"password flag", "mysql --user root --password hunter2hunter2", "hunter2hunter2"},
{"token flag", "tool login --token=opaque-flag-value", "opaque-flag-value"},
+ {"api key flag as a list item", `"args": ["-y", "@upstash/context7-mcp", "--api-key", "ctx7sk-abcdef0123456789"]`, "ctx7sk-abcdef0123456789"},
+ {"token flag as a toml list item", `args = ['--token', 'opaque-flag-value']`, "opaque-flag-value"},
{"curl basic auth", "curl -u admin:hunter2hunter2 https://api.example.com/v1", "hunter2hunter2"},
{"curl basic auth in a flag cluster", "curl -fsSu admin:hunter2hunter2 https://api.example.com", "hunter2hunter2"},
{"curl long user flag", "curl --user admin:hunter2hunter2 https://api.example.com", "hunter2hunter2"},
@@ -196,6 +198,8 @@ func TestRedactStringKeepsLabelsAndOrdinaryText(t *testing.T) {
"The cookie: chocolate chip recipe is great",
"curl -b cookies.txt https://example.com",
`curl --user-agent "Mozilla/5.0 (X11: Linux)" https://example.com`,
+ `"args": ["--max-tokens", "4096", "--author", "Ada"]`,
+ "token_type: bearer\nexpires_in: 3600",
}
for _, input := range kept {
if got := RedactString(input); got != input {
@@ -250,7 +254,11 @@ func TestSanitizeMapRedactsValuesUnderSecretKeys(t *testing.T) {
"password": "hunter2",
"apiKey": "plain",
"headers": map[string]interface{}{"X-Api-Key": "abc", "Cookie": "sid=1", "Accept": "application/json"},
- "env": map[string]interface{}{"GITHUB_TOKEN": "v1", "AWS_SECRET_ACCESS_KEY": "v2", "PWD": "/home/ada"},
+ "env": map[string]interface{}{
+ "GITHUB_TOKEN": "v1", "AWS_SECRET_ACCESS_KEY": "v2", "SECRET_KEY_BASE": "v3", "OPENAI_KEY": "v4",
+ "X_AUTH": "v5", "PGPASSWORD": "v6", "SSH_KEYS": "v7", "GITHUB_TOKENS": "v8", "DB_PASS": "v9",
+ "PWD": "/home/ada", "AUTHOR_NAME": "Ada Lovelace", "KEYBOARD": "dvorak", "MAX_TOKENS": "1200",
+ },
},
"usage": map[string]interface{}{"input_tokens": float64(12)},
"token_type": "Bearer",
@@ -262,16 +270,22 @@ func TestSanitizeMapRedactsValuesUnderSecretKeys(t *testing.T) {
t.Fatal(err)
}
text := string(data)
- for _, secret := range []string{"hunter2", `"plain"`, `"abc"`, "sid=1", `"v1"`, `"v2"`} {
+ for _, secret := range []string{"hunter2", `"plain"`, `"abc"`, "sid=1", `"v1"`, `"v2"`, `"v3"`, `"v4"`, `"v5"`, `"v6"`, `"v7"`, `"v8"`, `"v9"`} {
if strings.Contains(text, secret) {
t.Fatalf("SanitizeMap leaked %s: %s", secret, text)
}
}
- for _, keep := range []string{"application/json", "/home/ada", `"input_tokens":12`, `"token_type":"Bearer"`, `"author":"Ada"`} {
+ for _, keep := range []string{"application/json", "/home/ada", `"input_tokens":12`, `"token_type":"Bearer"`, `"author":"Ada"`, "Ada Lovelace", "dvorak", `"MAX_TOKENS":"1200"`} {
if !strings.Contains(text, keep) {
t.Fatalf("SanitizeMap dropped %s: %s", keep, text)
}
}
+ args := SanitizeMap(map[string]interface{}{
+ "args": []interface{}{"-y", "@upstash/context7-mcp", "--api-key", "ctx7sk-abcdef0123456789", "--max-tokens", "4096"},
+ }, PrivacyOptions{RedactSecrets: true, StringLimit: DefaultRawStringLimit})
+ if data, _ := json.Marshal(args); string(data) != `{"args":["-y","@upstash/context7-mcp","--api-key","[REDACTED]","--max-tokens","4096"]}` {
+ t.Fatalf("argument list = %s, want only the value after --api-key redacted", data)
+ }
headers := SanitizeMap(map[string]interface{}{
"Authorization": []interface{}{"Basic dXNlcjpwYXNz"},
"Cookie": []interface{}{"sid=abcdef123", ""},
diff --git a/pkg/asymptoteobserve/redact_cost_test.go b/pkg/asymptoteobserve/redact_cost_test.go
index b9ad040d..eeb99fda 100644
--- a/pkg/asymptoteobserve/redact_cost_test.go
+++ b/pkg/asymptoteobserve/redact_cost_test.go
@@ -23,10 +23,20 @@ func TestRedactStringRemovesBareCopiesLongestFirst(t *testing.T) {
}
}
-func TestIsSecretKeyName(t *testing.T) {
- for key, want := range map[string]bool{"password": true, "AWS_SECRET_ACCESS_KEY": true, "client_secret": true, "X-Api-Key": true, "input_tokens": false, "author": false} {
- if got := IsSecretKeyName(key); got != want {
- t.Errorf("IsSecretKeyName(%q) = %v, want %v", key, got, want)
+func TestIsSecretField(t *testing.T) {
+ for _, tc := range []struct {
+ key string
+ value interface{}
+ want bool
+ }{
+ {"password", "hunter2", true}, {"AWS_SECRET_ACCESS_KEY", "x", true}, {"client_secret", "x", true},
+ {"X-Api-Key", "x", true}, {"SECRET_KEY_BASE", "x", true}, {"DB_PASS", "x", true}, {"SMTP_PASS", "x", true},
+ {"GITHUB_TOKENS", "abc", true}, {"pin_token", 1234, true}, {"password", "12345678", true},
+ {"max_tokens", 4096, false}, {"input_tokens", float64(812), false}, {"input_tokens", "1200", false},
+ {"token_type", "Bearer", false}, {"author", "Ada", false}, {"PWD", "/home/ada", false}, {"keyboard", "dvorak", false},
+ } {
+ if got := IsSecretField(tc.key, tc.value); got != tc.want {
+ t.Errorf("IsSecretField(%q, %#v) = %v, want %v", tc.key, tc.value, got, tc.want)
}
}
}