Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/guides/dev/tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ cut can take the `@` that marks a password and the tail cut the `https://`
before it (`promptHidesAlterations`) — is recorded `***` whole; the
prompt the agent is sent is not changed, and the mask the first
scan leaves for a connection-string password of ten or more bytes matches
its own pattern and counts a finding —
its own pattern, counts a finding, and is itself masked `***` —
and sets `gen_ai.input.messages` on the span
before the runtime starts, so each finalize path carries it. Its findings
join the iteration's, and its encoded size is charged against
Expand Down
5 changes: 3 additions & 2 deletions internal/cli/content_collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,9 @@ func attachContent(span trace.Span, res contentResult) {
// values, once more after the fold, which can spell out a value that pass
// saw in compatibility forms. The mask that first scan leaves for a
// connection-string password of ten or more bytes ("abcd...") matches its
// own pattern again, so such a prompt counts a finding here; a shorter
// password is masked "***", which does not.
// own pattern again, so such a prompt counts a finding here and the
// placeholder is masked "***"; a shorter password is masked "***", which
// does not match.
// The pipeline also folds compatibility characters the agent received
// unfolded. Findings join the iteration's and surface through Result.
//
Expand Down
740 changes: 740 additions & 0 deletions internal/security/jsonsanitize.go

Large diffs are not rendered by default.

1,636 changes: 1,636 additions & 0 deletions internal/security/jsonsanitize_test.go

Large diffs are not rendered by default.

233 changes: 213 additions & 20 deletions internal/security/redactor.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"slices"
"strings"
"sync"
"unicode/utf8"
)

