From 53cdfed302334dfc201f420a74306cfa6e095dec Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 3 Dec 2026 10:41:50 -0500 Subject: [PATCH] fix(#5705): mask private-key blocks that span JSON members or records A JSON document can carry a private key one fragment per member: BEGIN in one string, body lines in the next, END in a third. Masking any single member removes the marker the block's own pattern needs, and the bytes scan that runs after the rewrite sees no block any more, so the body was written back in clear text. Such a block is now detected on a decoded view of the document or stream, before anything is rewritten, and neutralized member by member. The boundary members always carry marker text and are masked even when a marker is split across two of them; a member in between is masked when it carries a marker, a run that looks like PEM body material, or joins with its neighbours into text that does. Object keys keep their names unless the name itself is block content, so a review that merely quotes the PEM header in one finding and the footer in another keeps the shape and the enum values review-result.schema.json requires, instead of being dropped by schema validation. Records carrying part of a block across a record boundary are replaced with a fail-closed marker, because the record framing cannot be rewritten. A body split so that one-character and longer chunks alternate is a known residual; uniform chunks and complete body lines are masked. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 18 + .../user/run-artifacts-and-private-data.md | 5 +- internal/security/jsonsanitize.go | 856 +++++++++++++++++- internal/security/jsonsanitize_test.go | 775 +++++++++++++++- 4 files changed, 1591 insertions(+), 63 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index b093a2163f..3bf3084f8e 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -659,6 +659,24 @@ Every other pattern has already been applied to the decoded key or value, so a match on the serialized bytes would be a redaction placeholder plus JSON escape characters, not a secret (#5705). +A private-key block can also span members or records: one string holds the BEGIN +marker, another the body, a third the END marker. Masking any of them would hide +the marker from every later scan, so such a block is detected on a decoded view +of the document or stream before anything is rewritten, and handled where it +lives. The members the match starts and ends in carry marker text, so they are +always masked — even when a marker is split across two members and neither +fragment looks like one alone. A member in between is masked when it carries a +block marker, a run that looks like body material (16+ base64 characters mixing +upper case, lower case and a digit, and not hex only), or when the joined text of +consecutive members does, which is what catches a body split into short chunks. An +object key keeps its name unless the name itself is block content, so a document +that merely quotes the PEM header in one finding and the footer in another keeps +the shape `review-result.schema.json` accepts, including its enum-valued fields. +A body split so that one-character and longer chunks alternate is a known +residual; uniform chunks and complete body lines are masked. Records that carry +part of a block across a record boundary are replaced with a fail-closed marker +instead, because the framing itself cannot be rewritten. + Some content cannot be redacted in place. A JSON document or JSONL record is replaced with a valid fail-closed marker instead — never with corrupted syntax — when a redaction would invalidate the JSON or a match spans record diff --git a/docs/guides/user/run-artifacts-and-private-data.md b/docs/guides/user/run-artifacts-and-private-data.md index bd51b7247f..c96ce82a65 100644 --- a/docs/guides/user/run-artifacts-and-private-data.md +++ b/docs/guides/user/run-artifacts-and-private-data.md @@ -350,7 +350,10 @@ document, or the JSONL record that carries it, with a JSON error marker, and a file whose redacted content cannot be read, written or computed is replaced by such a marker and fails the run. If the marker cannot be written and the file cannot be removed either, the run's error says the unredacted file is still on -disk. When a +disk. A private-key block that spans JSON members is handled in place instead: +object keys keep their names unless a key name is itself a line of the key body, +and each string value — or key name — that carries block text or base64 key +material becomes `[REDACTED PRIVATE KEY]`. When a replacement happens in a run that still exits 0, the job log says so. On GitHub Actions this is an error annotation: fullsend writes a `::error::` workflow command whenever the job sets `GITHUB_ACTIONS=true`, and GitHub Actions renders diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 4919d01007..08108282fc 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -19,11 +19,17 @@ import ( // reason into an operator alert, because a replaced file loses whatever the // agent wrote into it (#5705). const ( - failClosedInvalidJSON = `{"error":"output removed because redaction would invalidate JSON"}` - failClosedCrossRecordJSON = `{"error":"output removed because output contained a cross-record secret"}` - FailClosedUnwritableJSON = `{"error":"output removed because it could not be redacted"}` + failClosedInvalidJSON = `{"error":"output removed because redaction would invalidate JSON"}` + failClosedCrossRecordJSON = `{"error":"output removed because output contained a cross-record secret"}` + failClosedSpansMembersJSON = `{"error":"output removed because a private key block spans JSON framing"}` + FailClosedUnwritableJSON = `{"error":"output removed because it could not be redacted"}` ) +// privateKeyMask replaces each JSON string value that carries key material from a +// private-key block spanning JSON framing, and any key name that carries block +// text itself. +const privateKeyMask = "[REDACTED PRIVATE KEY]" + // utf8BOM is the encoding mark some tooling writes at the start of a UTF-8 // file. encoding/json does not accept it as leading content, so a document that // carries one has to lose the prefix before it can be parsed and get it back on @@ -75,6 +81,7 @@ var outputRemovalMarkers = []struct { }{ {failClosedInvalidJSON, "redaction would invalidate JSON"}, {failClosedCrossRecordJSON, "a secret spanned multiple records"}, + {failClosedSpansMembersJSON, "a private key block spans JSON framing"}, {FailClosedUnwritableJSON, "it could not be redacted"}, } @@ -144,7 +151,19 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { // every return below puts it back, so it is stripped once here. body := bytes.TrimPrefix(doc, utf8BOM) trimmed := bytes.TrimSpace(body) - rebuilt, findings, err := rewriteJSONTokens(trimmed, p) + // A block that spans members is invisible to both the leaf scan and the + // written-bytes scan once a member is masked, and its markers may be + // \u-escaped in the raw bytes. The decoded view is the only place it is + // visible, so it is consulted before anything is rewritten. + spans := collectJSONLeaves(trimmed).spanningPrivateKeys() + if spans.unmappable > 0 { + // The view is built from the leaves themselves, so localization should + // never fail. If the walks ever disagree, fail closed rather than write + // bytes that may still carry the block. + return restoreBOM(doc, preserveTrailingNewline([]byte(failClosedSpansMembersJSON), doc)), + []Finding{privateKeySpanFinding(spans.unmappable, false)}, nil + } + rebuilt, findings, err := rewriteJSONTokens(trimmed, p, spans) if err != nil { // json.Valid accepted the text and the walk uses the same scanner, so // this is a decoder limit rather than a syntax error. Return the error @@ -152,12 +171,16 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { return nil, nil, fmt.Errorf("could not sanitize JSON document: %w", err) } out := body - if len(findings) > 0 { + if len(findings) > 0 || spans.localized > 0 { out = rebuilt } + if spans.localized > 0 { + findings = append(findings, privateKeySpanFinding(spans.localized, true)) + } // Scan the bytes that will actually be written, for the whole-value secrets - // a leaf scan cannot see: a registered runtime value, or a private-key block - // that spans JSON framing and so cannot be mapped back to a single leaf. + // a leaf scan cannot see: a runtime value or a private-key block that spans + // JSON framing (for example a PEM block split across members) and so cannot + // be mapped back to a single leaf. sanitizedOut, outputFindings := redactJSONOutput(out, p) if bytes.Equal(sanitizedOut, body) { // Nothing changed: hand the document back exactly as received. Running @@ -169,11 +192,473 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { return restoreBOM(doc, preserveTrailingNewline(sanitizedOut, body)), append(findings, outputFindings...), nil } -// decodedViewNormalizer normalizes decoded JSON text the same way the per-leaf -// scan does, so a key or value is matched and written back in one spelling: -// invisible characters stripped and compatibility forms folded. +// privateKeySpanFinding reports the private-key blocks that span JSON framing. +// localized says whether they were masked in the members that carried them or +// the whole document had to be dropped. +func privateKeySpanFinding(blocks int, localized bool) Finding { + detail := fmt.Sprintf("%d private key block(s) span JSON framing; masked the string values carrying them", blocks) + if !localized { + detail = "Private key block spans JSON framing and cannot be localized; output removed" + } + return Finding{ + Scanner: "secret_redactor", + Name: "private_key", + Severity: "critical", + Detail: detail, + } +} + +// privateKeyRe is the structural private-key pattern. A block that spans JSON +// framing has to be detected on the raw document: running the whole pipeline +// first lets a sensitive-named member mask the BEGIN marker and hide it. +var privateKeyRe = func() *regexp.Regexp { + for _, pattern := range defaultStructuralPatterns() { + if pattern.name == "private_key" { + return pattern.regex + } + } + panic("private_key structural pattern is missing") +}() + +// privateKeyMarkerRe matches a private-key marker line, including the fragments a +// marker is reduced to when it is split across members. It marks the text a +// multi-member block carries into a key name or string value, so nothing that is +// block content is written back as structure. The quoted markers are the ones +// privateKeyRe delimits a block with. +var privateKeyMarkerRe = regexp.MustCompile(`-----BEGIN|-----END|PRIVATE KEY-----`) + +// privateKeyMaterialRe matches a run of candidate PEM body material: the base64 +// alphabet (which covers hex) at a length no short identifier or enum value +// reaches. A string value covered by a framing-spanning block is masked only +// when it holds a marker or a run pemBodyRun accepts, because a lazy pattern that +// runs from one member's BEGIN to another member's END also covers the members +// between them. Masking those unconditionally replaced structural values — a +// finding's severity, category, action or repo, all of which the review schema +// constrains to enums and patterns — so the review failed validation and was not +// posted, which is the #5705 outcome. +// +// The length floor alone does not separate body material from free text: a long +// word ("misconfiguration") and a file path ("internal/security/jsonsanitize") +// both reach 16 characters using only base64 characters, and a path adds a slash +// that reads as base64 padding or division. pemBodyRun therefore also requires +// the case and digit mix a base64 body carries and a word or a path does not. +// A single member can hold only one line of the body, so a body split into short +// or digit-free chunks is decided by the joined text of consecutive members +// instead (maskSpanBody). +var privateKeyMaterialRe = regexp.MustCompile(`[A-Za-z0-9+/]{16,}=*`) + +// pemBodyRunRe matches a maximal run of base64 characters inside a leaf. A body +// fragment can be embedded in surrounding text or line framing — "part: MIIEowIB", +// or a chunk stored together with the newline that ended the line — so the runs, +// not the whole value, are what join a body. A run of two or more characters +// joins the candidate body directly. A run of exactly one character is +// ambiguous — it is as likely to be free text as a body fragment — so it joins +// only while the candidate run is still empty or entirely single-character: +// a body stored one character per member is reconstructed and decided on its +// joined text (pemBodyJoined), while an isolated single-character free-text +// value between a quoted marker pair keeps its content. A body split so that +// one-character and longer chunks alternate is not reconstructed (a known +// residual); uniform chunks and whole body lines are. +var pemBodyRunRe = regexp.MustCompile(`[A-Za-z0-9+/]+=*`) + +// pemBodyRuns returns the base64 runs of a leaf's text concatenated, or nil when +// the leaf carries no run at all. Surrounding prose, punctuation and whitespace +// stay out of the joined text, while an embedded body fragment (a "part:" prefix, +// a trailing newline) is still collected instead of breaking the run (#5705). +func pemBodyRuns(text []byte) []byte { + runs := pemBodyRunRe.FindAll(text, -1) + if len(runs) == 0 { + return nil + } + var material []byte + for _, run := range runs { + material = append(material, run...) + } + return material +} + +// schemaConstrainedFields is the set of review schema keys whose values are +// structural (enums, file paths, repository identifiers) rather than key material. +// When a quoted marker pair covers a review result, these fields are protected +// from joining candidate PEM body runs so schema validation is not broken (#5705). +var schemaConstrainedFields = map[string]bool{ + "action": true, + "category": true, + "severity": true, + "file": true, + "repo": true, + "head_sha": true, + "id": true, + "dimension": true, + "reason": true, + "pr_number": true, + "line": true, + "actionable": true, +} + +// isSchemaConstrainedField reports whether a value under memberKey is a +// schema-constrained review field rather than candidate key material. +func isSchemaConstrainedField(memberKey, value string) bool { + if !schemaConstrainedFields[memberKey] { + return false + } + if textCarriesKeyMaterial([]byte(value)) { + return false + } + return true +} + +// jsonProvenance accumulates an order-preserving view of the decoded strings +// in a document so a private-key block that spans members can be detected after +// JSON decoding. The raw bytes are not usable for this: a member may encode a +// marker with \u escapes, and masking a sensitive member removes the BEGIN +// marker before the rewritten document is scanned. +type jsonProvenance struct { + decoded bytes.Buffer + ranges []recordSpan + // keys marks the entries in ranges that are object keys rather than string + // values. Key names are the document's structure, so a block that spans + // them is neutralized differently from a block that spans values. + keys []bool + memberKeys []string +} + +// decodedViewNormalizer normalizes decoded JSON text before it is matched for +// framing-spanning secrets, so a marker obfuscated with zero-width or bidi +// characters is normalized exactly as the per-leaf scan normalizes it. var decodedViewNormalizer = NewUnicodeNormalizer() +// addString appends one decoded key or string value to the view and records its +// byte range so a match can be mapped back to the leaves that carry it. +func (v *jsonProvenance) addString(s string, isKey bool, memberKey string) { + s = decodedViewNormalizer.Scan(s).Sanitized + start := v.decoded.Len() + v.decoded.WriteString(s) + v.decoded.WriteByte('\n') + v.ranges = append(v.ranges, recordSpan{start: start, end: v.decoded.Len() - 1}) + v.keys = append(v.keys, isKey) + v.memberKeys = append(v.memberKeys, memberKey) +} + +// privateKeySpans is the result of looking for private-key blocks that span the +// keys and values of one document. +type privateKeySpans struct { + // covered holds the indexes of the string values that carry part of a block + // spanning more than one leaf. Every covered value is replaced whole. + covered map[int]bool + // maskedKeys holds the indexes of the object keys whose own name carries + // block content — a marker, or a run of base64 body material — so the name + // is key material rather than structure. + maskedKeys map[int]bool + // localized counts the blocks that were mapped onto leaves. + localized int + // unmappable counts the blocks that no leaf range covers. + unmappable int +} + +// spanningPrivateKeys finds the private-key blocks in the decoded view that are +// not contained in a single key or value, and maps each one onto the leaves it +// covers. Containment is checked per match: a lazy pattern can start at one +// leaf's BEGIN and end at another leaf's END, and counting differences would let +// that match cancel out a complete leaf block. +// +// A block whose markers sit in different members is not proof that key material +// spans them — a review that quotes the header in one finding and the footer in +// another matches too — so only the members the match carries block content into +// are touched. The strings the match starts and ends in carry marker text and are +// masked unconditionally; a string value in between is masked when it holds a +// block marker or base64 body material (valueCarriesKeyMaterial) or when the +// joined text of its neighbours looks like a PEM body line (maskSpanBody). Those +// are the two shapes key material takes in a member, while the free text and enum +// values between a quoted marker pair stay readable, so a review result keeps its +// shape instead of failing schema validation and being dropped (#5705). An object +// key keeps its name unless the match starts or ends in it, or the name itself +// carries block content — a marker or a run of base64 body material: key names are +// the document's structure, and masking them would drop a required field such as a +// finding's severity, category or file and make the document fail schema +// validation. A key name that is itself a body line is not structure, though; it is +// key material, and leaving it writes the body back after the markers are masked, +// where the written-bytes rescan can no longer see the block (#5705). +func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { + spans := privateKeySpans{covered: map[int]bool{}, maskedKeys: map[int]bool{}} + for _, match := range privateKeyRe.FindAllIndex(v.decoded.Bytes(), -1) { + if v.leafContaining(match[0], match[1]) >= 0 { + // A block inside one leaf is that leaf's own scan. + continue + } + var hit []int + for i, r := range v.ranges { + if r.start < match[1] && match[0] < r.end { + hit = append(hit, i) + } + } + if len(hit) == 0 { + spans.unmappable++ + continue + } + spans.localized++ + // The middle members are decided together: a body split into chunks + // that are each shorter than the material floor is only recognizable + // once they are joined. + v.maskSpanBody(hit, &spans) + for pos, i := range hit { + // The match begins with a BEGIN marker and ends with an END marker, so + // the leaves it starts and ends in always carry marker text. They are + // masked even when the marker itself is split across two members and + // neither fragment matches privateKeyMarkerRe on its own. + atBoundary := pos == 0 || pos == len(hit)-1 + if v.keys[i] { + if atBoundary || v.valueCarriesKeyMaterial(i) { + spans.maskedKeys[i] = true + } + continue + } + if atBoundary || v.valueCarriesKeyMaterial(i) { + spans.covered[i] = true + } + } + } + return spans +} + +// maskSpanBody covers the string values between a framing-spanning block's +// boundary members when their joined text looks like PEM body material. A member +// holds one line of the body, and an agent can split the body so that every line +// is short or digit-free; a per-member test then accepts none of them and writes +// the body back after the markers are masked, where the written-bytes rescan can +// no longer see the block (#5705). Consecutive candidate segments are therefore +// decided together, whatever their individual length: the base64 runs embedded in +// a member are collected (pemBodyRuns), so surrounding prose, a "part:" prefix or +// the newline an agent kept with a body line does not break the run, and the +// joined text is what has to look like a body line. An object key never joins the +// run — a key is structure, +// and letting one into the joined text renames required schema keys (severity, +// category, file) — but it does not break the run either: the values on either +// side of a key are still consecutive body chunks once the key names are ignored, +// so a body stored in separate object members is reconstructed and masked. A +// member that carries a single base64 character joins only while the run is +// empty or entirely single-character, so a body stored one character per member +// is reconstructed while an isolated single-character value keeps its content; a +// body whose one-character and longer chunks interleave is a known residual and +// is not reconstructed. A key +// whose own name is a body line is masked on its own instead +// (spanningPrivateKeys). +func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { + var group []int + var joined []byte + // bodySeeded says the current run was restarted at a recognized body line. + bodySeeded := false + // allSingle says every member of the current run carried a one-character + // base64 run. A one-character value cannot be told from free text, so it + // only joins a run that is still empty or all-single: a run of many + // single-character values is a body stored one character per member and is + // decided on its joined text (pemBodyJoined), while an isolated + // single-character value following a body line stays free text (#5705). + allSingle := true + flush := func() { + if len(group) == 0 { + bodySeeded = false + return + } + if bodySeeded || pemBodyJoined(joined) { + for _, i := range group { + spans.covered[i] = true + } + } + group = group[:0] + joined = joined[:0] + bodySeeded = false + allSingle = true + } + for pos, i := range hit { + if pos == 0 || pos == len(hit)-1 { + flush() + continue + } + if v.keys[i] { + // The key is structure, not a body chunk: skip it without breaking + // the run (see the doc comment). + continue + } + valBytes := v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end] + if isSchemaConstrainedField(v.memberKeys[i], string(valBytes)) { + // A schema-constrained field (severity, category, file, etc.) is + // review structure, not key material: it never joins a candidate + // run and breaks any pending run (#5705). + flush() + continue + } + if v.valueCarriesKeyMaterial(i) { + // A value that is a complete body line on its own is covered by the + // main loop. It ends the preceding run — the structural values before + // it ("severity", "category", "file") must not be joined into a mask + // with it — but the run restarts at this leaf, so a short fragment + // that follows it ("AQAB", or "part: MIIEowIB") is still + // reconstructed and masked instead of surviving once the markers are + // gone (#5705). + spans.covered[i] = true + flush() + bodySeeded = true + } + material := pemBodyRuns(valBytes) + if len(material) == 0 { + flush() + continue + } + if len(material) == 1 && !allSingle { + // A one-character value must not extend a run that already holds a + // longer member, or a lone free-text character after a body line + // would be masked. Flush and restart so a body stored one character + // per member is still decided on its own joined text. + flush() + } + allSingle = allSingle && len(material) == 1 + group = append(group, i) + joined = append(joined, material...) + } + flush() +} + +// valueCarriesKeyMaterial reports whether the decoded key or string value at +// index i has to be replaced whole: it carries a block marker, or one of its runs +// holds base64 body material. +func (v *jsonProvenance) valueCarriesKeyMaterial(i int) bool { + return textCarriesKeyMaterial(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) +} + +// textCarriesKeyMaterial reports whether a decoded key or value's text carries a +// block marker or a run of base64 body material. A leaf outside those two shapes +// is free text or a schema-constrained token that a framing-spanning match only +// covers because a lazy pattern ran from one member's marker to another's, so it +// keeps its content. +func textCarriesKeyMaterial(text []byte) bool { + if privateKeyMarkerRe.Match(text) { + return true + } + // Every run is checked, not only the first. A value can prefix the body with + // a hash or an id (a "sha " note), and stopping at that first + // hex-only run wrote the body back after the markers had been masked, where + // the written-bytes rescan can no longer see the block (#5705). + for _, run := range privateKeyMaterialRe.FindAll(text, -1) { + if pemBodyRun(run) { + return true + } + } + return false +} + +// pemBodyRun reports whether run looks like a line of PEM body material rather +// than a hash, an id, a file path or a long word. A base64 body mixes upper case, +// lower case and digits and carries a character outside the hex range, while a +// hex run has no base64-only character, a word such as "misconfiguration" has +// neither an upper-case letter nor a digit, and a path such as +// "internal/security/jsonsanitize" adds a slash but no upper case or digit. +// Requiring the full mix keeps a hex-only run from masking a required field +// (head_sha, id, file) and loses no realistic body: a 64-character line, or a +// partial final line, almost always has all four. +func pemBodyRun(run []byte) bool { + var upper, lower, digit, base64Only bool + for _, b := range run { + switch { + case b >= 'a' && b <= 'z': + lower = true + base64Only = base64Only || b > 'f' + case b >= 'A' && b <= 'Z': + upper = true + base64Only = base64Only || b > 'F' + case b >= '0' && b <= '9': + digit = true + case b == '+' || b == '/' || b == '=': + base64Only = true + } + } + return upper && lower && digit && base64Only +} + +// pemBodyJoined reports whether the concatenated text of consecutive member +// segments looks like PEM body material. It is the check maskSpanBody applies to +// a body split across members: a chunk on its own may be shorter than the +// material floor or carry no digit, but the joined body reconstructs both. It +// still requires upper case, lower case and a base64-only character, which a hex +// SHA, a lowercase word, a path and free text do not have. +// +// A joined run is not automatically a body, though: consecutive schema values +// read as concatenated words — a finding's "critical", "ssrf" and "Makefile" join +// to "criticalssrfMakefile", which carries the case and base64 mix on its own. A +// body line is base64 of binary key material, so it scatters separate runs of +// upper-case letters through the text, while an enum or a filename the schema +// constrains is a word with a single upper-case run at most ("Makefile", +// "README", "Makefile2"). A digit alone does not separate the two: the trailing +// "2" of "Makefile2" is also a digit, and treating it as proof of key material +// masked a finding's severity, category and file. A joined run therefore needs a +// multi-letter upper-case run that is followed by lower case (hasMixedUpperRun) +// to be body material. A body split so that every such run fell into one segment +// that broke the run is not recognized +// here; such a body is still caught member by member when a member is a whole +// body line (pemBodyRun), and the alternative — treating every value between +// quoted markers as body — masked required schema fields and lost the review +// (#5705). +func pemBodyJoined(joined []byte) bool { + if len(joined) < 16 { + return false + } + var upper, lower, base64Only bool + for _, b := range joined { + switch { + case b >= 'a' && b <= 'z': + lower = true + base64Only = base64Only || b > 'f' + case b >= 'A' && b <= 'Z': + upper = true + base64Only = base64Only || b > 'F' + case b == '+' || b == '/' || b == '=': + base64Only = true + } + } + if !upper || !lower || !base64Only { + return false + } + return hasMixedUpperRun(joined) +} + +// hasMixedUpperRun reports whether text carries a run of at least two upper-case +// letters that is immediately followed by a lower-case letter. That is the shape +// base64 of binary material scatters through a line ("MIIEow", "QWERTYuiop"): +// capitals recur inside a word and are followed by lower case. A schema word or +// filename produces a single leading capital ("Makefile"), a trailing digit that +// resets the run ("Makefile2"), or an all-capitals token at the end of the word +// ("README"), and none of those is followed by lower case after a multi-letter +// run. A digit alone therefore no longer settles the question, which is what let +// "Makefile2" mask required schema fields (#5705). +func hasMixedUpperRun(text []byte) bool { + run := 0 + for _, b := range text { + switch { + case b >= 'A' && b <= 'Z': + run++ + case b >= 'a' && b <= 'z': + if run >= 2 { + return true + } + run = 0 + default: + run = 0 + } + } + return false +} + +// leafContaining returns the index of the leaf that fully contains [start, end), +// or -1 when no single leaf does. +func (v *jsonProvenance) leafContaining(start, end int) int { + for i, r := range v.ranges { + if r.start <= start && end <= r.end { + return i + } + } + return -1 +} + // preserveTrailingNewline drops the newline json.Encoder always appends and // restores the document's own trailing newline, so a rewrite never changes the // file's line framing. @@ -206,10 +691,10 @@ func redactJSONOutput(clean []byte, p *Pipeline) ([]byte, []Finding) { return clean, nil } for _, finding := range res.Findings { - // A private-key block that survives the leaf walk spans JSON framing, - // so it cannot be masked in place without breaking the document. + // A private-key block spanning values cannot be masked in place + // without breaking the surrounding JSON. if finding.Name == "private_key" { - return []byte(failClosedInvalidJSON), res.Findings + return []byte(failClosedSpansMembersJSON), res.Findings } } if res.Sanitized == "" || !json.Valid([]byte(res.Sanitized)) { @@ -224,11 +709,17 @@ func redactJSONOutput(clean []byte, p *Pipeline) ([]byte, []Finding) { // that framing, so the records it covers are replaced with valid fail-closed // markers and every other record is left as sanitized. func SanitizeJSONLines(content []byte, p *Pipeline) ([]byte, []Finding, error) { + // A private-key block that spans records has to be detected on the original + // framing: per-record masking of a sensitive member removes the BEGIN + // marker, after which neither the record scan nor the whole-stream scan can + // recognize the block. + content, crossRecordFindings := failClosedCrossRecordPrivateKeys(content) var ( out bytes.Buffer findings []Finding spans []recordSpan ) + findings = append(findings, crossRecordFindings...) for len(content) > 0 { line := content newline := bytes.IndexByte(content, '\n') @@ -296,7 +787,8 @@ func SanitizeJSONLines(content []byte, p *Pipeline) ([]byte, []Finding, error) { return rebuilt, findings, nil } // Every finding a single record could account for was handled above: a - // within-record whole-value secret is caught by SanitizeJSONDocument. What + // within-record whole-value secret is caught by SanitizeJSONDocument, and a + // private-key block crossing records by failClosedCrossRecordPrivateKeys. What // remains spans a record boundary. findings = append(findings, stream.Findings...) return failClosedRecordSpans(rebuilt, spans, stream), findings, nil @@ -308,6 +800,299 @@ type recordSpan struct { start, end int } +// failClosedCrossRecordPrivateKeys replaces the records that carry part of a +// private-key block crossing record boundaries with a valid marker. Match +// offsets come from a decoded view of the whole stream, so a marker written with +// \u escapes is still recognized, and every match maps back to the records that +// carry it. +func failClosedCrossRecordPrivateKeys(content []byte) ([]byte, []Finding) { + spans := jsonLineSpans(content) + if len(spans) == 0 { + return content, nil + } + covered, findings := newJSONLineView(content, spans).spanningRecordPrivateKeys() + if len(findings) == 0 { + return content, nil + } + var out bytes.Buffer + cursor := 0 + for i, span := range spans { + if !covered[i] { + continue + } + out.Write(content[cursor:span.start]) + out.WriteString(failClosedCrossRecordJSON) + cursor = span.end + } + out.Write(content[cursor:]) + return out.Bytes(), findings +} + +// jsonLineView is an order-preserving, decoded view of a JSONL stream: every +// object key and string value of every record, in document order, with a newline +// between records so nothing a record does not contain can join its neighbours. +// The raw bytes are not usable for cross-record matching: a record may encode a +// marker with \u escapes, and a BOM-prefixed record is not valid JSON until the +// mark is stripped. +type jsonLineView struct { + decoded bytes.Buffer + // records holds each record's range in the view, excluding the separator. + records []recordSpan + // leaves holds every decoded key and string value with the record it came + // from, so a match can be mapped back to whole records. + leaves []jsonLineLeaf +} + +// jsonLineLeaf is one decoded object key or string value in a jsonLineView. +type jsonLineLeaf struct { + record int + span recordSpan + key bool + memberKey string +} + +// newJSONLineView builds the decoded view of a stream whose non-empty records +// start at spans. A record that is one JSON document contributes its decoded +// leaves; anything else contributes its raw text as a single leaf, so a stream of +// PEM text lines is still matched line by line. +func newJSONLineView(content []byte, spans []recordSpan) *jsonLineView { + view := &jsonLineView{} + for i, span := range spans { + start := view.decoded.Len() + line := content[span.start:span.end] + if body := jsonRecordBody(line); json.Valid(body) { + prov := collectJSONLeaves(body) + view.decoded.Write(prov.decoded.Bytes()) + for j, r := range prov.ranges { + view.leaves = append(view.leaves, jsonLineLeaf{ + record: i, + span: recordSpan{start: start + r.start, end: start + r.end}, + key: prov.keys[j], + memberKey: prov.memberKeys[j], + }) + } + } else { + view.decoded.Write(line) + if end := view.decoded.Len(); end > start { + view.leaves = append(view.leaves, jsonLineLeaf{record: i, span: recordSpan{start: start, end: end}}) + } + } + view.records = append(view.records, recordSpan{start: start, end: view.decoded.Len()}) + view.decoded.WriteByte('\n') + } + return view +} + +// spanningRecordPrivateKeys finds the private-key blocks in the decoded view that +// cross a record boundary and reports which records must be replaced. +// +// A block whose markers sit in different records is not proof that key material +// spans them — a transcript that quotes the header in one record and the footer +// in another matches too — so only the records the block carries content into are +// replaced. The records the match starts and ends in always carry marker text and +// are replaced; a record in between is replaced only when its leaves hold a block +// marker or PEM body material (textCarriesKeyMaterial), or when the joined text +// of consecutive leaves looks like a PEM body line (maskMiddleRecordBody). Those +// are the two shapes key material takes, while free text and structural values +// between a quoted marker pair stay readable, so a transcript of work on this very +// code is not gutted. The single-document path localizes the same way (#5705). +func (v *jsonLineView) spanningRecordPrivateKeys() ([]bool, []Finding) { + covered := make([]bool, len(v.records)) + var findings []Finding + for _, match := range privateKeyRe.FindAllIndex(v.decoded.Bytes(), -1) { + var hit []int + for i, record := range v.records { + if record.start < match[1] && match[0] < record.end { + hit = append(hit, i) + } + } + // A block confined to one record is handled by that record's own + // sanitization. + if len(hit) < 2 { + continue + } + findings = append(findings, Finding{ + Scanner: "secret_redactor", + Name: "private_key", + Severity: "critical", + Detail: "Private key block spans records; removed the records carrying block content", + }) + covered[hit[0]] = true + covered[hit[len(hit)-1]] = true + v.maskMiddleRecordBody(hit, covered) + } + return covered, findings +} + +// maskMiddleRecordBody covers the records between a cross-record block's boundary +// records when their leaves carry key material. It is the record-level counterpart +// of maskSpanBody: consecutive candidate leaves are decided together, because a +// body split so that every line is short or digit-free is only recognizable once +// the lines are joined. A leaf joins a run at any length, since the joined text is +// what has to look like a body line, except that a single-character leaf joins +// only while the run is empty or entirely single-character (see maskSpanBody), so +// an isolated single-character value keeps its content and a body stored one +// character per record is still reconstructed. An object key never joins the run, since a key +// is structure rather than body, but it does not break the run either: a body +// stored in separate object members of one record is still reconstructed. Only the +// base64 runs embedded in a leaf join the run (pemBodyRuns), so line framing, a +// "part:" prefix and the punctuation around a fragment do not break it, while a +// leaf with no base64 run at all breaks it. A key whose own name is a body line +// carries key material, so its record is covered on its own. +func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { + first, last := hit[0], hit[len(hit)-1] + var group []int + var joined []byte + // bodySeeded says the current run was restarted at a recognized body line. + bodySeeded := false + // allSingle is the JSONL counterpart of the single-document tracker: a + // one-character value only joins a run that is empty or all-single, so a + // body stored one character per record is reconstructed while an isolated + // one-character value after a body line stays free text (#5705). + allSingle := true + flush := func() { + if len(group) == 0 { + bodySeeded = false + return + } + if bodySeeded || pemBodyJoined(joined) { + for _, i := range group { + covered[v.leaves[i].record] = true + } + } + group = group[:0] + joined = joined[:0] + bodySeeded = false + allSingle = true + } + for i, leaf := range v.leaves { + // The boundary records are already covered, and their leaves neither + // extend nor join a middle run. + if leaf.record <= first || leaf.record >= last { + flush() + continue + } + text := v.decoded.Bytes()[leaf.span.start:leaf.span.end] + if leaf.key { + // A key name is structure: it never joins the run, but it must not + // break one either, so a body split across object members of the + // same record is still reconstructed. A key name that is itself + // body material covers the record on its own. + if textCarriesKeyMaterial(text) { + covered[leaf.record] = true + flush() + } + continue + } + if isSchemaConstrainedField(leaf.memberKey, string(text)) { + // Schema-constrained review fields never join candidate runs and + // break any pending run (#5705). + flush() + continue + } + if textCarriesKeyMaterial(text) { + // A recognized body line covers its own record and ends the preceding + // run, so structural values before it are not joined into a mask with + // it. The run restarts at this leaf, so a short fragment that follows + // is reconstructed and its record masked with it (#5705). + covered[leaf.record] = true + flush() + bodySeeded = true + } + material := pemBodyRuns(text) + if len(material) == 0 { + flush() + continue + } + if len(material) == 1 && !allSingle { + // See maskSpanBody: a lone one-character value must not extend a run + // that already holds a longer member, or free text after a body line + // would be masked. + flush() + } + allSingle = allSingle && len(material) == 1 + group = append(group, i) + joined = append(joined, material...) + } + flush() +} + +// jsonRecordBody returns a JSONL record's JSON body: surrounding whitespace and a +// leading UTF-8 BOM removed. encoding/json rejects a BOM, so a record carrying one +// would otherwise be read as plain text and its \u-escaped markers never decoded, +// which hid a cross-record block and left the key body behind (#5705). +func jsonRecordBody(line []byte) []byte { + return bytes.TrimSpace(bytes.TrimPrefix(bytes.TrimSpace(line), utf8BOM)) +} + +// collectJSONLeaves walks doc and records every decoded object key and string +// value, in document order, in a view where a value split across members reads as +// one contiguous run of text. Each leaf's range in that view is kept so a match +// can be mapped back to the members that carry it. +func collectJSONLeaves(doc []byte) *jsonProvenance { + prov := &jsonProvenance{} + dec := json.NewDecoder(bytes.NewReader(doc)) + dec.UseNumber() + var walkValue func(memberKey string) + walkValue = func(memberKey string) { + tok, err := dec.Token() + if err != nil { + return + } + switch t := tok.(type) { + case json.Delim: + switch t { + case '{': + for dec.More() { + keyTok, err := dec.Token() + if err != nil { + return + } + key, ok := keyTok.(string) + if !ok { + return + } + prov.addString(key, true, "") + walkValue(key) + } + _, _ = dec.Token() // consume the closing delimiter + case '[': + for dec.More() { + walkValue("") + } + _, _ = dec.Token() // consume the closing delimiter + } + case string: + prov.addString(t, false, memberKey) + } + } + walkValue("") + return prov +} + +// jsonLineSpans returns the byte range of every non-empty line in content, +// excluding its trailing CR/LF framing. +func jsonLineSpans(content []byte) []recordSpan { + var spans []recordSpan + for start := 0; start < len(content); { + end := bytes.IndexByte(content[start:], '\n') + if end < 0 { + end = len(content) + } else { + end += start + } + lineEnd := end + if lineEnd > start && content[lineEnd-1] == '\r' { + lineEnd-- + } + if len(bytes.TrimSpace(content[start:lineEnd])) > 0 { + spans = append(spans, recordSpan{start: start, end: lineEnd}) + } + start = end + 1 + } + return spans +} + // failClosedRecordSpans replaces the records a whole-stream redaction changed // with a valid fail-closed marker. Records the redaction did not touch are // copied through unchanged, so two disjoint cross-record matches never discard @@ -401,13 +1186,16 @@ func lineBounded(data []byte, start, end int) bool { // rewriteJSONTokens walks every token in doc, sanitizes each object key and // scalar value, and renders a valid JSON document. Unlike map decoding it // keeps member order and duplicate keys, so a secret in an earlier, overwritten -// value is still found. -func rewriteJSONTokens(doc []byte, p *Pipeline) ([]byte, []Finding, error) { +// value is still found, and a secret spanning JSON framing stays visible in the +// rewritten bytes. String values that a framing-spanning private key carries key +// material into, and key names whose own text carries a block marker, are +// replaced whole, which is how such a block is neutralized member by member. +func rewriteJSONTokens(doc []byte, p *Pipeline, spans privateKeySpans) ([]byte, []Finding, error) { dec := json.NewDecoder(bytes.NewReader(doc)) dec.UseNumber() var ( buf bytes.Buffer - w = &jsonRewrite{pipeline: p} + w = &jsonRewrite{pipeline: p, spans: spans} ) if err := w.writeValue(dec, &buf, ""); err != nil { return nil, nil, fmt.Errorf("could not tokenize JSON: %w", err) @@ -418,13 +1206,34 @@ func rewriteJSONTokens(doc []byte, p *Pipeline) ([]byte, []Finding, error) { return buf.Bytes(), w.findings, nil } -// jsonRewrite is the state one token walk carries: the pipeline and the findings -// it has collected. +// jsonRewrite is the state one token walk carries: the pipeline, the findings it +// has collected, and the keys and string values a framing-spanning private key +// covers. type jsonRewrite struct { pipeline *Pipeline findings []Finding + spans privateKeySpans + // index counts the keys and string values already walked, in document + // order, so it lines up with the ranges in jsonProvenance. + index int +} + +// nextIndex advances the leaf cursor past the next key or string value and +// returns that leaf's index in the provenance view. +func (w *jsonRewrite) nextIndex() int { + i := w.index + w.index++ + return i } +// valueMasked reports whether the string value at index i carries part of a +// framing-spanning private key and must be replaced whole. +func (w *jsonRewrite) valueMasked(i int) bool { return w.spans.covered[i] } + +// keyMasked reports whether the object key at index i carries a block marker and +// must be replaced whole. +func (w *jsonRewrite) keyMasked(i int) bool { return w.spans.maskedKeys[i] } + // writeValue writes one JSON value to buf, sanitizing object keys and scalar // leaves as it goes. memberKey is the enclosing object key when the value is an // object member, so sensitive-key masking still applies; it is empty for array @@ -438,6 +1247,9 @@ func (w *jsonRewrite) writeValue(dec *json.Decoder, buf *bytes.Buffer, memberKey case json.Delim: return w.writeContainer(dec, buf, t) case string: + if w.valueMasked(w.nextIndex()) { + return writeJSONString(buf, privateKeyMask) + } sanitized, stringFindings := sanitizeJSONString(t, memberKey, w.pipeline) w.findings = append(w.findings, stringFindings...) return writeJSONString(buf, sanitized) @@ -487,7 +1299,13 @@ func (w *jsonRewrite) writeContainer(dec *json.Decoder, buf *bytes.Buffer, delim if !ok { return fmt.Errorf("JSON object key is %T, want string", keyTok) } + masked := w.keyMasked(w.nextIndex()) sanitizedKey, keyFindings := sanitizeJSONKey(key, w.pipeline) + if masked { + // The key name carried a private-key block marker, so it is + // block content rather than structure and cannot be kept. + sanitizedKey, keyFindings = privateKeyMask, nil + } w.findings = append(w.findings, keyFindings...) var rendered bytes.Buffer // The original key decides whether the value is sensitive: the mask diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index e1f8521808..3fab65188d 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -61,6 +61,282 @@ func TestSanitizeJSONDocument_DuplicateKeysSurviveRewrite(t *testing.T) { // before the BEGIN marker the pattern no longer matched the original key // material. Dropping the document was the other extreme — a review result lost // its verdict with it (#5705). +func TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersMasksCoveredMembers(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + // Reverse the members' sort order so a map re-encode would emit END before + // BEGIN and hide the block from a serialized scan. + doc := []byte(`{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `","verdict":"approve"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "a framing-spanning private key must produce a finding") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "BEGIN RSA") + assert.NotContains(t, string(out), "MIIEpAIBAAKCAQEA") + assert.NotContains(t, string(out), "output removed", "the document must be kept, not dropped") + assert.Contains(t, string(out), `"verdict":"approve"`, "a member outside the block must survive") + assert.Contains(t, string(out), `"z_begin":`, "key names are structure and must survive") + assert.Contains(t, string(out), `"m_body":`) + assert.Contains(t, string(out), `"a_end":`) +} + +// TestSanitizeJSONDocument_HexPrefixBeforeBodyMaterialMasked pins the regression +// a reviewer found: only the first material run in a value was examined, so a +// value that put a hash before the body ("sha ") returned false at +// the hex run. The markers were masked, the body was written back, and the +// written-bytes rescan could not catch it because the markers were gone (#5705). +func TestSanitizeJSONDocument_HexPrefixBeforeBodyMaterialMasked(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + body := "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcw" + doc := []byte(`{"a":"` + begin + `","b":"sha 0123456789abcdef0123 ` + body + `","c":"` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), body, "a body after a hex prefix must not survive") + assert.NotContains(t, string(out), "0123456789abcdef0123", "the member carrying the block is replaced whole") + + var result struct { + B string `json:"b"` + } + require.NoError(t, json.Unmarshal(out, &result)) + assert.Equal(t, privateKeyMask, result.B, "the member carrying the block is masked") +} + +// TestSanitizeJSONDocument_PathsAndProseBetweenMarkersStayReadable pins the other +// regression a reviewer found: a file path and a long word both reach the +// material floor, so a path such as "internal/security/jsonsanitize" or a word +// such as "misconfiguration" was masked as key material. A quoted marker pair +// carries no secret, and the review has to keep the values its schema requires +// (#5705). +func TestSanitizeJSONDocument_PathsAndProseBetweenMarkersStayReadable(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + path := "internal/security/jsonsanitize" + prose := "a misconfiguration here" + doc := []byte(`{"action":"comment","pr_number":12,"repo":"acme/widgets",` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","findings":[` + + `{"severity":"high","category":"logic-error","file":"a.go","description":"quotes the ` + begin + ` header"},` + + `{"severity":"medium","category":"missing-test","file":"` + path + `","description":"` + prose + `"},` + + `{"severity":"low","category":"stale-doc","file":"c.go","description":"quotes the ` + end + ` footer"}],"body":"summary"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "the cross-member marker pair is still reported") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----") + assertReviewResultSchemaValid(t, out) + + var result struct { + Findings []struct { + Severity string `json:"severity"` + File string `json:"file"` + Description string `json:"description"` + } `json:"findings"` + } + require.NoError(t, json.Unmarshal(out, &result), "the sanitized review must still decode: %s", out) + require.Len(t, result.Findings, 3) + assert.Equal(t, path, result.Findings[1].File, "a path is not PEM body material") + assert.Equal(t, prose, result.Findings[1].Description, "a long word is not PEM body material") + assert.Equal(t, "medium", result.Findings[1].Severity, "the structural enum keeps its value") + assert.Equal(t, privateKeyMask, result.Findings[0].Description, "the value carrying the header is masked") + assert.Equal(t, privateKeyMask, result.Findings[2].Description, "the value carrying the footer is masked") +} + +// TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview pins the +// regression a reviewer found: a review result that quotes the PEM header in one +// finding and the footer in another matches the lazy private-key pattern across +// members, but nothing is hidden and the review still has to be posted. Only the +// values that carry a marker or key material are masked, so the structural values +// the review schema constrains keep theirs — action, repo, severity and category +// included — and the sanitized document still validates against +// schemas/review-result.schema.json. Masking every covered value instead replaced +// those enums with the block marker, so validation failed and the review was not +// posted, which is the #5705 outcome (#5705). +func TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN" + " PRIVATE KEY-----" + end := "-----END" + " PRIVATE KEY-----" + doc := []byte(`{"action":"comment","pr_number":12,"repo":"acme/widgets",` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01",` + + `"findings":[` + + `{"severity":"high","category":"logic-error","file":"a.go","description":"quotes the ` + begin + ` header"},` + + `{"severity":"medium","category":"missing-test","file":"b.go","description":"a finding between the markers"},` + + `{"severity":"low","category":"stale-doc","file":"c.go","description":"quotes the ` + end + ` footer"},` + + `{"severity":"info","category":"doc-style","file":"d.go","description":"a finding after the block"}],"body":"summary"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "the cross-member marker pair is still reported") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "output removed", "the review must not be dropped whole") + assert.NotContains(t, string(out), "PRIVATE KEY-----") + + // The blocking requirement: the sanitized review still satisfies the schema + // the harness validates before post-review runs. + assertReviewResultSchemaValid(t, out) + + var result struct { + Action string `json:"action"` + PRNumber int `json:"pr_number"` + Repo string `json:"repo"` + Body string `json:"body"` + Findings []struct { + Severity string `json:"severity"` + Category string `json:"category"` + File string `json:"file"` + Description string `json:"description"` + } `json:"findings"` + } + require.NoError(t, json.Unmarshal(out, &result), "the sanitized review must still decode: %s", out) + assert.Equal(t, "comment", result.Action, "the action must survive") + assert.Equal(t, 12, result.PRNumber) + assert.Equal(t, "acme/widgets", result.Repo) + assert.Equal(t, "summary", result.Body, "a field outside the matched span keeps its content") + require.Len(t, result.Findings, 4, "every finding must survive") + + // Only the values that carry a marker are masked; the free text between the + // quoted markers is not key material and keeps its content. + assert.Equal(t, "high", result.Findings[0].Severity, "a structural enum before the match keeps its value") + assert.Equal(t, "a.go", result.Findings[0].File, "a value before the match keeps its content") + assert.Equal(t, privateKeyMask, result.Findings[0].Description, "the value carrying the marker is masked") + assert.Equal(t, "a finding between the markers", result.Findings[1].Description, + "free text between a quoted marker pair is not key material") + assert.Equal(t, privateKeyMask, result.Findings[2].Description, "the value carrying the footer is masked") + assert.Equal(t, "d.go", result.Findings[3].File, "a finding after the footer is outside the span") + assert.Equal(t, "a finding after the block", result.Findings[3].Description) +} + +// TestSanitizeJSONDocument_KeyMaterialInSpanKeepsStructuralEnums pins the other +// half of the rule: when the block really is split across members, the values +// carrying key material are masked, while the structural values the review schema +// constrains keep theirs so the review can still be posted (#5705). +func TestSanitizeJSONDocument_KeyMaterialInSpanKeepsStructuralEnums(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"action":"request-changes","pr_number":12,"repo":"acme/widgets",` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","findings":[` + + `{"severity":"high","category":"secret-exposure","file":"a.go","description":"leaked ` + begin + `"},` + + `{"severity":"high","category":"secret-exposure","file":"b.go","description":"MIIEpAIBAAKCAQEA0123456789abcdef"},` + + `{"severity":"high","category":"secret-exposure","file":"c.go","description":"and ` + end + `"}],"body":"remove it"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "output removed", "the review must not be dropped whole") + assert.NotContains(t, string(out), "PRIVATE KEY-----") + assert.NotContains(t, string(out), "MIIEpAIBAAKCAQEA", "the key material must not survive") + assertReviewResultSchemaValid(t, out) + + var result struct { + Findings []struct { + Severity string `json:"severity"` + Category string `json:"category"` + File string `json:"file"` + Description string `json:"description"` + } `json:"findings"` + } + require.NoError(t, json.Unmarshal(out, &result)) + require.Len(t, result.Findings, 3) + for i, finding := range result.Findings { + assert.Equal(t, "high", finding.Severity, "finding %d must keep its severity enum", i) + assert.Equal(t, "secret-exposure", finding.Category, "finding %d must keep its category enum", i) + assert.NotEmpty(t, finding.File, "finding %d must keep its file", i) + assert.NotEmpty(t, finding.Description, "finding %d must keep its description", i) + } +} + +// TestSanitizeJSONDocument_MarkerSplitAcrossMembersMasked pins that a marker +// written in pieces does not survive: the leaves the match starts and ends in are +// always masked, and a value carrying only a marker fragment is masked too, so no +// piece of the block header or footer is written back (#5705). +func TestSanitizeJSONDocument_MarkerSplitAcrossMembersMasked(t *testing.T) { + p := OutputPipeline() + doc := []byte(`["-----BEGIN"," RSA PRIVATE KEY-----","MIIEb2R5","-----END"," RSA PRIVATE KEY-----"]`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "-----BEGIN") + assert.NotContains(t, string(out), "-----END") + assert.NotContains(t, string(out), "PRIVATE KEY-----") +} + +// TestSanitizeJSONDocument_SchemaFieldsBetweenQuotedMarkersKept pins the other +// side of the joined-run rule: the values between a quoted header and footer are +// not body material just because they are consecutive. A finding's severity, +// category and file join into "criticalssrfMakefile", which carries the case and +// base64 mix a body line has, and masking them failed the review schema and lost +// the review — the outcome this change exists to prevent (#5705). +func TestSanitizeJSONDocument_SchemaFieldsBetweenQuotedMarkersKept(t *testing.T) { + p := OutputPipeline() + // A filename is a word, not key material: a trailing digit ("Makefile2") or + // an all-capitals name ("README") must not tip the joined run into a mask + // that drops severity, category and file and fails schema validation + // (#5705). + for _, file := range []string{"Makefile", "Makefile2", "README", "LICENSE"} { + t.Run(file, func(t *testing.T) { + doc := []byte(`{"action":"comment","repo":"acme/widgets","pr_number":12,` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","body":"quotes a key",` + + `"findings":[` + + `{"severity":"high","category":"logic-error","file":"a.go","description":"quotes the ` + pemBegin + ` header"},` + + `{"severity":"critical","category":"ssrf","file":"` + file + `","description":"quotes the ` + pemEnd + ` footer"}]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----", "the markers themselves are masked") + assert.Contains(t, string(out), `"severity":"critical"`, "a schema value is not body material") + assert.Contains(t, string(out), `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, string(out), `"file":"`+file+`"`, "a schema value is not body material") + assertReviewResultSchemaValid(t, out) + }) + } +} + +// TestSanitizeJSONDocument_SchemaFieldsInReversedOrderKept pins that schema +// fields appearing in any key order (for example, "file" before "category" and +// "severity") are recognized as structure rather than candidate key material, +// so an all-caps filename like README before an enum like ssrf does not join into +// an apparent mixed-upper run (#5705). +func TestSanitizeJSONDocument_SchemaFieldsInReversedOrderKept(t *testing.T) { + p := OutputPipeline() + for _, file := range []string{"README", "LICENSE", "Makefile", "Makefile2"} { + t.Run(file, func(t *testing.T) { + doc := []byte(`{"action":"comment","repo":"acme/widgets","pr_number":12,` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","body":"quotes a key",` + + `"findings":[` + + `{"description":"quotes the ` + pemBegin + ` header","file":"a.go","category":"logic-error","severity":"high"},` + + `{"file":"` + file + `","category":"ssrf","severity":"critical","description":"quotes the ` + pemEnd + ` footer"}]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----", "the markers themselves are masked") + assert.Contains(t, string(out), `"severity":"critical"`, "a schema value is not body material") + assert.Contains(t, string(out), `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, string(out), `"file":"`+file+`"`, "a schema value is not body material") + assertReviewResultSchemaValid(t, out) + }) + } +} + +// TestSanitizeJSONDocument_ShortBodyChunksMasked pins that a body split into +// chunks shorter than the material floor is still masked. Each chunk is too short +// for the per-value test, so the run is decided on its joined text and every +// contributing chunk is covered; a length floor per chunk let the body survive +// once the boundary markers were masked (#5705). func TestSanitizeJSONDocument_ShortBodyChunksMasked(t *testing.T) { p := OutputPipeline() chunks := []string{"MII", "Eow", "IB", "AAK", "CAQ", "EA"} @@ -122,6 +398,70 @@ func TestSanitizeJSONDocument_ChunkedBodyBetweenMarkersMasked(t *testing.T) { // inside a quoted marker span is not treated as key material. A commit SHA or a // finding id is schema-constrained (head_sha, id), and a PEM body is base64, so a // hex-only run is far more likely a hash than a PEM line (#5705). +func TestSanitizeJSONDocument_HexValuesInSpanKeepTheirContent(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"action":"comment","pr_number":12,"repo":"acme/widgets","findings":[` + + `{"severity":"high","category":"logic-error","file":"a.go","id":"f_0123456789abcdef0123456789abcdef","description":"quotes the ` + begin + ` header"},` + + `{"severity":"low","category":"doc-style","file":"b.go","id":"f_0123456789abcdef0123456789abcdef","description":"and the ` + end + ` footer"}],` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","body":"summary"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.Contains(t, string(out), `"head_sha":"abcdef0123456789abcdef0123456789abcdef01"`, + "a commit SHA is not PEM body material") + assert.Contains(t, string(out), `"id":"f_0123456789abcdef0123456789abcdef"`, + "a finding id is not PEM body material") + assert.NotContains(t, string(out), "PRIVATE KEY-----") +} + +// TestSanitizeJSONDocument_KeyNameCarryingMarkerIsMasked pins the other half of +// the key rule: a key name is structure and keeps its name, unless the name itself +// carries a block marker. Then the name is block content and cannot be written +// back, while a sibling key between the markers still keeps its name (#5705). +func TestSanitizeJSONDocument_KeyNameCarryingMarkerIsMasked(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"` + begin + `":"x","severity":"high","` + end + `":"y"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "BEGIN RSA") + assert.NotContains(t, string(out), "END RSA") + assert.Contains(t, string(out), `"severity":`, "a key name between the markers keeps its name") +} + +// TestJSONProvenance_KeysAreStructure pins that the decoded view records which +// leaves are object keys, that a spanning block only covers string values, and +// that a value between the markers is covered only when it carries key material, +// so the rewrite never renames a key unless its own text carries a marker. +func TestJSONProvenance_KeysAreStructure(t *testing.T) { + begin := pemBegin + end := pemEnd + doc := []byte(`{"severity":"` + begin + `","category":"MIIEpAIBAAKCAQEA0123456789abcdef","body":"x","file":"` + end + `"}`) + + prov := collectJSONLeaves(doc) + require.Equal(t, len(prov.ranges), len(prov.keys), "every recorded leaf must carry a kind") + spans := prov.spanningPrivateKeys() + require.Equal(t, 1, spans.localized) + assert.Empty(t, spans.maskedKeys, "no key name carries a marker") + require.Len(t, spans.covered, 3, "the marker and the key-material values are covered") + for i := range spans.covered { + assert.False(t, prov.keys[i], "only string values are covered") + } + assert.False(t, spans.covered[5], "free text between the markers is not key material") +} + +// TestSanitizeJSONDocument_BodyLineAsKeyBetweenMarkersMasked pins that a key name +// which is itself a body line is key material, not structure. Once the boundary +// markers are masked the written-bytes rescan can no longer see the block, so a +// body kept in a key name would be written back unmasked (#5705). func TestSanitizeJSONDocument_BodyLineAsKeyBetweenMarkersMasked(t *testing.T) { p := OutputPipeline() begin := pemBegin @@ -142,6 +482,27 @@ func TestSanitizeJSONDocument_BodyLineAsKeyBetweenMarkersMasked(t *testing.T) { // side of the same rule: a structural key between the markers keeps its name even // when the values around it carry body material. Letting a key join the // joined-run test would rename required schema keys and drop the review (#5705). +func TestSanitizeJSONDocument_StructuralKeysKeepNamesNextToMaterial(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"` + begin + `":"x","severity":"high","category":"logic-error",` + + `"body":"MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez","` + end + `":"y"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + for _, key := range []string{`"severity":`, `"category":`, `"body":`} { + assert.Contains(t, string(out), key, "a structural key keeps its name") + } + assert.NotContains(t, string(out), "x7Qz9restOfTheBodyWq1Ez", "the body material is masked") +} + +// TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed pins that a +// document with no leaf findings is still scanned in its written form. A +// runtime secret spanning two member boundaries is visible only in the raw +// bytes, and the previous no-findings path returned those bytes untouched. func TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed(t *testing.T) { resetRuntimeSecrets() t.Cleanup(resetRuntimeSecrets) @@ -162,6 +523,25 @@ func TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed(t *testing // secret and a framing-spanning private key in the same document are both // handled: the rewrite keeps member order, and the members carrying the block // are masked while the rest of the document survives. +func TestSanitizeJSONDocument_CrossMemberPrivateKeyWithLeafSecret(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `",` + + `"token":"ghp_FAKEtesttoken000000000000000000000000","verdict":"approve"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + assert.NotContains(t, string(out), "PRIVATE KEY-----") + assert.Contains(t, string(out), `"verdict":"approve"`, "a member outside the block must survive") +} + +// TestSanitizeJSONDocument_DuplicateKeySanitizedKeyCollision pins that a +// sanitized key never steals the name of an existing clean member, and that +// intentional duplicate keys still survive. func TestSanitizeJSONDocument_DuplicateKeySanitizedKeyCollision(t *testing.T) { resetRuntimeSecrets() t.Cleanup(resetRuntimeSecrets) @@ -385,8 +765,9 @@ func TestOutputRemoval(t *testing.T) { }{ "invalid json": {failClosedInvalidJSON + "\n", "redaction would invalidate JSON", true}, "cross-record": {failClosedCrossRecordJSON, "a secret spanned multiple records", true}, + "spans members": {failClosedSpansMembersJSON, "a private key block spans JSON framing", true}, "unwritable": {FailClosedUnwritableJSON, "it could not be redacted", true}, - "bom prefixed": {"\ufeff" + failClosedCrossRecordJSON, "a secret spanned multiple records", true}, + "bom prefixed": {"\ufeff" + failClosedSpansMembersJSON, "a private key block spans JSON framing", true}, "bom and space": {"\ufeff " + failClosedInvalidJSON + "\r\n", "redaction would invalidate JSON", true}, "ordinary doc": {`{"error":"not a removal marker"}`, "", false}, "not json": {"plain prose", "", false}, @@ -408,10 +789,10 @@ func TestOutputRecordRemovals(t *testing.T) { stream := []byte( `{"event":"clean"}` + "\n" + failClosedCrossRecordJSON + "\r\n" + - failClosedInvalidJSON + "\n" + - failClosedCrossRecordJSON + "\n") + failClosedCrossRecordJSON + "\n" + + failClosedSpansMembersJSON + "\n") assert.Equal(t, - []string{"a secret spanned multiple records", "redaction would invalidate JSON"}, + []string{"a secret spanned multiple records", "a private key block spans JSON framing"}, OutputRecordRemovals(stream)) assert.Empty(t, OutputRecordRemovals([]byte(`{"event":"clean"}`+"\n"))) } @@ -429,6 +810,24 @@ func TestOutputRecordRemovals_BOMFirstRecord(t *testing.T) { // TestJSONProvenance_UnmappableBlock pins the defensive fallback: a block that no // recorded leaf range covers is reported as unmappable so the caller fails // closed instead of writing bytes that may still carry it. +func TestJSONProvenance_UnmappableBlock(t *testing.T) { + begin := pemBegin + end := pemEnd + v := &jsonProvenance{} + v.decoded.WriteString(begin + "\n" + "MIIEkeymaterial" + "\n" + end + "\n") + // One empty string value, which can never overlap a match. + v.ranges = []recordSpan{{start: 0, end: 0}} + v.keys = []bool{false} + + spans := v.spanningPrivateKeys() + assert.Equal(t, 1, spans.unmappable) + assert.Zero(t, spans.localized) + assert.Empty(t, spans.covered) + assert.Empty(t, spans.maskedKeys) +} + +// TestSanitizeJSONDocument_AlreadyMaskedValueNotRemasked pins that rescanning a +// document leaves an existing mask placeholder intact. func TestSanitizeJSONDocument_AlreadyMaskedValueNotRemasked(t *testing.T) { p := OutputPipeline() doc := []byte(`{"body":"Guard against null values with token_usage = metrics.get(\"token_usage\") or {}"}`) @@ -555,6 +954,99 @@ func TestSanitizeJSONLines_RepeatedRecordsFailsClosed(t *testing.T) { // block content, so a record that also appears after the block must not be // dropped from the match and its copy outside the match must not be attributed to // it. +func TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte( + "[\"" + begin + "\"]\n" + + "{\"value\":\"middle\"}\n" + + "[\"" + end + "\"]\n" + + "{\"value\":\"middle\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), begin) + assert.NotContains(t, string(out), end) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, i := range []int{0, 2} { + assert.True(t, json.Valid([]byte(lines[i])), "each replaced record must stay valid JSON: %s", lines[i]) + assert.Contains(t, lines[i], "output removed") + } + assert.Equal(t, `{"value":"middle"}`, lines[1], "a clean record inside the match must survive") + assert.Equal(t, `{"value":"middle"}`, lines[3], "its copy outside the match must survive too") +} + +// TestSanitizeJSONLines_QuotedMarkersKeepCleanRecords pins that a transcript that +// quotes a PEM header in one record and the footer in a later one loses only the +// records that carry block content. Replacing every record the lazy match touches +// gutted a transcript of work on this code — grep output and tool results quoting +// the markers — which is the #5705 outcome the single-document path avoids +// (6dca72790, 078ffa2, b0ab1e2). +func TestSanitizeJSONLines_QuotedMarkersKeepCleanRecords(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte( + "{\"event\":\"quote\",\"text\":\"" + begin + "\"}\n" + + "{\"event\":\"normal record one\"}\n" + + "{\"event\":\"normal record two\"}\n" + + "{\"event\":\"quote\",\"text\":\"" + end + "\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), begin) + assert.NotContains(t, string(out), end) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, i := range []int{0, 3} { + assert.True(t, json.Valid([]byte(lines[i])), "each replaced record must stay valid JSON: %s", lines[i]) + assert.Contains(t, lines[i], "output removed") + } + assert.Equal(t, `{"event":"normal record one"}`, lines[1], "a record carrying no block content must survive") + assert.Equal(t, `{"event":"normal record two"}`, lines[2], "a record carrying no block content must survive") +} + +// TestSanitizeJSONLines_BodyLineAsKeyBetweenMarkersCovered pins the record-level +// half of the body-in-key rule: a middle record whose key name is itself a body +// line carries key material and must be replaced, while a clean record between the +// markers still survives (#5705). +func TestSanitizeJSONLines_BodyLineAsKeyBetweenMarkersCovered(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + const body = "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + content := []byte( + "{\"" + begin + "\":1}\n" + + "{\"event\":\"normal record\"}\n" + + "{\"" + body + "\":2}\n" + + "{\"" + end + "\":3}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), body, "a body line in a key name is key material") + assert.NotContains(t, string(out), begin) + assert.NotContains(t, string(out), end) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, i := range []int{0, 2, 3} { + assert.True(t, json.Valid([]byte(lines[i])), "each replaced record must stay valid JSON: %s", lines[i]) + assert.Contains(t, lines[i], "output removed") + } + assert.Equal(t, `{"event":"normal record"}`, lines[1], "a record carrying no block content must survive") +} + +// TestSanitizeJSONLines_BodySplitAcrossRecordsCovered pins the other half: a +// middle record is kept only when it really is clean. A body split so that every +// record holds one short, digit-free chunk is still body material once the chunks +// are joined, and every record carrying it must be replaced. func TestSanitizeJSONLines_BodySplitAcrossRecordsCovered(t *testing.T) { p := OutputPipeline() begin := pemBegin @@ -583,6 +1075,23 @@ func TestSanitizeJSONLines_BodySplitAcrossRecordsCovered(t *testing.T) { // sensitive-named member holding only the BEGIN marker is masked as a // json_field, which would leave the body and END marker behind; the block is // detected in the original framing and its members are masked. +func TestSanitizeJSONDocument_SensitiveBeginMemberMasksBlock(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"key_start":"` + begin + `","payload":"MIIEpAIBAAKCAQEA0123456789abcdef","tail":"` + end + `","verdict":"approve"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEpAIBAAKCAQEA", "the key body must not survive") + assert.NotContains(t, string(out), "END RSA") + assert.Contains(t, string(out), `"verdict":"approve"`, "a member outside the block must survive") +} + +// TestSanitizeJSONLines_CleanDuplicateKeyRecordPreserved pins that a clean +// duplicate-key record survives while another record is rewritten. func TestSanitizeJSONLines_CleanDuplicateKeyRecordPreserved(t *testing.T) { p := OutputPipeline() content := []byte("{\"a\":1,\"a\":2}\n{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\n") @@ -723,6 +1232,134 @@ func TestLineBounded(t *testing.T) { // TestSanitizeJSONDocument_LeafAndSplitPrivateKeysMasked pins that a handled // leaf block does not exempt a second, framing-spanning block in the same // document, and that neither leaves key material behind. +func TestSanitizeJSONDocument_LeafAndSplitPrivateKeysMasked(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"note":"` + begin + `\nMIIEleafkeymaterial\n` + end + `",` + + `"key_start":"` + begin + `","payload":"MIIEspanningkeymaterial0","tail":"` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") + assert.NotContains(t, string(out), "MIIEleafkeymaterial") +} + +// TestSanitizeJSONLines_SensitiveBeginRecordFailsClosed pins that a +// cross-record private key is detected on the original stream, before masking +// a sensitive-named member removes its BEGIN marker. +func TestSanitizeJSONLines_SensitiveBeginRecordFailsClosed(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + records := []string{ + "{\"key_start\":\"" + begin + "\"}", + "{\"payload\":\"MIIEspanningkeymaterial0\"}", + "{\"tail\":\"" + end + "\"}", + } + for name, tc := range map[string]struct { + sep string + trailer string + }{ + "lf": {sep: "\n", trailer: "\n"}, + "crlf": {sep: "\r\n", trailer: "\r\n"}, + "no trailing newline": {sep: "\n", trailer: ""}, + } { + t.Run(name, func(t *testing.T) { + content := []byte(strings.Join(records, tc.sep) + tc.trailer) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") + assert.NotContains(t, string(out), "END RSA") + + lines := strings.Split(strings.TrimSuffix(strings.TrimSuffix(string(out), "\n"), "\r"), tc.sep) + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } + }) + } +} + +// TestSanitizeJSONDocument_EscapedLeafBlockDoesNotExemptSplitBlock pins that an +// escaped-marker leaf block cannot stand in for a separate block that spans +// members: the escaped block is visible only after JSON decoding, so raw-byte +// and decoded finding counts are not comparable. +func TestSanitizeJSONDocument_EscapedLeafBlockDoesNotExemptSplitBlock(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + escapedBegin := `\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + doc := []byte(`{"note":"` + escapedBegin + `\nMIIEleafkeymaterial\n` + end + `",` + + `"key_start":"` + begin + `","payload":"MIIEspanningkeymaterial0","tail":"` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0", "the spanning block must not survive") + assert.NotContains(t, string(out), "MIIEleafkeymaterial", "the escaped leaf block must be redacted") +} + +// TestSanitizeJSONLines_EscapedBeginRecordFailsClosed pins that a cross-record +// block is recognized even when its BEGIN marker is written with \u escapes in +// the original record bytes. +func TestSanitizeJSONLines_EscapedBeginRecordFailsClosed(t *testing.T) { + p := OutputPipeline() + end := pemEnd + content := []byte(`{"key_start":"\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + `"}` + "\n" + + `{"payload":"MIIEspanningkeymaterial0"}` + "\n" + + `{"tail":"` + end + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") + assert.NotContains(t, string(out), "END RSA") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONLines_BOMRecordEscapedBeginFailsClosed pins that a BOM on the +// first record does not hide a cross-record block. encoding/json rejects the mark, +// so the record was read as plain text, its \u-escaped BEGIN marker was never +// decoded, and the key body survived — bypassing the escaped-marker fix from +// bb35a97f6 (#5705). +func TestSanitizeJSONLines_BOMRecordEscapedBeginFailsClosed(t *testing.T) { + p := OutputPipeline() + bom := "\ufeff" + end := pemEnd + content := []byte(bom + `{"a":"\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + `"}` + "\n" + + `{"b":"MIIEspanningkeymaterial0"}` + "\n" + + `{"c":"` + end + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") + assert.NotContains(t, string(out), "END RSA") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONLines_CleanBOMRecordPreserved pins that a BOM-prefixed record is +// routed through the structural path and keeps its encoding mark, exactly as a +// BOM-prefixed single document does. func TestSanitizeJSONLines_CleanBOMRecordPreserved(t *testing.T) { p := OutputPipeline() bom := []byte("\ufeff") @@ -758,6 +1395,22 @@ func TestSanitizeJSONDocument_CRLFNoStrayCarriageReturn(t *testing.T) { // TestSanitizeJSONDocument_EscapedMarkersAcrossMembersMasked pins that a block // spanning members is detected even when no leaf produces a finding and the // markers are \u-escaped in the raw bytes. +func TestSanitizeJSONDocument_EscapedMarkersAcrossMembersMasked(t *testing.T) { + p := OutputPipeline() + end := pemEnd + doc := []byte(`["\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + + `","MIIEspanningkeymaterial0","` + end + `"]`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") +} + +// TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersMasked pins that the +// decoded view applies the same Unicode normalization as the leaf scan, so a +// marker obfuscated with a zero-width character cannot hide a spanning block. func TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersMasked(t *testing.T) { p := OutputPipeline() end := pemEnd @@ -776,6 +1429,22 @@ func TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersMasked(t *testing.T) // that a lazy match starting at one leaf's BEGIN and ending at another leaf's // END cannot cancel out a complete leaf block: containment is judged per match, // so both blocks are neutralized. +func TestSanitizeJSONDocument_UnterminatedBeginBeforeCompleteBlockMasksBoth(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"a":"` + begin + `\nMIIEfirstkeymaterial","b":"` + begin + `\nZZZZZZZZ\n` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEfirstkeymaterial", "the unterminated block must not survive") + assert.NotContains(t, string(out), "ZZZZZZZZ", "the complete block must not survive") +} + +// TestSanitizeJSONDocument_LeavesUnsupportedInputAlone pins the fallback +// contract for documents the structural path cannot handle. func TestSanitizeJSONDocument_LeavesUnsupportedInputAlone(t *testing.T) { p := OutputPipeline() for name, doc := range map[string]string{ @@ -970,7 +1639,9 @@ func TestSanitizeJSONDocument_DuplicateKeyWithSecretKey(t *testing.T) { // of the structural fields, additionalProperties false, and the required members // — instead of a hand-maintained mirror that silently drifts when the upstream // enum changes. The upstream repo, commit and path are recorded in -// testdata/review-result.schema.pin; re-vendor the schema together with that pin. +// testdata/review-result.schema.pin; re-vendor the schema together with that pin, +// and scripts/check-review-schema-pin.sh reports when this copy drifts from +// upstream at the pinned commit. const reviewResultSchemaPath = "testdata/review-result.schema.json" // reviewResultSchema is the subset of the vendored schema the checks below use. @@ -1085,44 +1756,6 @@ func assertReviewResultSchemaValid(t *testing.T, doc []byte) { } } -// TestSanitizeJSONDocument_ReviewResultStaysSchemaValid pins that a review -// result survives the structural rewrite with the shape the harness validates: a -// redaction must never rename a member, drop a required one, or rewrite an -// enum-valued field, or the harness rejects the result and the review is never -// posted (#5705). -func TestSanitizeJSONDocument_ReviewResultStaysSchemaValid(t *testing.T) { - p := OutputPipeline() - doc := []byte(`{ - "action": "request-changes", - "pr_number": 9699, - "repo": "fullsend-ai/fullsend", - "head_sha": "a7bfefc244c85ad55517f073cfe7af15d483c2b1", - "body": "Two findings.", - "findings": [ - { - "severity": "high", - "category": "secret-exposure", - "file": "internal/cli/run.go", - "line": 42, - "description": "The token ghp_FAKEtesttoken000000000000000000000000 is written back." - }, - { - "severity": "low", - "category": "doc-style", - "file": "docs/guides/user/run-artifacts-and-private-data.md", - "description": "The guide does not mention the marker." - } - ] - }`) - - out, findings, err := SanitizeJSONDocument(doc, p) - require.NoError(t, err) - require.NotEmpty(t, findings, "the token must be reported") - assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) - assert.NotContains(t, string(out), "ghp_FAKEtesttoken") - assertReviewResultSchemaValid(t, out) -} - // TestSanitizeJSONDocument_KeepsBOM pins that a document carrying a UTF-8 BOM is // sanitized structurally and keeps its encoding mark. The BOM is not JSON // whitespace, so without this the document falls through to the plain-text scan, @@ -1315,6 +1948,62 @@ func TestSanitizeJSONDocument_BodyChunksWithLineFramingMasked(t *testing.T) { // half of the joined-run rule: a middle record whose values are schema fields // joins into "criticalssrfMakefile" and must keep its content, so the review the // transcript describes is not discarded (#5705). +func TestSanitizeJSONLines_SchemaFieldsBetweenQuotedMarkersKept(t *testing.T) { + p := OutputPipeline() + for _, file := range []string{"Makefile", "Makefile2", "README", "LICENSE"} { + t.Run(file, func(t *testing.T) { + content := []byte( + `{"note":"quotes the ` + pemBegin + ` header"}` + "\n" + + `{"severity":"critical","category":"ssrf","file":"` + file + `"}` + "\n" + + `{"note":"quotes the ` + pemEnd + ` footer"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + assert.Contains(t, lines[1], `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, lines[1], `"file":"`+file+`"`, "a schema value is not body material") + assert.NotContains(t, lines[0], "PRIVATE KEY-----") + assert.NotContains(t, lines[2], "PRIVATE KEY-----") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "every record must stay valid JSON: %s", line) + } + }) + } +} + +// TestSanitizeJSONLines_SchemaFieldsInReversedOrderKept is the JSONL record +// counterpart of TestSanitizeJSONDocument_SchemaFieldsInReversedOrderKept. +func TestSanitizeJSONLines_SchemaFieldsInReversedOrderKept(t *testing.T) { + p := OutputPipeline() + for _, file := range []string{"README", "LICENSE", "Makefile", "Makefile2"} { + t.Run(file, func(t *testing.T) { + content := []byte( + `{"note":"quotes the ` + pemBegin + ` header"}` + "\n" + + `{"file":"` + file + `","category":"ssrf","severity":"critical"}` + "\n" + + `{"note":"quotes the ` + pemEnd + ` footer"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + assert.Contains(t, lines[1], `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, lines[1], `"file":"`+file+`"`, "a schema value is not body material") + assert.Contains(t, lines[1], `"severity":"critical"`, "a schema value is not body material") + assert.NotContains(t, lines[0], "PRIVATE KEY-----") + assert.NotContains(t, lines[2], "PRIVATE KEY-----") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "every record must stay valid JSON: %s", line) + } + }) + } +} + +// TestSanitizeJSONLines_ShortBodyChunksCovered pins that a middle record holding +// a body in chunks shorter than the material floor is replaced, not written back +// with its body intact (#5705). func TestSanitizeJSONLines_ShortBodyChunksCovered(t *testing.T) { p := OutputPipeline() content := []byte(