Repository navigation
fix(#5705)!: stop JSON redaction from eating escaping backslashes #10082
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
f6dc2ce
abfa104
dd29b2c
4911942
b5f395b
364b1ff
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,6 +7,7 @@ import ( | |
| "slices" | ||
| "strings" | ||
| "sync" | ||
| "unicode/utf8" | ||
| ) | ||
|
|
||
| // Runtime secrets are exact credential values the runner learned during | ||
|
|
@@ -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 | ||
|
|
@@ -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 | ||
|
|
||
|
|
@@ -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) | ||
|
|
@@ -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", | ||
|
|
@@ -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 | ||
| // 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 | ||
|
|
@@ -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. | ||
| // | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [MEDIUM]
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 Suggestion: Trim the prefix back to a rune boundary (for example, take the first 4 runes, or step back with Verified: reproduced with a go test probe; NewSecretRedactor().Scan on a Japanese password gives invalid UTF-8 |
||
| // 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. | ||
|
andrewevansrh marked this conversation as resolved.
Resolved
|
||
| func mask(value string) string { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Suggested fix: No code change; keep the breaking-change note in the PR and release notes. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [low] backward-incompatible mask() returns Suggested fix: No code change needed beyond the declared breaking-change marker. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [low] backward-incompatible The fallback 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 { | ||
|
|
@@ -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]*\\)")`}, | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. 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. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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>". | ||
|
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-----`}, | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.