// Runtime secrets are exact credential values the runner learned during
Expand All @@ -17,6 +18,12 @@ import (
// trivial string can never blank out ordinary output.
const minRuntimeSecretLen = 8

// minJSONFieldLen is the shortest value masked as a json_field. It is counted in
// runes, matching the {8,} quantifier the json_field value used before the
// pattern was widened to span escaped quotes inside a JSON string. The other
// structural patterns enforce their own minimum in the pattern itself.
const minJSONFieldLen = 8

var (
runtimeSecretsMu sync.RWMutex
runtimeSecrets []string
Expand Down Expand Up @@ -87,6 +94,21 @@ func NewSecretRedactor() *SecretRedactor {
func (s *SecretRedactor) Name() string { return "secret_redactor" }

func (s *SecretRedactor) Scan(text string) ScanResult {
return s.scan(text, false)
}

// scanWholeValueSecrets masks only the secrets whose match is the entire value:
// registered runtime values and private-key blocks. It is meant for bytes a leaf
// scan has already redacted, where a pattern match can be a redaction
// placeholder plus JSON escape characters rather than a new secret (#5705).
func (s *SecretRedactor) scanWholeValueSecrets(text string) ScanResult {
return s.scan(text, true)
}

// scan runs the pattern set. wholeValueOnly restricts it to the patterns whose
// match is the whole secret, which are the only ones that can still be present
// in bytes an earlier pass already redacted.
func (s *SecretRedactor) scan(text string, wholeValueOnly bool) ScanResult {
result := ScanResult{Safe: true, Sanitized: text}
current := text

Expand All @@ -110,29 +132,37 @@ func (s *SecretRedactor) Scan(text string) ScanResult {

// Prefix-based patterns (full match is the secret).
// Use ReplaceAll to catch duplicate occurrences of the same secret.
for _, p := range s.prefixPatterns {
// Deduplicate matches so we report each unique secret once.
seen := map[string]bool{}
matches := p.regex.FindAllString(current, -1)
for _, match := range matches {
if seen[match] {
continue
if !wholeValueOnly {
for _, p := range s.prefixPatterns {
// Deduplicate matches so we report each unique secret once.
seen := map[string]bool{}
matches := p.regex.FindAllString(current, -1)
for _, match := range matches {
if seen[match] {
continue
}
seen[match] = true
masked := mask(match)
result.Findings = append(result.Findings, Finding{
Scanner: "secret_redactor",
Name: p.name,
Severity: "critical",
Detail: fmt.Sprintf("Redacted %s (%d chars) -> %s", p.name, len(match), masked),
})
current = strings.ReplaceAll(current, match, masked)
result.Safe = false
}
seen[match] = true
masked := mask(match)
result.Findings = append(result.Findings, Finding{
Scanner: "secret_redactor",
Name: p.name,
Severity: "critical",
Detail: fmt.Sprintf("Redacted %s (%d chars) -> %s", p.name, len(match), masked),
})
current = strings.ReplaceAll(current, match, masked)
result.Safe = false
}
}

// Structural patterns (capture group is the secret)
// Structural patterns (capture group is the secret). Only the private-key
// block is safe to match in whole-value mode: every other pattern captures a
// value out of surrounding text, so a match on bytes that already carry a
// redaction placeholder can be that placeholder rather than a secret.
for _, p := range s.structuralPatterns {
if wholeValueOnly && p.name != "private_key" {
continue
}
// Private key: replace full match (no capture group needed).
if p.name == "private_key" {
matches := p.regex.FindAllString(current, -1)
Expand Down Expand Up @@ -171,11 +201,61 @@ func (s *SecretRedactor) Scan(text string) ScanResult {
if start < 0 || end < 0 {
continue
}
// A double-quoted value that ends in a backslash is ambiguous: the
// bounded branch the pattern returns first reads the \" as a literal
// backslash before the closing quote, while the escape-reading branch
// reads it as an escaped quote inside the value. Prefer the reading
// that ends the string at a JSON value boundary, so a credential that
// carries an escaped quote stays masked whole (#10082).
if p.name == "json_field" {
if escapeStart, escapeEnd, ok := resolveJSONFieldDoubleQuote(current, loc[0], start, end); ok {
start, end = escapeStart, escapeEnd
}
}

secret := current[start:end]
if p.name == "json_field" && isExemptJSONField(current, loc[0], loc[1], secret) {
continue
}
// If the matched secret ends with a backslash and is immediately
// followed by a quote delimiter, the trailing backslash was escaping
// that delimiter (e.g. \" in JSON or code strings). Preserve the
// escape by excluding the backslash from the redacted secret span.
// json_field spans escaped quotes in its own value pattern, so its
// capture already ends at the delimiter it belongs to.
if p.name != "json_field" && end < len(current) && (current[end] == '"' || current[end] == '\'') {
numBackslashes := 0
for k := len(secret) - 1; k >= 0 && secret[k] == '\\'; k-- {
numBackslashes++
}
if numBackslashes%2 == 1 {
secret = secret[:len(secret)-1]
end--
}
}
if len(secret) == 0 {
continue
}
// A captured value is always masked, even when it already looks
// like a mask. The shape of a placeholder (4 characters and "...",
// or "***") is also the shape of a real short secret:
// db_connection_password accepts a value of 4 characters or more,
// so skipping every 7-byte capture that ends in "..." left a real
// password such as postgres://u:abcd...@host in the output. Callers
// that rescan bytes an earlier pass already redacted use
// scanWholeValueSecrets, which runs no value pattern, so they never
// reach this loop; a full Scan over redacted text can therefore
// only be re-masking a placeholder into "***", never a secret into
// itself.
//
// Only json_field needs the length gate here: its value pattern
// matches any length, while env_assignment, auth_header and
// db_connection_password enforce their own minimum in the pattern.
// The gate counts runes and runs on the trimmed span, so the bytes
// actually masked are never shorter than the documented minimum.
if p.name == "json_field" && utf8.RuneCountInString(secret) < minJSONFieldLen {
continue
}
masked := mask(secret)
result.Findings = append(result.Findings, Finding{
Scanner: "secret_redactor",
Expand Down Expand Up @@ -207,6 +287,58 @@ func (s *SecretRedactor) Scan(text string) ScanResult {
// 8- and 9-byte paths such as /root/qa stay masked, as before #9944.
var authorPathValue = regexp.MustCompile(`^/[A-Za-z0-9_./-]{9,}$`)

// jsonFieldEscapeReadingRe is the json_field pattern restricted to the
// escape-reading double-quoted value branch. scan runs it against the same
// match start to compare the escape reading with the bounded reading the full
// pattern returns first; see resolveJSONFieldDoubleQuote.
var jsonFieldEscapeReadingRe = regexp.MustCompile(`(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*"((?:\\[\s\S]|[^"\\\r\n])*)"`)

// jsonValueBoundaryRe matches the text that may follow a complete JSON string
// value: a member or element separator, a closing bracket, or the end of the
// physical line.
//
// It runs against the remainder of the text after the escape reading's closing
// quote, so it is anchored with \A: a (?m)^ would also accept a boundary on any
// later line, letting the escape reading win whenever unrelated text further
// down the input starts with }, ] or a blank line, and swallow the separator
// that follows the value (#10082).
var jsonValueBoundaryRe = regexp.MustCompile(`\A[ \t]*(?:,|\}|\]|\r?\n|\z)`)

// resolveJSONFieldDoubleQuote picks between the two readings of a
// double-quoted json_field value that ends in a backslash. The pattern returns
// the bounded reading first, because in raw text — a log line or a YAML flow
// mapping — "api_key": "secret\", "password": "..." means the backslash is
// literal and the value ends at that quote; taking the \" as an escape there
// would run on to the next field's opening quote and swallow the separator.
// The same bytes inside valid JSON mean the opposite: a \" can only be an
// escaped quote, so a value such as {"password":"ab\",cd"} keeps going to the
// later quote, and stopping at the first one would mask a fragment and leave
// the rest of the credential in an invalid document (#10082).
//
// The two readings are told apart by where they end. An escape reading that
// closes the string at a JSON value boundary (a separator, a bracket or the
// line end) is a well-formed string, so it wins when it covers more than the
// bounded reading. When it ends anywhere else — before the next field's key,
// for example — it ran past the real end of the value and the bounded reading
Comment thread
andrewevansrh marked this conversation as resolved.
Resolved
// stands. The returned span is the value to mask.
func resolveJSONFieldDoubleQuote(text string, matchStart, valueStart, valueEnd int) (int, int, bool) {
if matchStart < 0 || matchStart >= len(text) {
return 0, 0, false
}
loc := jsonFieldEscapeReadingRe.FindStringSubmatchIndex(text[matchStart:])
if loc == nil || loc[0] != 0 || loc[2] < 0 {
return 0, 0, false
}
start, end := matchStart+loc[2], matchStart+loc[3]
if start != valueStart || end <= valueEnd {
return 0, 0, false
}
if !jsonValueBoundaryRe.MatchString(text[matchStart+loc[1]:]) {
return 0, 0, false
}
return start, end, true
}

// isExemptJSONKey reports whether a json_field match has the key "author",
// in any case. "author" contains the trigger word "auth" but names a
// sender, such as a codex child agent path (#9944). Only that one name is
Expand Down Expand Up @@ -237,11 +369,41 @@ func isExemptJSONField(text string, matchStart, matchEnd int, secret string) boo
return authorPathValue.MatchString(secret) && isExemptJSONKey(text[matchStart:matchEnd])
}

// mask returns a redacted representation of a secret value.
//

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] mask() can split a UTF-8 rune and write invalid UTF-8, even though the new doc comment says the result is safe to splice

mask keeps value[:4], which is the first four bytes, not runes. For a non-ASCII value the cut can land inside a multi-byte character. At head, Scan on "password": "日本語のパスワードです" produces "password": "日\xe6...", and utf8.ValidString on the result is false.

The new doc comment says the returned text is safe to splice into a JSON or YAML string. jq rejects invalid UTF-8, which is the kind of failure #5705 is about. The PR now counts the json_field minimum in runes but still slices the mask prefix in bytes, and text-path Pipeline.Scan callers write the result back without re-encoding it.

Suggestion: Trim the prefix back to a rune boundary (for example, take the first 4 runes, or step back with utf8.RuneStart), or return *** when value[:4] is not valid UTF-8. Add a utf8.ValidString assertion to the "json_field minimum counts runes, not bytes" subtest in scanner_test.go.

Verified: reproduced with a go test probe; NewSecretRedactor().Scan on a Japanese password gives invalid UTF-8 日\xe6... at 364b1ff; raised by: DeepSeek

// The returned text is safe to splice into a JSON or YAML string value, but not
// into arbitrary byte ranges: it keeps the first four bytes unless they contain
// an escape or a quote delimiter, in which case it returns "***". Callers that
// write it back must place it inside a string literal (writeJSONString does this
// for the structural path); a caller that rebuilds raw framing must re-escape
// the surrounding text itself.
Comment thread
andrewevansrh marked this conversation as resolved.
Resolved
func mask(value string) string {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] backward-incompatible

Redacted output is no longer byte-identical to earlier releases (escape handling and the *** fallback mask changed). Declared by the ! marker and BREAKING CHANGE footer; keep the note in release notes.

Suggested fix: No code change; keep the breaking-change note in the PR and release notes.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] backward-incompatible

mask() returns *** instead of the first four bytes plus ... when the kept prefix carries a backslash or quote delimiter, so placeholder text differs for those inputs. The package is internal; only artifact placeholder text changes, and the change is declared with !.

Suggested fix: No code change needed beyond the declared breaking-change marker.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] backward-incompatible

The fallback *** mask changes sanitized output text and finding details for values whose four-byte prefix carries an escape or quote delimiter. Declared as a breaking change.

Suggested fix: No code change needed; name the placeholder change in the release note.

if len(value) < 10 {
return "***"
}
return value[:4] + "..."
prefix := value[:4]
// A prefix that carries an escape or a quote delimiter cannot be written
// back: in a JSON or YAML string it would escape or close the surrounding
// quoting and break the document (#5705). The quote case covers a YAML
// single-quoted value whose doubled quote ('') falls inside the prefix:
// keeping half of the pair leaves a lone quote that ends the string early.
if strings.ContainsAny(prefix, "\\'\"") {
return "***"
}
return prefix + "..."
}

// isAlreadyMasked reports whether value is already a redaction placeholder
// produced by mask. Trailing backslashes are ignored: a placeholder that sits in
// a JSON string can be followed by escape characters once the string is
// re-encoded, and that tail must not turn the placeholder into a new secret
// (#5705).
//
// Only callers that know the value came from mask may use this. The shape alone
// cannot tell a placeholder from a real short secret, so Scan does not apply it.
func isAlreadyMasked(value string) bool {
value = strings.TrimRight(value, `\`)
return value == "***" || len(value) == 7 && strings.HasSuffix(value, "...")
}

func defaultPrefixPatterns() []secretPattern {
Expand Down Expand Up @@ -297,7 +459,38 @@ func defaultStructuralPatterns() []secretPattern {
// the mask keeps it visible. A bare value still ends at the first
// space, as in the PostToolUse hook.
{"env_assignment", `(?i)(?:^|\s)(?:export\s+)?((?:[A-Za-z0-9]+_)*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|PASSWD|AUTH|API_KEY)(?:_[A-Za-z0-9]+)*)\s*=\s*(?:['"](?:(?:basic|bearer|token)[ \t]+)?)?([^\s"'}\]),;]{8,})['"]?`},
{"json_field", `(?:"[^"]*(?i:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?i:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"([^"]{8,})"|'([^']{8,})')`},
// json_field captures a value out of a quoted field. The escape-reading
// branches consume escaped delimiters, so a JSON or YAML string with an
// embedded quote is matched whole. A value that ends in a literal backslash
// right before its closing quote is ambiguous: reading that \" as an escape
// runs on to the next quote on the line, which is usually the next field's
// opening quote, and swallows the separator between the two fields — and
// with it the chance to mask the second field. Each quote style therefore
// has a bounded branch that keeps the backslash out of the captured value
// and matches only when the closing quote is followed by a field or line
// boundary. The boundary accepts an optional CR before the line end, so a
// CRLF line is treated like an LF one. Those bounded branches come before
// the escape-reading ones because Go's regexp alternation is leftmost-first:
// for 'api_key': 'secret\', 'password': '...' and
// "api_key": "secret\", "password": "..." the escape-reading branch would
// otherwise match first and eat the comma. scan corrects that order for a
// double-quoted value whose closing \" continues a valid JSON string rather
// than ending the field (resolveJSONFieldDoubleQuote). The strict
// double-quoted branch stops at a raw newline, so a JSON value ending in \"
// cannot run on to the next line's quote and swallow the field there
// (#9944). A value folded across physical lines (a YAML or log string, not
// JSON) still needs to be matchable when its closing quote ends the field or
// the line: the sixth branch allows raw newlines but only at that boundary,
// so it cannot run on to a later field's quote. A value that ends in a
// literal backslash and is followed by neither a field nor a line end — a
// log line such as "password": "Abc123xyzQ\" (rotated) — is matched by the
// last-resort branch, which takes any trailing-backslash value so it can
// never fall through unmasked. That branch is last so it can only win when
// no bounded or escape-reading branch matches. The single-quoted branch
// keeps a raw newline inside the value matchable, as it was before the
// escape handling was added. The minimum length is enforced in scan, not
// here.
{"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"([^"\r\n]*\\)"[ \t]*(?:,|\}|\]|\r?$)|"((?:\\[\s\S]|[^"\\\r\n])*)"|'((?:''|[^'\r\n])*\\)'[ \t]*(?:,|\}|\]|\r?$)|'((?:''|\\\r?\n|\\.|[^'\r\n\\])*[^'\r\n\\])'|'([^']*)'|"((?:\\[\s\S]|[^"\\])*)"[ \t]*(?:,|\}|\]|\r?$)|"([^"\r\n]*\\)")`},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] secret-exposure

The rewritten json_field expression no longer redacts a double-quoted multiline credential when prose follows its closing quote, e.g. "password": "firs..." (rotated). The ordinary double-quoted branch excludes raw newlines, the multiline branch requires a comma, bracket, brace or line end after the closing quote, and the last-resort branch requires a trailing backslash. The base pattern "([^"]{8,})" matched this input, so this is a regression for every existing Pipeline.Scan caller.

Suggested fix: Handle multiline double-quoted values followed by prose without consuming adjacent fields, and add a regression asserting that both lines of the credential are removed while the trailing annotation survives.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] backward-incompatible

json_field now matches escaped-quote and multiline quoted values it previously did not, changing sanitized output for those inputs. Declared as a breaking change in the title and commit footer.

Suggested fix: No code change needed beyond the declared breaking-change marker.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] backward-incompatible

The json_field pattern was rewritten (7 capture groups instead of 2; the 8-rune minimum moved from the quantifier into scan). Only scan reads the groups, so nothing in the module breaks, but callers depending on finding counts or exact sanitized text from Pipeline.Scan can see different output.

Suggested fix: Call out the changed matching behavior in the release notes; nothing outside scan depends on the old group layout.

// The optional quote covers YAML: authorization: "Bearer <token>".
Comment thread
andrewevansrh marked this conversation as resolved.
Resolved
{"auth_header", `(?i)(?:Authorization|X-Api-Key|X-Auth-Token)\s*:\s*['"]?(?:(?:Basic|Bearer|Token)\s+)?([^\s"'}\]),;]{12,})`},
{"private_key", `-----BEGIN\s+(?:RSA\s+|EC\s+|OPENSSH\s+)?PRIVATE KEY-----[\s\S]*?-----END\s+(?:RSA\s+|EC\s+|OPENSSH\s+)?PRIVATE KEY-----`},
Expand Down
36 changes: 36 additions & 0 deletions internal/security/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,42 @@ func (p *Pipeline) Scan(text string) ScanResult {
return aggregate
}

// wholeValueScanner masks only the secrets whose match is the entire value.
// Pipeline.scanWholeValueSecrets uses it to rescan bytes an earlier pass has
// already redacted without mistaking a redaction placeholder for a secret.
type wholeValueScanner interface {
scanWholeValueSecrets(text string) ScanResult
}

// scanWholeValueSecrets runs only the whole-value masking of the pipeline's
// scanners: registered runtime values and private-key blocks. Normalizers and
// value patterns are skipped, because the leaf scan has already applied them to
// the decoded document, and re-running them over serialized bytes can only
// damage the redactions they produced (#5705).
func (p *Pipeline) scanWholeValueSecrets(text string) ScanResult {
aggregate := ScanResult{Safe: true, Sanitized: text}
current := text
for _, s := range p.scanners {
w, ok := s.(wholeValueScanner)
if !ok {
continue
}
result := w.scanWholeValueSecrets(current)
aggregate.Findings = append(aggregate.Findings, result.Findings...)
if !result.Safe {
aggregate.Safe = false
}
if result.Sanitized != "" {
current = result.Sanitized
aggregate.Sanitized = current
}
}
if aggregate.Sanitized == text {
aggregate.Sanitized = "" // no changes
}
return aggregate
}

// InputPipeline returns the standard input scanning pipeline for
// untrusted text entering the agent. Order matters:
// 1. UnicodeNormalizer — strip invisible chars, normalize fullwidth
Expand Down
Loading
Loading