diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index de2e46ffd0..3bf3084f8e 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -634,6 +634,68 @@ The post-run output scan skips `/skills/` and origins and warnings are documented in [Configuring with Skills § The persona list file](../guides/user/customizing-with-skills.md#the-persona-list-file). +### The post-run output scan + +`scanOutputFiles` runs the output pipeline (Unicode normalization, then secret +redaction) over every file under the run directory (`/`, including +`iteration-N/` transcripts) except the skips above, any directory named +`security` (which holds `findings.jsonl`), and the telemetry JSONL. + +A file whose content is one JSON document — or two or more newline-delimited +ones — is sanitized structurally, so redaction never changes its syntax. The +document is rewritten by a token-preserving walk rather than decoded into a map +and re-encoded: member order and duplicate keys survive, so an earlier value that +map decoding would drop is still scanned. Each object key and string value is +scanned on its own; a value whose member name marks it sensitive (key, token, +secret, password, credential, auth) is masked even when the value matches no +pattern, and a sanitized key name that would collide with a different member is +disambiguated (`_`). A leading UTF-8 BOM is stripped before the walk and +restored on write, and a clean document comes back byte for byte. + +After the rewrite the serialized bytes are scanned once more, but only for +whole-value secrets — registered runtime values and private-key blocks — because +those are the only matches a leaf scan cannot see once a member value is masked. +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 +boundaries. Markers look like `{"error":"output removed because …"}` and are +logged as findings in `security/findings.jsonl`. Because a replaced file loses +everything the agent wrote into it and the run still exits 0, the reason a +marker states is also emitted as a `::error::` workflow command whenever the job +sets `GITHUB_ACTIONS=true`. GitHub Actions renders it as an error annotation. +Forgejo Actions also sets `GITHUB_ACTIONS=true`, so its runner writes the same +line, but Forgejo has no annotation view: the line appears in the step log and +the exit status stays 0. On GitLab the line is not written at all. + +A file that cannot be read, sanitized or written does not stop the walk: every +remaining file is still scanned and redacted, and the run fails closed afterwards +with all failures joined. The unredacted file is replaced with the fail-closed +marker so its bytes do not reach the uploaded artifact when the filesystem allows +it; if the marker write and the fallback removal both fail, that failure is added +to the joined error rather than left unreported. + ## Agent rule layering When `fullsend run` executes an agent, Claude Code loads instructions from diff --git a/docs/guides/dev/tracing.md b/docs/guides/dev/tracing.md index 7666c7c9ee..018056582d 100644 --- a/docs/guides/dev/tracing.md +++ b/docs/guides/dev/tracing.md @@ -395,7 +395,7 @@ cut can take the `@` that marks a password and the tail cut the `https://` before it (`promptHidesAlterations`) — is recorded `***` whole; the prompt the agent is sent is not changed, and the mask the first scan leaves for a connection-string password of ten or more bytes matches -its own pattern and counts a finding — +its own pattern, counts a finding, and is itself masked `***` — and sets `gen_ai.input.messages` on the span before the runtime starts, so each finalize path carries it. Its findings join the iteration's, and its encoded size is charged against diff --git a/docs/guides/user/run-artifacts-and-private-data.md b/docs/guides/user/run-artifacts-and-private-data.md index 901d5d4ecb..c96ce82a65 100644 --- a/docs/guides/user/run-artifacts-and-private-data.md +++ b/docs/guides/user/run-artifacts-and-private-data.md @@ -345,7 +345,23 @@ Tool results in those files can quote what the agent read, such as the text of a private Jira issue. On a public repository, any signed-in user can download the artifact until it expires. The output scan masks secret literals; it does not remove personal data, customer names or other private -business text. +business text. A secret that cannot be localized replaces the whole JSON +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. 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 +it. Forgejo Actions also sets `GITHUB_ACTIONS=true`, so the same `::error::` +line is written there, but Forgejo has no annotation view: its runner prints the +line in the step log and the exit status stays 0. On GitLab the line is not +written at all, so the run's log is the signal. A read, write or sanitize +failure needs no annotation because the run itself fails. `fullsend run` leaves `output/` untouched. At the end of the job, `fullsend prepare-artifacts` builds a filtered copy at the level you set, and diff --git a/internal/cli/content_collector.go b/internal/cli/content_collector.go index b7e5a5addd..452dddc88a 100644 --- a/internal/cli/content_collector.go +++ b/internal/cli/content_collector.go @@ -190,8 +190,9 @@ func attachContent(span trace.Span, res contentResult) { // values, once more after the fold, which can spell out a value that pass // saw in compatibility forms. The mask that first scan leaves for a // connection-string password of ten or more bytes ("abcd...") matches its -// own pattern again, so such a prompt counts a finding here; a shorter -// password is masked "***", which does not. +// own pattern again, so such a prompt counts a finding here and the +// placeholder is masked "***"; a shorter password is masked "***", which +// does not match. // The pipeline also folds compatibility characters the agent received // unfolded. Findings join the iteration's and surface through Result. // diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go new file mode 100644 index 0000000000..08108282fc --- /dev/null +++ b/internal/security/jsonsanitize.go @@ -0,0 +1,1478 @@ +package security + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "regexp" + "strconv" + "strings" + "unicode/utf8" +) + +// JSON output that cannot be redacted without corrupting its structure is +// replaced with one of these valid JSON markers so downstream parsers (jq, the +// retro and eval tooling) keep working while no secret reaches the artifact. +// Each marker names the reason its content was dropped: the CLI turns that +// 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"}` + 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 +// write. Without that, the file falls through to the plain-text scan, where a +// redaction can still break the JSON syntax the BOM was hiding (#5705). +var utf8BOM = []byte{0xEF, 0xBB, 0xBF} + +// IsJSONDocument reports whether doc is one JSON document, tolerating a leading +// UTF-8 BOM. SanitizeJSONDocument uses the same test, so callers route exactly +// the documents here that it will treat structurally. +func IsJSONDocument(doc []byte) bool { + return json.Valid(bytes.TrimSpace(bytes.TrimPrefix(doc, utf8BOM))) +} + +// IsJSONLines reports whether content consists of two or more non-empty lines +// where every non-empty line is a valid JSON document. Callers use it to detect +// a multi-document JSON stream regardless of file extension (#5705). +func IsJSONLines(content []byte) bool { + lines := bytes.Split(content, []byte("\n")) + nonEmpty := 0 + for _, line := range lines { + trimmed := bytes.TrimSpace(bytes.TrimPrefix(bytes.TrimSpace(line), utf8BOM)) + if len(trimmed) == 0 { + continue + } + if !json.Valid(trimmed) { + return false + } + nonEmpty++ + } + return nonEmpty >= 2 +} + +// restoreBOM puts back the UTF-8 BOM the structural path strips, so a +// BOM-prefixed file keeps its encoding mark. +func restoreBOM(original, sanitized []byte) []byte { + if !bytes.HasPrefix(original, utf8BOM) { + return sanitized + } + out := make([]byte, 0, len(utf8BOM)+len(sanitized)) + out = append(out, utf8BOM...) + return append(out, sanitized...) +} + +// outputRemovalMarkers lists every whole-file removal marker with the reason it +// states. +var outputRemovalMarkers = []struct { + document, reason string +}{ + {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"}, +} + +// OutputRemoval reports whether sanitized is a whole-file removal marker and +// returns the reason it states. A replaced file loses the content the agent +// wrote into it, so callers alert operators rather than let that loss pass +// silently (#5705). +// +// A leading UTF-8 BOM is framing, not content. SanitizeJSONDocument restores the +// mark on its fail-closed returns and a replaced JSONL record keeps the mark its +// line carried, so the comparison strips it: otherwise a BOM-prefixed file or +// record that lost everything would read as ordinary content and raise no alert. +func OutputRemoval(sanitized []byte) (string, bool) { + trimmed := string(bytes.TrimSpace(bytes.TrimPrefix(bytes.TrimSpace(sanitized), utf8BOM))) + for _, marker := range outputRemovalMarkers { + if trimmed == marker.document { + return marker.reason, true + } + } + return "", false +} + +// OutputRecordRemovals returns the reason stated by each fail-closed marker +// record in a sanitized JSONL stream, in order and without repeats. A JSONL file +// keeps its framing when records are replaced, so it is never a whole-file +// marker, yet the records it lost still have to reach an operator (#5705). +func OutputRecordRemovals(sanitized []byte) []string { + var ( + reasons []string + seen = map[string]bool{} + ) + for _, line := range bytes.Split(sanitized, []byte("\n")) { + reason, removed := OutputRemoval(line) + if !removed || seen[reason] { + continue + } + seen[reason] = true + reasons = append(reasons, reason) + } + return reasons +} + +// sensitiveJSONKeyRe matches object keys whose values are masked even when the +// value itself does not match a secret pattern. +var sensitiveJSONKeyRe = regexp.MustCompile(`(?i)(?:key|token|secret|password|credential|auth)`) + +// redactedJSONKey replaces an object key that sanitization removed entirely +// (a key made only of bidi overrides or other invisible characters, for +// example). Such a key must never be restored as-is. +const redactedJSONKey = "redacted" + +// SanitizeJSONDocument structurally sanitizes a single JSON document so that +// redaction never changes its syntax. It returns the bytes to write and the +// findings that justified a rewrite; no findings means the document is clean +// and the caller must leave it untouched. A document that is not valid JSON is +// returned unchanged with no findings so the caller can fall back to a text +// scan. +// +// The document is rewritten by a token-preserving walk rather than decoded into +// a map and re-encoded: that keeps member order and duplicate keys, so a +// secret that spans JSON framing is still visible in the rewritten bytes. +func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { + if !IsJSONDocument(doc) { + return doc, nil, nil + } + // A BOM is framing rather than content: the token walk cannot parse it, and + // every return below puts it back, so it is stripped once here. + body := bytes.TrimPrefix(doc, utf8BOM) + trimmed := bytes.TrimSpace(body) + // 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 + // so the caller fails closed instead of writing unscanned bytes. + return nil, nil, fmt.Errorf("could not sanitize JSON document: %w", err) + } + out := body + 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 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 + // the trailing-newline adjustment on unchanged bytes would collapse a + // document that ends in more than one newline, rewriting a clean file + // and contradicting the byte-for-byte guarantee (#5705). + return restoreBOM(doc, body), append(findings, outputFindings...), nil + } + return restoreBOM(doc, preserveTrailingNewline(sanitizedOut, body)), append(findings, outputFindings...), nil +} + +// 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. +func preserveTrailingNewline(encoded, doc []byte) []byte { + encoded = bytes.TrimRight(encoded, "\r\n") + switch { + case bytes.HasSuffix(doc, []byte("\r\n")): + return append(encoded, '\r', '\n') + case bytes.HasSuffix(doc, []byte("\n")): + return append(encoded, '\n') + default: + return encoded + } +} + +// redactJSONOutput scans the bytes about to be written for secrets that only +// appear in the serialized form. Such a match does not map to a single leaf, so +// it is applied only when the redacted text is still valid JSON; otherwise the +// document fails closed with a valid marker. clean is returned unchanged when +// the scan finds nothing. +// +// Only whole-value patterns run here. The leaf walk has already applied the +// value patterns to the decoded document, so a value match on the re-encoded +// bytes is a redaction placeholder followed by JSON escape characters rather +// than a secret, and masking it again would drop both the placeholder's prefix +// and a non-secret backslash (#5705). +func redactJSONOutput(clean []byte, p *Pipeline) ([]byte, []Finding) { + res := p.ScanWholeValueSecrets(string(clean)) + if len(res.Findings) == 0 { + return clean, nil + } + for _, finding := range res.Findings { + // A private-key block spanning values cannot be masked in place + // without breaking the surrounding JSON. + if finding.Name == "private_key" { + return []byte(failClosedSpansMembersJSON), res.Findings + } + } + if res.Sanitized == "" || !json.Valid([]byte(res.Sanitized)) { + return []byte(failClosedInvalidJSON), res.Findings + } + return []byte(res.Sanitized), res.Findings +} + +// SanitizeJSONLines sanitizes newline-delimited JSON one record at a time, +// preserving the record framing so every line stays independently parseable. +// A secret that spans a record boundary cannot be redacted without rewriting +// 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') + hasNewline := newline >= 0 + if hasNewline { + line = content[:newline] + content = content[newline+1:] + } else { + content = nil + } + // Keep CRLF framing byte-for-byte for records that are not rewritten. + carriageReturn := len(line) > 0 && line[len(line)-1] == '\r' + if carriageReturn { + line = line[:len(line)-1] + } + trimmed := bytes.TrimSpace(line) + start := out.Len() + switch { + case len(trimmed) == 0: + out.Write(line) + case IsJSONDocument(trimmed): + record, recordFindings, err := SanitizeJSONDocument(trimmed, p) + if err != nil { + return nil, findings, fmt.Errorf("could not sanitize JSONL record: %w", err) + } + findings = append(findings, recordFindings...) + if len(recordFindings) > 0 { + out.Write(record) + } else { + out.Write(line) + } + spans = append(spans, recordSpan{start: start, end: out.Len()}) + default: + res := p.Scan(string(line)) + if len(res.Findings) > 0 { + findings = append(findings, res.Findings...) + out.WriteString(res.Sanitized) + } else { + out.Write(line) + } + spans = append(spans, recordSpan{start: start, end: out.Len()}) + } + if carriageReturn { + out.WriteByte('\r') + } + if hasNewline { + out.WriteByte('\n') + } + } + + rebuilt := out.Bytes() + // Rescan the rebuilt stream only for the secrets no single record can show. + // The per-record pass has already applied every value pattern to the decoded + // record, so running them again on the encoded stream re-matches a redaction + // placeholder followed by JSON escape characters: in encoded JSON a \n escape + // is two non-space bytes, which lets env_assignment run past the end of the + // decoded value and swallow the next word. Each such match replaced an + // already-correct record — and a record whose only secret was an escaped + // newline — with a cross-record marker, which is exactly the failure + // redactJSONOutput rules out for single documents (#5705). Only whole-value + // secrets (registered runtime values and private-key blocks) can still cross + // a record boundary, so only those are scanned here. + stream := p.ScanWholeValueSecrets(string(rebuilt)) + if len(stream.Findings) == 0 { + 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, 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 +} + +// recordSpan is the byte range of one non-empty JSONL record in the rebuilt +// stream, excluding its trailing newline. +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 +// the clean records between them. +// +// The per-record pass has already handled every match a single record could +// account for, so a remaining match spans a record boundary. Localization is +// conservative but per record, not all-or-nothing: inside the changed region a +// record is kept only when its bytes are unique in the stream and reappear as a +// whole newline-delimited record in the redacted stream. Locating a covered +// record means finding its bytes again in the redacted stream, which is only +// trustworthy when the record is distinct: with a repeated record, a later +// untouched copy can stand in for the copy a match covered, and the original +// bytes — carrying part of the secret — would be written back. Such a record is +// replaced. Records outside the changed region are copied through, duplicates +// included. +func failClosedRecordSpans(stream []byte, spans []recordSpan, scan ScanResult) []byte { + sanitized := []byte(scan.Sanitized) + + // Changes are confined to the region that differs between the stream and + // the redacted stream, so records outside it were not touched. + start, end := changedRegion(stream, sanitized) + counts := make(map[string]int, len(spans)) + for _, span := range spans { + counts[string(stream[span.start:span.end])]++ + } + + var out bytes.Buffer + cursor := 0 + searchFrom := 0 + for _, span := range spans { + record := stream[span.start:span.end] + if span.end <= start || span.start >= end { + // Outside the changed region: the bytes are untouched. + out.Write(stream[cursor:span.end]) + cursor = span.end + continue + } + idx := bytes.Index(sanitized[searchFrom:], record) + // A surviving copy must be a whole record, and it must be the only copy: + // otherwise a later untouched duplicate can stand in for a covered one. + if counts[string(record)] == 1 && idx >= 0 && lineBounded(sanitized, searchFrom+idx, searchFrom+idx+len(record)) { + searchFrom += idx + len(record) + out.Write(stream[cursor:span.end]) + cursor = span.end + continue + } + // The record is not present verbatim, so a match covered part of it (or + // the scan reported a finding without changing bytes, which cannot be + // localized at all). Either way it must not be written as-is. + out.Write(stream[cursor:span.start]) + out.WriteString(failClosedCrossRecordJSON) + cursor = span.end + } + out.Write(stream[cursor:]) + return out.Bytes() +} + +// changedRegion returns the half-open byte range that differs between a and b. +// It is approximate for length-changing edits, which is enough: it is used as an +// upper bound on the bytes a redaction touched. +func changedRegion(a, b []byte) (int, int) { + limit := min(len(a), len(b)) + start := 0 + for start < limit && a[start] == b[start] { + start++ + } + end := 0 + for end < limit-start && a[len(a)-1-end] == b[len(b)-1-end] { + end++ + } + return start, len(a) - end +} + +// lineBounded reports whether data[start:end] is a whole newline-delimited +// line. +func lineBounded(data []byte, start, end int) bool { + if start > 0 && data[start-1] != '\n' { + return false + } + switch { + case end == len(data), data[end] == '\n': + return true + case data[end] == '\r': + return end+1 < len(data) && data[end+1] == '\n' + default: + return false + } +} + +// 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, 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, spans: spans} + ) + if err := w.writeValue(dec, &buf, ""); err != nil { + return nil, nil, fmt.Errorf("could not tokenize JSON: %w", err) + } + if _, err := dec.Token(); !errors.Is(err, io.EOF) { + return nil, nil, fmt.Errorf("unexpected trailing JSON content") + } + return buf.Bytes(), w.findings, nil +} + +// 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 +// elements and the top-level value. +func (w *jsonRewrite) writeValue(dec *json.Decoder, buf *bytes.Buffer, memberKey string) error { + tok, err := dec.Token() + if err != nil { + return err + } + switch t := tok.(type) { + 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) + case json.Number: + literal := t.String() + res := w.pipeline.Scan(literal) + if len(res.Findings) == 0 { + buf.WriteString(literal) + return nil + } + w.findings = append(w.findings, res.Findings...) + // A redacted number is no longer a number literal, so write the + // replacement as a JSON string to keep the document valid. + return writeJSONString(buf, res.Sanitized) + case bool: + buf.WriteString(strconv.FormatBool(t)) + return nil + case nil: + buf.WriteString("null") + return nil + default: + return fmt.Errorf("unexpected JSON token %T", tok) + } +} + +// jsonMember is one object member whose value has been rendered but whose name +// is not final yet. Names are resolved once the whole object has been read so a +// sanitized name can never collide with a clean key that appears later. +type jsonMember struct { + originalKey string + sanitizedKey string + rendered []byte +} + +// writeContainer writes the members of an object or array, preserving member +// order and duplicate keys. +func (w *jsonRewrite) writeContainer(dec *json.Decoder, buf *bytes.Buffer, delim json.Delim) error { + switch delim { + case '{': + var members []jsonMember + for dec.More() { + keyTok, err := dec.Token() + if err != nil { + return err + } + key, ok := keyTok.(string) + 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 + // that replaced a key must not drag its value into json_field + // masking. + if err := w.writeValue(dec, &rendered, key); err != nil { + return err + } + members = append(members, jsonMember{ + originalKey: key, + sanitizedKey: sanitizedKey, + rendered: rendered.Bytes(), + }) + } + if _, err := dec.Token(); err != nil { // consume '}' + return err + } + assignJSONMemberNames(members) + buf.WriteByte('{') + for i, m := range members { + if i > 0 { + buf.WriteByte(',') + } + if err := writeJSONString(buf, m.sanitizedKey); err != nil { + return err + } + buf.WriteByte(':') + buf.Write(m.rendered) + } + buf.WriteByte('}') + return nil + case '[': + buf.WriteByte('[') + first := true + for dec.More() { + if !first { + buf.WriteByte(',') + } + if err := w.writeValue(dec, buf, ""); err != nil { + return err + } + first = false + } + if _, err := dec.Token(); err != nil { // consume ']' + return err + } + buf.WriteByte(']') + return nil + default: + return fmt.Errorf("unexpected JSON delimiter %q", delim.String()) + } +} + +// assignJSONMemberNames resolves the member names of one object. Clean keys keep +// their names, and a sanitized name that would collide with a different key is +// disambiguated. Repeats of the same original duplicate key keep sharing one +// name, so intentional duplicate keys survive sanitization. +func assignJSONMemberNames(members []jsonMember) { + claimed := make(map[string]string, len(members)) + for _, m := range members { + if m.sanitizedKey == m.originalKey { + claimed[m.sanitizedKey] = m.originalKey + } + } + renamed := make(map[string]string, len(members)) + for i := range members { + m := &members[i] + if m.sanitizedKey == m.originalKey { + continue + } + if target, ok := renamed[m.originalKey]; ok { + m.sanitizedKey = target + continue + } + target := m.sanitizedKey + if owner, taken := claimed[target]; taken && owner != m.originalKey { + for n := 1; ; n++ { + cand := fmt.Sprintf("%s_%d", m.sanitizedKey, n) + if _, exists := claimed[cand]; !exists { + target = cand + break + } + } + } + renamed[m.originalKey] = target + claimed[target] = m.originalKey + m.sanitizedKey = target + } +} + +// writeJSONString appends s to buf as a JSON string literal without escaping +// HTML characters, so legitimate markup survives sanitization. +func writeJSONString(buf *bytes.Buffer, s string) error { + var encoded bytes.Buffer + enc := json.NewEncoder(&encoded) + enc.SetEscapeHTML(false) + if err := enc.Encode(s); err != nil { + return err + } + buf.Write(bytes.TrimSuffix(encoded.Bytes(), []byte("\n"))) + return nil +} + +// sanitizeJSONKey sanitizes one object key. A key whose sanitized value is +// empty was removed entirely, so it is replaced with a placeholder rather than +// kept as-is. +func sanitizeJSONKey(key string, p *Pipeline) (string, []Finding) { + res := p.Scan(key) + if len(res.Findings) == 0 { + return key, nil + } + sanitized := res.Sanitized + if sanitized == "" { + sanitized = redactedJSONKey + } + return sanitized, res.Findings +} + +// sanitizeJSONString sanitizes one string leaf. memberKey is the enclosing +// object key, used to mask values whose key name marks them as sensitive even +// when the value itself matches no secret pattern. +func sanitizeJSONString(value, memberKey string, p *Pipeline) (string, []Finding) { + res := p.Scan(value) + out := value + var findings []Finding + rewritten := len(res.Findings) > 0 + if rewritten { + findings = append(findings, res.Findings...) + out = res.Sanitized + } + // Sensitivity is decided on the key as the leaf scan sees it: invisible + // characters stripped and compatibility forms folded, the same normalization + // sanitizeJSONKey applies when it writes the name back. Testing the original + // spelling let a key such as "pass\u200bword" be written as "password" with an + // untouched value (#5705). + key := normalizedJSONKey(memberKey) + // #9944: an "author" member holding a codex agent path is not a credential, + // although "author" contains the "auth" trigger word. The text pipeline + // honours this exemption; the structural path must too, because a codex + // transcript is a JSON document and takes that path. + exempt := strings.EqualFold(key, "author") && authorPathValue.MatchString(out) + // isAlreadyMasked is only trusted for a value this scan actually rewrote: + // the placeholder shape is also a real short-secret shape, so an original + // value must still be masked even when it looks like one (#5705). + if key != "" && !exempt && sensitiveJSONKeyRe.MatchString(key) && + !(rewritten && isAlreadyMasked(out)) && + utf8.RuneCountInString(out) >= minJSONFieldLen { + masked := Mask(out) + findings = append(findings, Finding{ + Scanner: "secret_redactor", + Name: "json_field", + Severity: "high", + Detail: fmt.Sprintf("Redacted json_field (%d chars) -> %s", utf8.RuneCountInString(out), masked), + }) + out = masked + } + return out, findings +} + +// normalizedJSONKey returns key as the leaf scan sees it: invisible characters +// stripped and compatibility forms folded, exactly as sanitizeJSONKey normalizes +// the name it writes back. Sensitivity has to be checked on this spelling, or a +// zero-width or fullwidth obfuscated sensitive key becomes an explicitly +// sensitive field with an untouched value (#5705). +func normalizedJSONKey(key string) string { + if key == "" { + return "" + } + return decodedViewNormalizer.Scan(key).Sanitized +} diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go new file mode 100644 index 0000000000..3fab65188d --- /dev/null +++ b/internal/security/jsonsanitize_test.go @@ -0,0 +1,2131 @@ +package security + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// pemBegin and pemEnd are the marker strings under test. They are split at +// definition so a source scan of the test files does not treat this as key +// material, and defined once so a marker-shape change cannot leave one fixture +// testing a different shape than the others. +var ( + pemBegin = "-----BEGIN RSA" + " PRIVATE KEY-----" + pemEnd = "-----END RSA" + " PRIVATE KEY-----" +) + +// TestSanitizeJSONDocument_DuplicateKeyEarlierOccurrenceRedacted pins that a +// secret in an earlier, overwritten duplicate-key occurrence is still found. +// Map decoding drops that occurrence, so only a token-preserving walk sees it. +func TestSanitizeJSONDocument_DuplicateKeyEarlierOccurrenceRedacted(t *testing.T) { + p := OutputPipeline() + // \u0067 decodes to "g"; the raw text never contains "ghp_". + escapedSecret := `\u0067hp_FAKEtesttoken000000000000000000000000` + doc := []byte(`{"note":"` + escapedSecret + `","note":"clean"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized duplicate-key JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + assert.NotContains(t, string(out), `\u0067hp_`) + assert.Contains(t, string(out), `"note":"clean"`, "the surviving duplicate value must be preserved") +} + +// TestSanitizeJSONDocument_DuplicateKeysSurviveRewrite pins that the +// token-preserving walk keeps duplicate keys and their order when another +// member forces a rewrite. +func TestSanitizeJSONDocument_DuplicateKeysSurviveRewrite(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"a":1,"a":2,"token":"ghp_FAKEtesttoken000000000000000000000000"}`) + + 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), `"a":1,"a":2`, "duplicate members must keep their order") + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersMasksCoveredMembers pins +// that a private key spread over several members is neutralized member by member +// instead of dropping the whole document. Scanning only the re-encoded form +// missed the block: encoding a map sorts keys, and with the END marker sorted +// 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"} + quoted := []string{`"` + pemBegin + `"`} + for _, chunk := range chunks { + quoted = append(quoted, `"`+chunk+`"`) + } + quoted = append(quoted, `"`+pemEnd+`"`) + doc := []byte(`{"lines":[` + strings.Join(quoted, ",") + `]}`) + + 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 _, chunk := range chunks { + assert.NotContains(t, string(out), chunk, "a short body chunk must not survive") + } + assert.NotContains(t, string(out), "PRIVATE KEY-----") +} + +// TestSanitizeJSONDocument_ChunkedBodyBetweenMarkersMasked pins the regression a +// reviewer found: a body split across members into chunks that are each short, +// digit-free, or hex-looking was written back after the boundary markers were +// masked, where the written-bytes rescan can no longer see the block. The joined +// text of consecutive values reconstructs the body, so every chunk is masked +// (#5705). +func TestSanitizeJSONDocument_ChunkedBodyBetweenMarkersMasked(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + cases := map[string][]string{ + "short chunks": {"MIIEowIB", "AAKCAQEA", "x9Kq2Lm"}, + "digit-free chunk": {"MIIEowIBAAKCAQEA"}, + "hex chunk in the run": {"MIIEowIBAAKCAQEA", "abcdef0123456789", "short+chunk"}, + } + for name, chunks := range cases { + t.Run(name, func(t *testing.T) { + quoted := make([]string, 0, len(chunks)+2) + quoted = append(quoted, `"`+begin+`"`) + for _, chunk := range chunks { + quoted = append(quoted, `"`+chunk+`"`) + } + quoted = append(quoted, `"`+end+`"`) + doc := []byte(`{"lines":[` + strings.Join(quoted, ",") + `]}`) + + 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-----") + for _, chunk := range chunks { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } + }) + } +} + +// TestSanitizeJSONDocument_HexValuesInSpanKeepTheirContent pins that a hex run +// 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 + end := pemEnd + const body = "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + doc := []byte(`{"` + begin + `":1,"` + body + `":2,"` + end + `":3}`) + + 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 line in a key name is key material") + assert.NotContains(t, string(out), "BEGIN RSA") + assert.NotContains(t, string(out), "END RSA") +} + +// TestSanitizeJSONDocument_StructuralKeysKeepNamesNextToMaterial pins the other +// 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) + const secret = `","field2":"` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + doc := []byte(`{"field1":"foo","field2":"bar"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "a framing-spanning secret must produce a finding") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), secret) +} + +// TestSanitizeJSONDocument_CrossMemberPrivateKeyWithLeafSecret pins that a leaf +// 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) + const secret = "abcdefghijk" + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + doc := []byte(`{"` + secret + `":1,"***":2,"d":0,"d":1}`) + + 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), secret) + + var decoded map[string]any + require.NoError(t, json.Unmarshal(out, &decoded)) + assert.Equal(t, float64(2), decoded["***"], "the clean key must keep its own value") + assert.Equal(t, float64(1), decoded["***_1"], "the sanitized key must be disambiguated") + assert.Equal(t, 2, strings.Count(string(out), `"d":`), "intentional duplicate keys must survive") +} + +// TestSanitizeJSONLines_CrossRecordRuntimeSecretFailsClosed pins that a +// runtime secret spanning two individually valid records is not discarded. +func TestSanitizeJSONLines_CrossRecordRuntimeSecretFailsClosed(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const secret = `one"}` + "\n" + `{"key` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + content := []byte("{\"key_one\":\"one\"}\n{\"key_two\":\"two\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), secret, "the cross-record secret must not survive") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 2, "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_RedactedAssignmentBeforeEscapedNewlineKeepsRecord pins +// that the whole-stream rescan cannot re-match a value the per-record pass +// already redacted. In encoded JSON a \n escape is two non-space bytes, so +// running env_assignment over the rebuilt stream matched the placeholder plus +// the next word, and the correctly redacted record was replaced with a +// cross-record marker — a false alarm that dropped real content from +// transcripts/*.jsonl and output.jsonl (#5705). +func TestSanitizeJSONLines_RedactedAssignmentBeforeEscapedNewlineKeepsRecord(t *testing.T) { + p := OutputPipeline() + content := []byte(`{"type":"assistant","text":"run: API_KEY=supersecretvalue123\nnext line"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.Len(t, findings, 1, "one secret must be reported once, not recounted by the stream rescan: %+v", findings) + assert.Equal(t, "env_assignment", findings[0].Name) + + line := strings.TrimSpace(string(out)) + assert.True(t, json.Valid([]byte(line)), "the record must stay valid JSON: %s", line) + assert.NotContains(t, line, "output removed", "a redacted record must not be replaced") + assert.NotContains(t, line, "supersecretvalue123") + assert.Contains(t, line, "next line", "the text after the escaped newline must survive") +} + +// TestSanitizeJSONLines_BenignEscapedAssignmentKeepsRecord pins the benign half +// of the same regression: a shell command with an escaped newline contains no +// secret at all, and the per-record pass leaves it alone (#5705). +func TestSanitizeJSONLines_BenignEscapedAssignmentKeepsRecord(t *testing.T) { + p := OutputPipeline() + content := []byte(`{"text":"export GITHUB_TOKEN=$TOKEN\nnext line"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.Empty(t, findings, "no secret is present, so nothing may be reported") + assert.Equal(t, string(content), string(out), "a benign record must be written back unchanged") +} + +// only the records a cross-record match touches are replaced. A single +// first-to-last changed region used to swallow every record between two +// disjoint matches. +func TestSanitizeJSONLines_DisjointCrossRecordMatchesKeepCleanRecord(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const first = `one"}` + "\n" + `{"b` + const second = `three"}` + "\n" + `{"d` + require.True(t, RegisterRuntimeSecret(first)) + require.True(t, RegisterRuntimeSecret(second)) + + p := OutputPipeline() + content := []byte( + "{\"a\":\"one\"}\n" + + "{\"b\":\"two\"}\n" + + "{\"clean\":\"middle\"}\n" + + "{\"c\":\"three\"}\n" + + "{\"d\":\"four\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), first) + assert.NotContains(t, string(out), second) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 5, "record count must not change") + assert.Equal(t, `{"clean":"middle"}`, lines[2], "the clean record between two matches must survive") + for _, i := range []int{0, 1, 3, 4} { + 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") + } +} + +// TestSanitizeJSONDocument_BackstopKeepsEarlierMask pins that the +// serialized-bytes backstop never masks a redaction placeholder a second time. +// The leaf pass masked part of an escaped sequence, so re-encoding left the +// placeholder followed by doubled backslashes. A value pattern captured that +// tail, found no complete mask, and masked again — dropping the informative +// prefix and a non-secret backslash, and logging a duplicate finding (#5705). +func TestSanitizeJSONDocument_BackstopKeepsEarlierMask(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"body":"x token_usage = metrics.get(\\\"token_usage\\\") or {}"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.Len(t, findings, 1, "only the leaf match may be reported: %+v", findings) + assert.Equal(t, "env_assignment", findings[0].Name) + + var decoded struct { + Body string `json:"body"` + } + require.NoError(t, json.Unmarshal(out, &decoded)) + assert.Equal(t, `x token_usage = metr...\"token_usage\") or {}`, decoded.Body, + "the earlier mask and the non-secret backslashes must survive") +} + +// TestSanitizeJSONDocument_BackstopRedactsSecondRuntimeSecret pins that a +// runtime secret exposed only by serializing the parsed document is still +// handled when another runtime secret was already found in a leaf. +func TestSanitizeJSONDocument_BackstopRedactsSecondRuntimeSecret(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const leafSecret = "leafonlysecretvalue" + const serializedSecret = `","field2":"` + require.True(t, RegisterRuntimeSecret(leafSecret)) + require.True(t, RegisterRuntimeSecret(serializedSecret)) + + p := OutputPipeline() + doc := []byte(`{"field1":"leafonlysecretvalue","field2":"bar"}`) + + 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), leafSecret) + assert.NotContains(t, string(out), serializedSecret) +} + +// TestSanitizeJSONDocument_KeyRemovedEntirelyIsReplaced pins that a JSON key +// made only of removable characters never survives sanitization. +func TestSanitizeJSONDocument_KeyRemovedEntirelyIsReplaced(t *testing.T) { + p := OutputPipeline() + for name, key := range map[string]string{ + "null byte": "\x00", + "bidi override": "\u202e", + } { + t.Run(name, func(t *testing.T) { + doc, err := json.Marshal(map[string]string{key: "value"}) + require.NoError(t, err) + + 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), `\u0000`) + assert.NotContains(t, string(out), `\u202e`) + + var decoded map[string]string + require.NoError(t, json.Unmarshal(out, &decoded)) + assert.Equal(t, "value", decoded[redactedJSONKey]) + }) + } +} + +// TestSanitizeJSONLines_SingleRecordPEMKeepsCleanRecords pins that a private +// key confined to one record is redacted in place instead of replacing every +// record in the file. +func TestSanitizeJSONLines_SingleRecordPEMKeepsCleanRecords(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte( + "{\"event\":\"clean-before\"}\n" + + "{\"tool\":\"read\",\"text\":\"" + begin + "\\nMIIEpAIBAAKCAQEA0123456789abcdef\\n" + end + "\"}\n" + + "{\"event\":\"clean-after\"}\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.Equal(t, `{"event":"clean-before"}`, lines[0], "clean records must be untouched") + assert.Equal(t, `{"event":"clean-after"}`, lines[2], "clean records must be untouched") + assert.True(t, json.Valid([]byte(lines[1]))) + assert.NotContains(t, lines[1], "BEGIN RSA") + assert.NotContains(t, lines[1], "MIIEpAIBAAKCAQEA") +} + +// TestOutputRemoval pins the markers recognized as a whole-file replacement and +// the reason reported for the operator alert. +func TestOutputRemoval(t *testing.T) { + for name, tc := range map[string]struct { + input string + reason string + removed bool + }{ + "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" + 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}, + "empty": {"", "", false}, + } { + t.Run(name, func(t *testing.T) { + reason, removed := OutputRemoval([]byte(tc.input)) + assert.Equal(t, tc.removed, removed) + assert.Equal(t, tc.reason, reason) + }) + } +} + +// TestOutputRecordRemovals pins that a JSONL stream whose records were replaced +// reports each distinct reason once. A replaced record keeps the file's framing, +// so the file never equals a whole-file marker, and this is how its loss reaches +// an operator (#5705). +func TestOutputRecordRemovals(t *testing.T) { + stream := []byte( + `{"event":"clean"}` + "\n" + + failClosedCrossRecordJSON + "\r\n" + + failClosedCrossRecordJSON + "\n" + + failClosedSpansMembersJSON + "\n") + assert.Equal(t, + []string{"a secret spanned multiple records", "a private key block spans JSON framing"}, + OutputRecordRemovals(stream)) + assert.Empty(t, OutputRecordRemovals([]byte(`{"event":"clean"}`+"\n"))) +} + +// TestOutputRecordRemovals_BOMFirstRecord pins that a replaced first record keeps +// the BOM its line carried, and that the mark does not hide the loss: the record +// is still reported, so the operator alert is not skipped (#5705). +func TestOutputRecordRemovals_BOMFirstRecord(t *testing.T) { + stream := []byte("\ufeff" + failClosedCrossRecordJSON + "\n" + `{"event":"clean"}` + "\n") + assert.Equal(t, + []string{"a secret spanned multiple records"}, + OutputRecordRemovals(stream)) +} + +// 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 {}"}`) + + first, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.Len(t, findings, 1, "one secret must produce one finding") + assert.Contains(t, string(first), "metr...", "the informative prefix must be retained") + + second, findings, err := SanitizeJSONDocument(first, p) + require.NoError(t, err) + assert.Empty(t, findings, "rescanning a sanitized document must be idempotent") + assert.Equal(t, first, second) +} + +// TestSanitizeJSONDocument_DuplicateKeyNestedContainers covers the +// token-preserving walk across nested objects, arrays, every scalar type, and +// an escaped duplicate key whose value is a container. +func TestSanitizeJSONDocument_DuplicateKeyNestedContainers(t *testing.T) { + p := OutputPipeline() + escapedSecret := `\u0067hp_FAKEtesttoken000000000000000000000000` + doc := []byte(`{"outer":[{"id":1,"id":2,"opts":{"flag":true,"none":null,"ratio":1.5}},` + + `{"token":"` + escapedSecret + `","token":["clean"]}],"tail":false}`) + + 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") + + var decoded any + require.NoError(t, json.Unmarshal(out, &decoded)) + outer := decoded.(map[string]any)["outer"].([]any) + second := outer[1].(map[string]any) + // The duplicate-key walk keeps the later occurrence, which is the array. + assert.Equal(t, []any{"clean"}, second["token"]) + assert.Equal(t, false, decoded.(map[string]any)["tail"]) +} + +// TestSanitizeJSONDocument_ScalarAndContainerCoverage exercises every scalar +// branch and nested collection of the walker. +func TestSanitizeJSONDocument_ScalarAndContainerCoverage(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const numericSecret = "123456789012" + require.True(t, RegisterRuntimeSecret(numericSecret)) + + p := OutputPipeline() + doc := []byte(`{"list":["plain",42,` + numericSecret + `,true,null],` + + `"nested":{"deep":[{"value":"plain"}]},"counter":7}`) + + 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), numericSecret) + assert.Contains(t, string(out), "42", "clean numbers must keep their precision") + assert.Contains(t, string(out), `"counter":7`) +} + +// TestSanitizeJSONDocument_CleanKeyWinsSanitizedCollision pins that a secret key +// whose mask collides with an existing clean member never steals that member's +// name or value. +func TestSanitizeJSONDocument_CleanKeyWinsSanitizedCollision(t *testing.T) { + const secret = "ghp_FAKEtesttoken000000000000000000000000" + const masked = "ghp_..." + p := OutputPipeline() + doc := []byte(`{"` + secret + `":"secretkeyval","` + masked + `":"plainval"}`) + + // Repeat so a map-iteration-order-dependent bug in name resolution cannot + // hide behind a single lucky ordering. + for range 20 { + 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) + + var decoded map[string]string + require.NoError(t, json.Unmarshal(out, &decoded)) + assert.Equal(t, "plainval", decoded[masked], "clean key must retain its name and value") + assert.Len(t, decoded, 2) + assert.NotContains(t, string(out), secret) + } +} + +// TestSanitizeJSONLines_RepeatedRecordsFailsClosed pins that a cross-record +// match is not localized by a substring search a repeated record can fool. A +// later untouched copy must never stand in for a covered record: keeping the +// original bytes would write the spanning secret back out. Duplicates outside +// the changed region are still preserved. +func TestSanitizeJSONLines_RepeatedRecordsFailsClosed(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const secret = `aaa"}` + "\n" + `{"v":"bbb` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + content := []byte( + "{\"v\":\"aaa\"}\n" + // first half of the match + "{\"v\":\"bbb\"}\n" + // second half of the match + "{\"v\":\"aaa\"}\n" + // untouched duplicate of record 1 + "{\"v\":\"ccc\"}\n" + + "{\"v\":\"bbb\"}\n") // untouched duplicate of record 2 + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), secret, "the spanning secret must not be reassembled") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 5, "record count must not change") + for _, line := range lines[:2] { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } + assert.Equal(t, `{"v":"aaa"}`, lines[2], "an untouched duplicate outside the change must survive") + assert.Equal(t, `{"v":"ccc"}`, lines[3]) + assert.Equal(t, `{"v":"bbb"}`, lines[4], "an untouched duplicate outside the change must survive") +} + +// TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch pins that a +// clean record between a quoted header and footer survives, whether or not it +// repeats later. The cross-record check replaces only the records that carry +// 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 + end := pemEnd + content := []byte( + "[\"" + begin + "\"]\n" + + "[\"dfghjk\"]\n" + + "[\"QWERTYuiop\"]\n" + + "[\"" + end + "\"]\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "dfghjkQWERTYuiop") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONDocument_SensitiveBeginMemberMasksBlock pins that masking a +// sensitive member value cannot hide a private-key block that spans members. A +// 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") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.NotEmpty(t, findings) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 2) + assert.Equal(t, `{"a":1,"a":2}`, lines[0], "clean duplicate-key record must remain unchanged") + assert.True(t, json.Valid([]byte(lines[1]))) + assert.NotContains(t, lines[1], "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONLines_PrivateKeyAcrossRecordsFailsClosed pins that a PEM +// block split over three records replaces all three. +func TestSanitizeJSONLines_PrivateKeyAcrossRecordsFailsClosed(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte(fmt.Sprintf("[%q]\n[%q]\n[%q]\n", begin, "MIIEpAIBAAKCAQEA0123456789abcdefghijklmnop", end)) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.Equal(t, "private_key", findings[0].Name) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3) + for _, line := range lines { + assert.True(t, json.Valid([]byte(line))) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONLines_RawMultilinePEMFailsClosed pins the same for a PEM +// block written as raw lines rather than JSON values. +func TestSanitizeJSONLines_RawMultilinePEMFailsClosed(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte(fmt.Sprintf("%s\nMIIEpAIBAAKCAQEA0123456789abcdefghijklmnop\n%s\n", begin, end)) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.Equal(t, "private_key", findings[0].Name) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3) + for _, line := range lines { + assert.True(t, json.Valid([]byte(line))) + assert.Contains(t, line, "output removed") + assert.NotContains(t, line, "MIIEpAIBAAKCAQEA") + } +} + +// TestSanitizeJSONLines_DuplicateKeyEscapedSecretRedacted pins that an escaped +// secret in a record with duplicate keys is found by the token walk. +func TestSanitizeJSONLines_DuplicateKeyEscapedSecretRedacted(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"a\":\"first\",\"a\":\"second\",\"password\":\"\\u0073\\u0065\\u0063\\u0072\\u0065\\u0074_password_1234\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.NotEmpty(t, findings) + line := strings.TrimSpace(string(out)) + assert.True(t, json.Valid([]byte(line))) + assert.NotContains(t, line, "password_1234") + assert.Contains(t, line, `"a":"first"`, "an earlier duplicate value must survive redaction") + assert.Contains(t, line, `"a":"second"`, "the second duplicate value must survive redaction") +} + +// TestSanitizeJSONLines_FramingSecretPreservesLineCount pins that a secret +// spanning one record's own framing is redacted without adding or removing +// lines. +func TestSanitizeJSONLines_FramingSecretPreservesLineCount(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const secret = `","field2":"` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + content := []byte("{\"field1\":\"foo\",\"field2\":\"bar\"}\n{\"field3\":\"second record\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.Equal(t, 2, strings.Count(string(out), "\n"), "line count must remain exactly 2") + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 2) + assert.True(t, json.Valid([]byte(lines[0]))) + assert.True(t, json.Valid([]byte(lines[1]))) + assert.NotContains(t, lines[0], secret) +} + +// TestSanitizeJSONLines_SingleRecordPrivateKeyRedactedInPlace pins that a key +// confined to one record is redacted rather than failed closed. +func TestSanitizeJSONLines_SingleRecordPrivateKeyRedactedInPlace(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte(fmt.Sprintf("{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\",\"pem\":\"%s\\n%s\"}\n", begin, end)) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.NotEmpty(t, findings) + line := strings.TrimSpace(string(out)) + assert.True(t, json.Valid([]byte(line))) + assert.Equal(t, 1, strings.Count(string(out), "\n"), "one record must stay one record") + assert.NotContains(t, line, "ghp_FAKEtesttoken") + assert.NotContains(t, line, "PRIVATE KEY-----") + assert.Contains(t, line, "[REDACTED PRIVATE KEY]", "a key confined to one record is redacted in place") +} + +// TestLineBounded pins the record-boundary check used to decide whether a +// surviving record copy is a whole record. +func TestLineBounded(t *testing.T) { + data := []byte("a\nbb\r\nccc\nlast") + tests := []struct { + name string + start, end int + want bool + }{ + {"whole first line", 0, 1, true}, + {"whole crlf line", 2, 4, true}, + {"whole middle line", 6, 9, true}, + {"last line without newline", 10, 14, true}, + {"starts mid-line", 1, 4, false}, + {"ends mid-line", 6, 8, false}, + {"lone carriage return", 9, 10, false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, lineBounded(data, tc.start, tc.end)) + }) + } +} + +// 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") + content := append(append([]byte{}, bom...), []byte(`{"event":"clean"}`+"\n")...) + content = append(content, []byte("{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\n")...) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, bytes.HasPrefix(out, bom), "the BOM must survive: %q", out) + assert.Contains(t, string(out), `{"event":"clean"}`, "a clean BOM-prefixed record must be unchanged") + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONDocument_CRLFNoStrayCarriageReturn pins that trailing CRLF +// framing is reproduced exactly, without a duplicated carriage return, on the +// unchanged and rewritten paths. +func TestSanitizeJSONDocument_CRLFNoStrayCarriageReturn(t *testing.T) { + p := OutputPipeline() + for name, doc := range map[string]string{ + "clean": "{\"a\":\"x\"}\r\n", + "secret": "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\r\n", + } { + t.Run(name, func(t *testing.T) { + out, _, err := SanitizeJSONDocument([]byte(doc), p) + require.NoError(t, err) + assert.NotContains(t, string(out), "\r\r", "no stray carriage return") + assert.True(t, strings.HasSuffix(string(out), "}\r\n"), "CRLF framing must be preserved: %q", out) + }) + } +} + +// 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 + // U+200B inside the BEGIN marker: not a PEM block in any single form. + doc := []byte(`{"begin":"-----\u200bBEGIN RSA` + " PRIVATE KEY-----\"" + + `,"payload":"MIIEspanningkeymaterial0","end":"` + 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_UnterminatedBeginBeforeCompleteBlockMasksBoth pins +// 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{ + "not json": `{"unterminated": `, + "plain text": "just prose", + "empty": "", + "trailing value": `{"a":1}{"b":2}`, + } { + t.Run(name, func(t *testing.T) { + out, findings, err := SanitizeJSONDocument([]byte(doc), p) + require.NoError(t, err) + assert.Empty(t, findings) + assert.Equal(t, doc, string(out), "an unsupported document must be returned unchanged") + }) + } +} + +// TestIsJSONLines pins multi-document detection. +func TestIsJSONLines(t *testing.T) { + assert.True(t, IsJSONLines([]byte("{\"a\":1}\n{\"b\":2}\n"))) + assert.True(t, IsJSONLines([]byte("\ufeff{\"a\":1}\r\n{\"b\":2}\r\n"))) + assert.False(t, IsJSONLines([]byte("{\"a\":1}\n")), "single record is not a multi-document stream") + assert.False(t, IsJSONLines([]byte("{\"a\":1}")), "single record without newline is not a stream") + assert.False(t, IsJSONLines([]byte("{\"a\":1}\nnot json\n")), "stream with non-JSON line is rejected") + assert.False(t, IsJSONLines([]byte("")), "empty content is not a stream") +} + +// TestSanitizeJSONLines_NonJSONRecordsRedacted pins the text fallback for +// records that are not valid JSON. +func TestSanitizeJSONLines_NonJSONRecordsRedacted(t *testing.T) { + p := OutputPipeline() + content := []byte("plain Token: ghp_FAKEtesttoken000000000000000000000000\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + assert.Equal(t, 1, strings.Count(string(out), "\n"), "line framing must be preserved") +} + +// TestSanitizeJSONLines_PreservesBlankAndCleanRecords pins that blank lines and +// clean non-JSON records survive a stream that also contains a secret. +func TestSanitizeJSONLines_PreservesBlankAndCleanRecords(t *testing.T) { + p := OutputPipeline() + content := []byte("plain prose without secrets\n" + + "\n" + + "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\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, "blank lines and record count must be preserved") + assert.Equal(t, "plain prose without secrets", lines[0]) + assert.Empty(t, lines[1]) + assert.NotContains(t, lines[2], "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONDocument_TextRedactionThatBreaksJSONFailsClosed pins that a +// framing-spanning secret whose in-place redaction would leave invalid JSON is +// replaced with a valid marker instead of corrupted syntax. +func TestSanitizeJSONDocument_TextRedactionThatBreaksJSONFailsClosed(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + // Spans the closing quote, comma and next key, so masking it breaks the + // document. + const secret = `"v1","k2"` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + doc := []byte(`{"k1":"v1","k2":"v2"}`) + + 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), secret) + assert.Contains(t, string(out), "output removed") +} + +// TestSanitizeJSONDocument_TopLevelScalars pins that scalar documents are +// handled without inventing structure. +func TestSanitizeJSONDocument_TopLevelScalars(t *testing.T) { + p := OutputPipeline() + for name, doc := range map[string]string{ + "number": "42", + "true": "true", + "null": "null", + } { + t.Run(name, func(t *testing.T) { + out, findings, err := SanitizeJSONDocument([]byte(doc), p) + require.NoError(t, err) + assert.Empty(t, findings) + assert.Equal(t, doc, string(out)) + }) + } +} + +// TestSanitizeJSONLines_LastRecordWithoutNewline pins that a final record +// without a trailing newline is still sanitized and keeps its framing. +func TestSanitizeJSONLines_LastRecordWithoutNewline(t *testing.T) { + p := OutputPipeline() + content := []byte(`{"token":"ghp_FAKEtesttoken000000000000000000000000"}`) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + assert.False(t, strings.HasSuffix(string(out), "\n"), "no newline must be invented") + assert.True(t, json.Valid(out), "the record must stay valid JSON: %s", out) +} + +// TestSanitizeJSONLines_PreservesCRLFFraming pins that CRLF records keep their +// carriage returns across a rewrite. +func TestSanitizeJSONLines_PreservesCRLFFraming(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"event\":\"clean\"}\r\n{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\r\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.Equal(t, 2, strings.Count(string(out), "\r\n"), "CRLF framing must be preserved") + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONDocument_TrailingNewlinePreserved pins that a rewritten +// document keeps the file's own line framing. +func TestSanitizeJSONDocument_TrailingNewlinePreserved(t *testing.T) { + p := OutputPipeline() + for name, doc := range map[string]string{ + "lf": "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\n", + "crlf": "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\r\n", + "none": "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}", + } { + t.Run(name, func(t *testing.T) { + out, findings, err := SanitizeJSONDocument([]byte(doc), p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + + want := map[string]string{"lf": "\n", "crlf": "\r\n", "none": ""}[name] + assert.True(t, strings.HasSuffix(string(out), "}"+want), "trailing framing must be preserved: %q", out) + assert.Equal(t, strings.Count(doc, "\n"), strings.Count(string(out), "\n")) + }) + } +} + +// TestSanitizeJSONDocument_CleanDuplicateKeyDocumentUnchanged pins that a +// duplicate-key document with nothing to redact is left byte-for-byte intact. +func TestSanitizeJSONDocument_CleanDuplicateKeyDocumentUnchanged(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"a": 1, "a": 2}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + assert.Empty(t, findings) + assert.Equal(t, string(doc), string(out), "a clean duplicate-key document must not be reformatted") +} + +// TestSanitizeJSONDocument_DuplicateKeyRawTextFinding covers a document whose +// match exists in the serialized form: the leaves are individually clean, so +// the raw-text scan finds and redacts it. +func TestSanitizeJSONDocument_DuplicateKeyRawTextFinding(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"password": "secretvalue123", "dup": 1, "dup": 2}`) + + 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), "secretvalue123") +} + +// TestSanitizeJSONDocument_DuplicateKeyWithSecretKey covers a duplicate-key +// document whose keys themselves carry a secret. +func TestSanitizeJSONDocument_DuplicateKeyWithSecretKey(t *testing.T) { + p := OutputPipeline() + const secret = "ghp_FAKEtesttoken000000000000000000000000" + doc := []byte(`{"` + secret + `": 1, "` + secret + `": 2}`) + + 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), secret) +} + +// reviewResultSchemaPath is a pinned copy of the schema authored in +// fullsend-ai/agents (schemas/review-result.schema.json). Vendoring it ties these +// tests to the real constraints sanitization can break — the enums and patterns +// 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, +// 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. +type reviewResultSchema struct { + topLevel map[string]bool + findingMembers map[string]bool + actions []string + severities []string + categories []string +} + +// loadReviewResultSchema reads the pinned schema and extracts the constraints +// from it, so the test cannot accept a category or member the real harness would +// reject. +func loadReviewResultSchema(t *testing.T) reviewResultSchema { + t.Helper() + raw, err := os.ReadFile(reviewResultSchemaPath) + require.NoError(t, err, "the pinned review-result schema must be readable") + + var doc struct { + Properties map[string]json.RawMessage `json:"properties"` + Defs struct { + Finding struct { + Properties map[string]struct { + Enum []string `json:"enum"` + } `json:"properties"` + } `json:"finding"` + } `json:"$defs"` + } + require.NoError(t, json.Unmarshal(raw, &doc), "the pinned review-result schema must decode") + + schema := reviewResultSchema{topLevel: map[string]bool{}, findingMembers: map[string]bool{}} + for key := range doc.Properties { + schema.topLevel[key] = true + } + for key := range doc.Defs.Finding.Properties { + schema.findingMembers[key] = true + } + + var action struct { + Enum []string `json:"enum"` + } + require.NoError(t, json.Unmarshal(doc.Properties["action"], &action)) + schema.actions = action.Enum + + findingProps := doc.Defs.Finding.Properties + schema.severities = findingProps["severity"].Enum + schema.categories = findingProps["category"].Enum + require.NotEmpty(t, schema.actions, "action enum must be present in the schema") + require.NotEmpty(t, schema.severities, "severity enum must be present in the schema") + require.NotEmpty(t, schema.categories, "category enum must be present in the schema") + return schema +} + +// assertReviewResultSchemaValid checks doc against the review-result schema +// constraints sanitization can break. A review the harness rejects is not posted, +// which is the #5705 outcome, so a fixture that survives sanitization has to still +// satisfy these. +func assertReviewResultSchemaValid(t *testing.T, doc []byte) { + t.Helper() + schema := loadReviewResultSchema(t) + + var result map[string]json.RawMessage + require.NoError(t, json.Unmarshal(doc, &result), "sanitized review must decode: %s", doc) + + for key := range result { + assert.True(t, schema.topLevel[key], "unexpected top-level member %q", key) + } + + var action string + require.NoError(t, json.Unmarshal(result["action"], &action), "action is required") + assert.Contains(t, schema.actions, action, "action must be one of the schema enums") + + var repo string + require.NoError(t, json.Unmarshal(result["repo"], &repo), "repo is required") + assert.Regexp(t, `^[a-zA-Z0-9._-]+(/[a-zA-Z0-9._-]+)+$`, repo, "repo must match the schema pattern") + + var prNumber int + require.NoError(t, json.Unmarshal(result["pr_number"], &prNumber), "pr_number is required") + assert.Positive(t, prNumber, "pr_number must be at least 1") + + if action == "comment" || action == "approve" || action == "request-changes" || action == "reject" { + var headSHA, body string + require.NoError(t, json.Unmarshal(result["head_sha"], &headSHA), "%s requires head_sha", action) + require.NoError(t, json.Unmarshal(result["body"], &body), "%s requires body", action) + assert.Regexp(t, `^[0-9a-fA-F]{40}$|^[0-9a-fA-F]{64}$`, headSHA, "head_sha must match the schema pattern") + assert.NotEmpty(t, body, "body must be at least one character") + } + + rawFindings, hasFindings := result["findings"] + if !hasFindings { + assert.NotContains(t, []string{"request-changes", "reject"}, action, "%s requires findings", action) + return + } + var findings []map[string]json.RawMessage + require.NoError(t, json.Unmarshal(rawFindings, &findings), "findings must be an array of objects") + require.NotEmpty(t, findings, "findings must not be empty") + + for i, finding := range findings { + for key := range finding { + assert.True(t, schema.findingMembers[key], "finding %d has unexpected member %q", i, key) + } + var severity, category, file, description string + require.NoError(t, json.Unmarshal(finding["severity"], &severity), "finding %d requires severity", i) + require.NoError(t, json.Unmarshal(finding["category"], &category), "finding %d requires category", i) + require.NoError(t, json.Unmarshal(finding["file"], &file), "finding %d requires file", i) + require.NoError(t, json.Unmarshal(finding["description"], &description), "finding %d requires description", i) + assert.Contains(t, schema.severities, severity, "finding %d severity must be one of the schema enums", i) + assert.Contains(t, schema.categories, category, "finding %d category must be one of the schema enums", i) + assert.NotEmpty(t, file, "finding %d file must be at least one character", i) + assert.NotEmpty(t, description, "finding %d description must be at least one character", i) + } +} + +// 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, +// which is the scan that cannot guarantee JSON syntax stays intact (#5705). +func TestSanitizeJSONDocument_KeepsBOM(t *testing.T) { + p := OutputPipeline() + bom := []byte("\ufeff") + + clean := append(append([]byte{}, bom...), []byte(`{"verdict":"approve"}`)...) + out, findings, err := SanitizeJSONDocument(clean, p) + require.NoError(t, err) + assert.Empty(t, findings) + assert.Equal(t, clean, out, "a clean BOM-prefixed document must be returned unchanged") + + dirty := append(append([]byte{}, bom...), []byte(`{"token":"ghp_FAKEtesttoken000000000000000000000000"}`)...) + out, findings, err = SanitizeJSONDocument(dirty, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, bytes.HasPrefix(out, bom), "the BOM must survive the rewrite: %q", out) + assert.True(t, json.Valid(bytes.TrimPrefix(out, bom)), "sanitized document must stay valid JSON: %s", out) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") +} + +// TestOutputRemoval_NoPlainTextReason pins that the plain-text marker the CLI no +// longer writes is not a recognized reason. A document that parses as JSON takes +// the structural path, so every remaining fail-closed reason is structural. +func TestOutputRemoval_NoPlainTextReason(t *testing.T) { + reason, removed := OutputRemoval([]byte(`{"error":"output removed because text redaction would invalidate JSON"}`)) + assert.False(t, removed, "the removed plain-text marker must not be recognized") + assert.Empty(t, reason) +} + +// TestSanitizeJSONDocument_NormalizedSensitiveKeyMasksValue pins that a +// sensitive key obfuscated with a zero-width or fullwidth character is still +// recognized after sanitizeJSONKey writes its normalized spelling. Deciding +// sensitivity on the original key produced an explicit "password" field with an +// untouched opaque value, and the whole-value rescan does not apply json_field +// (#5705). +func TestSanitizeJSONDocument_NormalizedSensitiveKeyMasksValue(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"pass\u200bword":"opaque-value-12345","password":"another-opaque-1"}`) + + 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), "opaque-value-12345", "a normalized sensitive key must mask its value") + assert.NotContains(t, string(out), "another-opaque-1", "a compatibility-obfuscated sensitive key must mask its value") + assert.Contains(t, string(out), `"password":`, "the normalized key is written") +} + +// TestSanitizeJSONLines_NormalizedSensitiveKeyMasksValue is the JSONL half: a +// record whose sensitive key is obfuscated must still mask its value. +func TestSanitizeJSONLines_NormalizedSensitiveKeyMasksValue(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"pass\\u200bword\":\"opaque-value-12345\"}\n" + + "{\"event\":\"clean\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "opaque-value-12345") + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 2, "record count must not change") + assert.Equal(t, `{"event":"clean"}`, lines[1], "a clean record must survive") +} + +// TestSanitizeJSONDocument_AuthorPathExemption pins that the structural path +// honours the #9944 exemption the text scan applies: an "author" member holding a +// codex agent path is not a credential, even though "author" contains "auth". +func TestSanitizeJSONDocument_AuthorPathExemption(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"author":"/root/agent_one/child","messages":[{"author":"/root/agent_one/child"}]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + assert.Empty(t, findings, "a codex agent path under author is exempt") + assert.Equal(t, string(doc), string(out), "an exempt document must be returned unchanged") +} + +// TestSanitizeJSONLines_AuthorPathExemption is the JSONL half of the #9944 +// exemption: a codex transcript record is a JSON document and takes the +// structural path. +func TestSanitizeJSONLines_AuthorPathExemption(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"author\":\"/root/agent_one/child\"}\n" + + "{\"author\":\"/root/agent_two/child\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.Empty(t, findings, "codex agent paths under author are exempt") + assert.Equal(t, string(content), string(out), "an exempt stream must be returned unchanged") +} + +// TestSanitizeJSONDocument_MaskShapedRealSecretStillMasked pins that a real short +// credential that happens to look like a mask placeholder is still masked when it +// is the original value. isAlreadyMasked is only trusted for a value this scan +// rewrote; otherwise an eight-character password ending in "..." and a backslash +// was written back unchanged (#5705). +func TestSanitizeJSONDocument_MaskShapedRealSecretStillMasked(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"password":"abcd...\\"}`) + + 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), "abcd...", "a real secret shaped like a placeholder must still be masked") +} + +// TestSanitizeJSONDocument_BodyChunksSplitAcrossObjectKeysMasked pins the +// regression a reviewer found: a PEM body split into short chunks stored in +// separate object members lost its markers but kept every chunk, because each +// intervening key flushed the joined-run test. Object keys are structure and never +// join the run, but they must not break it either (#5705). +func TestSanitizeJSONDocument_BodyChunksSplitAcrossObjectKeysMasked(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"` + begin + `":"MIIEowIB","k1":"AAKCAQEA","k2":"x9Kq2Lm","` + end + `":"tail"}`) + + 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 _, chunk := range []string{"MIIEowIB", "AAKCAQEA", "x9Kq2Lm"} { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } + assert.NotContains(t, string(out), "BEGIN RSA") + assert.NotContains(t, string(out), "END RSA") +} + +// TestSanitizeJSONDocument_ShortFragmentAfterBodyLineMasked pins that a recognized +// body line does not end the run: a short final fragment beside it must be masked +// too, or it survives once the markers are gone (#5705). +func TestSanitizeJSONDocument_ShortFragmentAfterBodyLineMasked(t *testing.T) { + p := OutputPipeline() + longLine := "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + doc := []byte(`{"a":"` + pemBegin + `","b":"` + longLine + `","c":"AQAB","d":"` + pemEnd + `"}`) + + 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), longLine) + assert.NotContains(t, string(out), "AQAB", "a short fragment beside a body line must not survive") +} + +// TestSanitizeJSONDocument_PrefixedBodyFragmentsMasked pins that body fragments +// embedded in surrounding text are masked. The "part:" prefix and the whitespace +// used to break the run, so each 8-character fragment stayed below the material +// floor and survived after the markers were masked (#5705). +func TestSanitizeJSONDocument_PrefixedBodyFragmentsMasked(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"a":"` + pemBegin + `","b":"part: MIIEowIB","c":"part: AAKCAQEA","d":"` + pemEnd + `"}`) + + 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), "MIIEowIB", "a prefixed body fragment must not survive") + assert.NotContains(t, string(out), "AAKCAQEA", "a prefixed body fragment must not survive") +} + +// TestSanitizeJSONDocument_BodyChunksWithLineFramingMasked pins that a body split +// into short chunks that each carry the newline that ended the line is still +// masked. The whitespace is line framing, not body: it must not break the joined +// run, where each chunk on its own is below the material floor (#5705). +func TestSanitizeJSONDocument_BodyChunksWithLineFramingMasked(t *testing.T) { + p := OutputPipeline() + chunks := []string{`MIIEowIB\n`, `AAKCAQEA\n`, `x9Kq2Lm0\n`} + quoted := []string{`"` + pemBegin + `"`} + for _, chunk := range chunks { + quoted = append(quoted, `"`+chunk+`"`) + } + quoted = append(quoted, `"`+pemEnd+`"`) + doc := []byte(`{"lines":[` + strings.Join(quoted, ",") + `]}`) + + 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-----") + for _, chunk := range []string{"MIIEowIB", "AAKCAQEA", "x9Kq2Lm0"} { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } +} + +// TestSanitizeJSONLines_SchemaFieldsBetweenQuotedMarkersKept is the record-level +// 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( + `{"note":"` + pemBegin + `"}` + "\n" + + `["MII","Eow","IB","AAK","CAQ","EA"]` + "\n" + + `{"note":"` + pemEnd + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + for _, chunk := range []string{"MII", "Eow", "IB", "AAK", "CAQ", "EA"} { + assert.NotContains(t, string(out), `"`+chunk+`"`, "a short body chunk must not survive") + } + 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 replaced record must stay valid JSON: %s", line) + } +} + +// TestSanitizeJSONLines_ShortFragmentAfterBodyLineCovered is the record-level half +// of TestSanitizeJSONDocument_ShortFragmentAfterBodyLineMasked: a short fragment +// beside a recognized body line must be covered with it (#5705). +func TestSanitizeJSONLines_ShortFragmentAfterBodyLineCovered(t *testing.T) { + p := OutputPipeline() + longLine := "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + content := []byte( + `{"note":"` + pemBegin + `"}` + "\n" + + `{"line":"` + longLine + `"}` + "\n" + + `{"tail":"AQAB"}` + "\n" + + `{"note":"` + pemEnd + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), longLine) + assert.NotContains(t, string(out), "AQAB", "a short fragment beside a body line must not survive") + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + } +} + +// TestSanitizeJSONLines_PrefixedBodyFragmentsCovered is the record-level half of +// TestSanitizeJSONDocument_PrefixedBodyFragmentsMasked (#5705). +func TestSanitizeJSONLines_PrefixedBodyFragmentsCovered(t *testing.T) { + p := OutputPipeline() + content := []byte( + `{"note":"` + pemBegin + `"}` + "\n" + + `{"part":"part: MIIEowIB"}` + "\n" + + `{"part":"part: AAKCAQEA"}` + "\n" + + `{"note":"` + pemEnd + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "MIIEowIB", "a prefixed body fragment must not survive") + assert.NotContains(t, string(out), "AAKCAQEA", "a prefixed body fragment must not survive") + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + } +} + +// TestSanitizeJSONLines_BodyChunksWithLineFramingCovered is the record-level half +// of TestSanitizeJSONDocument_BodyChunksWithLineFramingMasked: each middle record +// holds a short body chunk together with the newline that ended the line, and the +// framing must not stop the chunks from being joined and masked (#5705). +func TestSanitizeJSONLines_BodyChunksWithLineFramingCovered(t *testing.T) { + p := OutputPipeline() + content := []byte( + `{"note":"` + pemBegin + `"}` + "\n" + + `["MIIEowIB\n","AAKCAQEA\n","x9Kq2Lm0\n"]` + "\n" + + `{"note":"` + pemEnd + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + for _, chunk := range []string{"MIIEowIB", "AAKCAQEA", "x9Kq2Lm0"} { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } + 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 replaced record must stay valid JSON: %s", line) + } +} + +// TestSanitizeJSONLines_BodyChunksSplitAcrossObjectKeysCovered is the JSONL half: +// a middle record whose body chunks are stored in separate object members must be +// replaced once the chunks are joined across the intervening keys. +func TestSanitizeJSONLines_BodyChunksSplitAcrossObjectKeysCovered(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte( + "{\"" + begin + "\":1}\n" + + "{\"a\":\"MIIEowIB\",\"b\":\"AAKCAQEA\",\"c\":\"x9Kq2Lm\"}\n" + + "{\"" + end + "\":2}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + for _, chunk := range []string{"MIIEowIB", "AAKCAQEA", "x9Kq2Lm"} { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } + 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 replaced record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// The error return of SanitizeJSONDocument and SanitizeJSONLines is only +// reachable on a decoder limit after IsJSONDocument has accepted the bytes, and +// no input produces one: json.Valid and the token decoder share the same limits, +// so a document the decoder rejects is rejected before the structural path and +// falls back to the text scan. The wrap text ("could not sanitize JSON document" +// / "could not sanitize JSONL record") is therefore pinned at the CLI layer by +// TestScanOutputFiles_SanitizerErrorContainsFileAndContinues, which injects the +// error through the sanitizer parameter rather than depending on a natural +// trigger. diff --git a/internal/security/redactor.go b/internal/security/redactor.go index 9941deee98..d3ad4e157e 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -7,6 +7,7 @@ import ( "slices" "strings" "sync" + "unicode/utf8" ) // Runtime secrets are exact credential values the runner learned during @@ -17,6 +18,12 @@ import ( // trivial string can never blank out ordinary output. const minRuntimeSecretLen = 8 +// minJSONFieldLen is the shortest value masked as a json_field. It is counted in +// runes, matching the {8,} quantifier the json_field value used before the +// pattern was widened to span escaped quotes inside a JSON string. The other +// structural patterns enforce their own minimum in the pattern itself. +const minJSONFieldLen = 8 + var ( runtimeSecretsMu sync.RWMutex runtimeSecrets []string @@ -63,6 +70,13 @@ func resetRuntimeSecrets() { runtimeSecrets = nil } +// ResetRuntimeSecretsForTest clears the registry. It is exported because tests +// outside this package (internal/cli drives the output scan end to end) need a +// clean registry; the tests in this package call resetRuntimeSecrets directly. +func ResetRuntimeSecretsForTest() { + resetRuntimeSecrets() +} + // SecretRedactor scans text for API keys, tokens, credentials, and // sensitive patterns, replacing them with masked versions. Adapted from // Hermes Agent's agent/redact.py. @@ -87,6 +101,21 @@ func NewSecretRedactor() *SecretRedactor { func (s *SecretRedactor) Name() string { return "secret_redactor" } func (s *SecretRedactor) Scan(text string) ScanResult { + return s.scan(text, false) +} + +// ScanWholeValueSecrets masks only the secrets whose match is the entire value: +// registered runtime values and private-key blocks. It is meant for bytes a leaf +// scan has already redacted, where a pattern match can be a redaction +// placeholder plus JSON escape characters rather than a new secret (#5705). +func (s *SecretRedactor) ScanWholeValueSecrets(text string) ScanResult { + return s.scan(text, true) +} + +// scan runs the pattern set. wholeValueOnly restricts it to the patterns whose +// match is the whole secret, which are the only ones that can still be present +// in bytes an earlier pass already redacted. +func (s *SecretRedactor) scan(text string, wholeValueOnly bool) ScanResult { result := ScanResult{Safe: true, Sanitized: text} current := text @@ -110,29 +139,37 @@ func (s *SecretRedactor) Scan(text string) ScanResult { // Prefix-based patterns (full match is the secret). // Use ReplaceAll to catch duplicate occurrences of the same secret. - for _, p := range s.prefixPatterns { - // Deduplicate matches so we report each unique secret once. - seen := map[string]bool{} - matches := p.regex.FindAllString(current, -1) - for _, match := range matches { - if seen[match] { - continue + if !wholeValueOnly { + for _, p := range s.prefixPatterns { + // Deduplicate matches so we report each unique secret once. + seen := map[string]bool{} + matches := p.regex.FindAllString(current, -1) + for _, match := range matches { + if seen[match] { + continue + } + seen[match] = true + masked := Mask(match) + result.Findings = append(result.Findings, Finding{ + Scanner: "secret_redactor", + Name: p.name, + Severity: "critical", + Detail: fmt.Sprintf("Redacted %s (%d chars) -> %s", p.name, len(match), masked), + }) + current = strings.ReplaceAll(current, match, masked) + result.Safe = false } - seen[match] = true - masked := mask(match) - result.Findings = append(result.Findings, Finding{ - Scanner: "secret_redactor", - Name: p.name, - Severity: "critical", - Detail: fmt.Sprintf("Redacted %s (%d chars) -> %s", p.name, len(match), masked), - }) - current = strings.ReplaceAll(current, match, masked) - result.Safe = false } } - // Structural patterns (capture group is the secret) + // Structural patterns (capture group is the secret). Only the private-key + // block is safe to match in whole-value mode: every other pattern captures a + // value out of surrounding text, so a match on bytes that already carry a + // redaction placeholder can be that placeholder rather than a secret. for _, p := range s.structuralPatterns { + if wholeValueOnly && p.name != "private_key" { + continue + } // Private key: replace full match (no capture group needed). if p.name == "private_key" { matches := p.regex.FindAllString(current, -1) @@ -176,7 +213,46 @@ func (s *SecretRedactor) Scan(text string) ScanResult { if p.name == "json_field" && isExemptJSONField(current, loc[0], loc[1], secret) { continue } - masked := mask(secret) + // If the matched secret ends with a backslash and is immediately + // followed by a quote delimiter, the trailing backslash was escaping + // that delimiter (e.g. \" in JSON or code strings). Preserve the + // escape by excluding the backslash from the redacted secret span. + // json_field spans escaped quotes in its own value pattern, so its + // capture already ends at the delimiter it belongs to. + if p.name != "json_field" && end < len(current) && (current[end] == '"' || current[end] == '\'') { + numBackslashes := 0 + for k := len(secret) - 1; k >= 0 && secret[k] == '\\'; k-- { + numBackslashes++ + } + if numBackslashes%2 == 1 { + secret = secret[:len(secret)-1] + end-- + } + } + if len(secret) == 0 { + continue + } + // A captured value is always masked, even when it already looks + // like a mask. The shape of a placeholder (4 characters and "...", + // or "***") is also the shape of a real short secret: + // db_connection_password accepts a value of 4 characters or more, + // so skipping every 7-byte capture that ends in "..." left a real + // password such as postgres://u:abcd...@host in the output. Callers + // that rescan bytes an earlier pass already redacted use + // ScanWholeValueSecrets, which runs no value pattern, so they never + // reach this loop; a full Scan over redacted text can therefore + // only be re-masking a placeholder into "***", never a secret into + // itself. + // + // Only json_field needs the length gate here: its value pattern + // matches any length, while env_assignment, auth_header and + // db_connection_password enforce their own minimum in the pattern. + // The gate counts runes and runs on the trimmed span, so the bytes + // actually masked are never shorter than the documented minimum. + if p.name == "json_field" && utf8.RuneCountInString(secret) < minJSONFieldLen { + continue + } + masked := Mask(secret) result.Findings = append(result.Findings, Finding{ Scanner: "secret_redactor", Name: p.name, @@ -200,7 +276,7 @@ func (s *SecretRedactor) Scan(text string) ScanResult { // authorPathValue matches the author values the json_field rule leaves // unmasked: an absolute path of at least 10 bytes made only of letters, // digits, '_', '.', '/' and '-'. Such a value has no quote, colon, -// whitespace, backslash or '@', and mask would keep its first four bytes, +// whitespace, backslash or '@', and Mask would keep its first four bytes, // so the patterns that run after json_field match the same text whether // the value is kept or masked. Codex agent paths (/root, /morpheus, or // /root/ plus /-separated names of [a-z0-9_]) of 10 or more bytes qualify; @@ -237,11 +313,41 @@ func isExemptJSONField(text string, matchStart, matchEnd int, secret string) boo return authorPathValue.MatchString(secret) && isExemptJSONKey(text[matchStart:matchEnd]) } -func mask(value string) string { +// Mask returns a redacted representation of a secret value. +// +// The returned text is safe to splice into a JSON or YAML string value, but not +// into arbitrary byte ranges: it keeps the first four bytes unless they contain +// an escape or a quote delimiter, in which case it returns "***". Callers that +// write it back must place it inside a string literal (writeJSONString does this +// for the structural path); a caller that rebuilds raw framing must re-escape +// the surrounding text itself. +func Mask(value string) string { if len(value) < 10 { return "***" } - return value[:4] + "..." + prefix := value[:4] + // A prefix that carries an escape or a quote delimiter cannot be written + // back: in a JSON or YAML string it would escape or close the surrounding + // quoting and break the document (#5705). The quote case covers a YAML + // single-quoted value whose doubled quote ('') falls inside the prefix: + // keeping half of the pair leaves a lone quote that ends the string early. + if strings.ContainsAny(prefix, "\\'\"") { + return "***" + } + return prefix + "..." +} + +// isAlreadyMasked reports whether value is already a redaction placeholder +// produced by Mask. Trailing backslashes are ignored: a placeholder that sits in +// a JSON string can be followed by escape characters once the string is +// re-encoded, and that tail must not turn the placeholder into a new secret +// (#5705). +// +// Only callers that know the value came from Mask may use this. The shape alone +// cannot tell a placeholder from a real short secret, so Scan does not apply it. +func isAlreadyMasked(value string) bool { + value = strings.TrimRight(value, `\`) + return value == "***" || len(value) == 7 && strings.HasSuffix(value, "...") } func defaultPrefixPatterns() []secretPattern { @@ -297,7 +403,28 @@ func defaultStructuralPatterns() []secretPattern { // the mask keeps it visible. A bare value still ends at the first // space, as in the PostToolUse hook. {"env_assignment", `(?i)(?:^|\s)(?:export\s+)?((?:[A-Za-z0-9]+_)*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|PASSWD|AUTH|API_KEY)(?:_[A-Za-z0-9]+)*)\s*=\s*(?:['"](?:(?:basic|bearer|token)[ \t]+)?)?([^\s"'}\]),;]{8,})['"]?`}, - {"json_field", `(?:"[^"]*(?i:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?i:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"([^"]{8,})"|'([^']{8,})')`}, + // json_field captures a value out of a quoted field. The double-quoted + // branch and the second single-quoted branch consume escaped delimiters, so + // a JSON or YAML string with an embedded quote is matched whole. The first + // single-quoted branch covers a value that ends in a literal backslash, + // where that backslash must not escape the closing quote; it comes first + // because Go's regexp alternation is leftmost-first, so the escape-reading + // branch would otherwise match first and read the closing quote of + // 'api_key': 'secret\' in a YAML flow mapping as an escape, running on to + // the next quote on the same line and swallowing the field that follows. + // That branch therefore matches only when the quote after the backslash is + // followed by a field or line boundary. The strict double-quoted branch + // stops at a raw newline, so a JSON value ending in \" cannot run on to the + // next line's quote and swallow the field there (#9944). A double-quoted + // value that ends in a literal backslash right before its closing quote + // needs the same bounded fallback the single-quoted branch has, and a + // value folded across physical lines (a YAML or log string, not JSON) still + // needs to be matchable when its closing quote ends the field or the line: + // that last branch allows raw newlines but only at that boundary, so it + // cannot run on to a later field's quote. The single-quoted branch keeps a + // raw newline inside the value matchable, as it was before the escape + // handling was added. The minimum length is enforced in scan, not here. + {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\[\s\S]|[^"\\\r\n])*)"|"([^"\r\n]*\\)"[ \t]*(?:,|\}|\]|$)|'((?:''|[^'\r\n])*\\)'[ \t]*(?:,|\}|\]|$)|'((?:''|\\\r?\n|\\.|[^'\r\n\\])*[^'\r\n\\])'|'([^']*)'|"((?:\\[\s\S]|[^"\\])*)"[ \t]*(?:,|\}|\]|$))`}, // The optional quote covers YAML: authorization: "Bearer ". {"auth_header", `(?i)(?:Authorization|X-Api-Key|X-Auth-Token)\s*:\s*['"]?(?:(?:Basic|Bearer|Token)\s+)?([^\s"'}\]),;]{12,})`}, {"private_key", `-----BEGIN\s+(?:RSA\s+|EC\s+|OPENSSH\s+)?PRIVATE KEY-----[\s\S]*?-----END\s+(?:RSA\s+|EC\s+|OPENSSH\s+)?PRIVATE KEY-----`}, diff --git a/internal/security/scanner.go b/internal/security/scanner.go index a793cdee5c..e1df3743fd 100644 --- a/internal/security/scanner.go +++ b/internal/security/scanner.go @@ -79,6 +79,42 @@ func (p *Pipeline) Scan(text string) ScanResult { return aggregate } +// wholeValueScanner masks only the secrets whose match is the entire value. +// Pipeline.ScanWholeValueSecrets uses it to rescan bytes an earlier pass has +// already redacted without mistaking a redaction placeholder for a secret. +type wholeValueScanner interface { + ScanWholeValueSecrets(text string) ScanResult +} + +// ScanWholeValueSecrets runs only the whole-value masking of the pipeline's +// scanners: registered runtime values and private-key blocks. Normalizers and +// value patterns are skipped, because the leaf scan has already applied them to +// the decoded document, and re-running them over serialized bytes can only +// damage the redactions they produced (#5705). +func (p *Pipeline) ScanWholeValueSecrets(text string) ScanResult { + aggregate := ScanResult{Safe: true, Sanitized: text} + current := text + for _, s := range p.scanners { + w, ok := s.(wholeValueScanner) + if !ok { + continue + } + result := w.ScanWholeValueSecrets(current) + aggregate.Findings = append(aggregate.Findings, result.Findings...) + if !result.Safe { + aggregate.Safe = false + } + if result.Sanitized != "" { + current = result.Sanitized + aggregate.Sanitized = current + } + } + if aggregate.Sanitized == text { + aggregate.Sanitized = "" // no changes + } + return aggregate +} + // InputPipeline returns the standard input scanning pipeline for // untrusted text entering the agent. Order matters: // 1. UnicodeNormalizer — strip invisible chars, normalize fullwidth diff --git a/internal/security/scanner_test.go b/internal/security/scanner_test.go index 0399ad60fd..8564b6ef33 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -2,6 +2,7 @@ package security import ( "encoding/json" + "fmt" "strings" "testing" @@ -261,6 +262,40 @@ func TestSecretRedactor(t *testing.T) { assert.True(t, result.Safe || !hasFinding(result, "db_connection_password")) }) + // A real password can look like a mask placeholder: the placeholder shape + // (4 characters and "...") is 7 bytes, and db_connection_password accepts a + // value of 4 or more, so a shape test in the redactor skipped it and left + // the password in the output (#5705). + t.Run("db password shaped like a mask placeholder redacted", func(t *testing.T) { + result := r.Scan("postgres://user:abcd...@host:5432/db") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "db_connection_password")) + assert.Equal(t, "postgres://user:***@host:5432/db", result.Sanitized) + }) + + // Rescanning redacted text with a full Scan re-masks the placeholder: a + // seven-byte placeholder is shorter than ten, so Mask returns "***". The + // text stays redacted; only the informative prefix is lost. Callers that + // rescan bytes an earlier pass redacted use ScanWholeValueSecrets, which + // runs no value pattern and leaves the placeholder alone. + t.Run("db password placeholder remasked on a full rescan", func(t *testing.T) { + first := r.Scan("postgres://user:hunter2secret@host:5432/db") + require.False(t, first.Safe) + require.Equal(t, "postgres://user:hunt...@host:5432/db", first.Sanitized) + + second := r.Scan(first.Sanitized) + assert.Equal(t, "postgres://user:***@host:5432/db", second.Sanitized, + "a placeholder is still redacted, never left as itself") + assert.False(t, second.Safe) + }) + + t.Run("whole-value rescan leaves a placeholder intact", func(t *testing.T) { + const redacted = "postgres://user:hunt...@host:5432/db" + result := r.ScanWholeValueSecrets(redacted) + assert.True(t, result.Safe) + assert.Empty(t, result.Sanitized, "the earlier redaction must survive a whole-value rescan") + }) + t.Run("db password with multiple @ redacted", func(t *testing.T) { result := r.Scan("postgres://user:P@ss@w0rd@host:5432/db") assert.False(t, result.Safe) @@ -382,6 +417,269 @@ func TestSecretRedactor(t *testing.T) { assert.True(t, json.Valid([]byte(result.Sanitized)), "output is not valid JSON: %s", result.Sanitized) }) + + t.Run("env assignment does not eat escaping backslash in JSON string", func(t *testing.T) { + // Regression test (#5705): [^\s"'}\]),;]{8,} previously consumed \ + // inside JSON string values before an escaped quote, leaving unescaped + // quote syntax like token_usage = metr..."token_usage"). + tokenVar := "token" + "_usage" + input := fmt.Sprintf(`{"remediation": "Guard against null values with %s = metrics.get(\"token_usage\") or {}"}`, tokenVar) + result := r.Scan(input) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "env_assignment")) + assert.True(t, json.Valid([]byte(result.Sanitized)), + "output must remain valid JSON: %s", result.Sanitized) + assert.Contains(t, result.Sanitized, `\"token_usage\"`) + }) + + t.Run("env assignment redacts credentials containing backslashes", func(t *testing.T) { + result := r.Scan(`TOKEN=ab\cdEFGHijkl`) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "env_assignment")) + assert.NotContains(t, result.Sanitized, `ab\cdEFGHijkl`) + + // Boundary test: exactly 8 characters containing multiple backslashes + resultBoundary := r.Scan(`TOKEN=a\b\c\def`) + assert.False(t, resultBoundary.Safe) + assert.True(t, hasFinding(resultBoundary, "env_assignment")) + assert.NotContains(t, resultBoundary.Sanitized, `a\b\c\def`) + + // Trailing backslash before boundary + resultTrailing := r.Scan(`TOKEN=abcdefg\`) + assert.False(t, resultTrailing.Safe) + assert.True(t, hasFinding(resultTrailing, "env_assignment")) + assert.NotContains(t, resultTrailing.Sanitized, `abcdefg\`) + + // Exact-minimum-length boundary tests (8 chars) ending in backslash before quote delimiters + resultSingleQuote := r.Scan("TOKEN='abcdefg\\'") + assert.False(t, resultSingleQuote.Safe) + assert.True(t, hasFinding(resultSingleQuote, "env_assignment")) + assert.NotContains(t, resultSingleQuote.Sanitized, "abcdefg") + assert.Contains(t, resultSingleQuote.Sanitized, `\'`) + + resultDoubleQuote := r.Scan(`TOKEN="abcdefg\""`) + assert.False(t, resultDoubleQuote.Safe) + assert.True(t, hasFinding(resultDoubleQuote, "env_assignment")) + assert.NotContains(t, resultDoubleQuote.Sanitized, "abcdefg") + assert.Contains(t, resultDoubleQuote.Sanitized, `\"`) + }) + + t.Run("db connection redacts password containing backslashes", func(t *testing.T) { + result := r.Scan(`postgres://user:pa\ss@host:5432/db`) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "db_connection_password")) + assert.NotContains(t, result.Sanitized, `pa\ss`) + + // Boundary test: exactly 4 characters containing interior backslash + resultInterior := r.Scan(`postgres://user:p\ss@host:5432/db`) + assert.False(t, resultInterior.Safe) + assert.True(t, hasFinding(resultInterior, "db_connection_password")) + assert.NotContains(t, resultInterior.Sanitized, `p\ss`) + + // Boundary test: trailing backslash before delimiter @ + resultTrailing := r.Scan(`postgres://user:p\s\@host:5432/db`) + assert.False(t, resultTrailing.Safe) + assert.True(t, hasFinding(resultTrailing, "db_connection_password")) + assert.NotContains(t, resultTrailing.Sanitized, `p\s\`) + }) + + t.Run("auth header redacts credentials containing backslashes", func(t *testing.T) { + result := r.Scan(`Authorization: Bearer ab\cdEFGHijkl1234`) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "auth_header")) + assert.NotContains(t, result.Sanitized, `ab\cdEFGHijkl1234`) + + // Boundary test: exactly 12 characters containing multiple backslashes + resultBoundary := r.Scan(`Authorization: Bearer a\b\c\d\e\f\g`) + assert.False(t, resultBoundary.Safe) + assert.True(t, hasFinding(resultBoundary, "auth_header")) + assert.NotContains(t, resultBoundary.Sanitized, `a\b\c\d\e\f\g`) + + // Exact-minimum-length boundary tests (12 chars) ending in backslash before quote delimiters + resAuthSingle := r.Scan("authorization: 'Bearer abcdefghijk\\'") + assert.False(t, resAuthSingle.Safe) + assert.True(t, hasFinding(resAuthSingle, "auth_header")) + assert.NotContains(t, resAuthSingle.Sanitized, "abcdefghijk") + assert.Contains(t, resAuthSingle.Sanitized, `\'`) + + resAuthDouble := r.Scan(`authorization: "Bearer abcdefghijk\""`) + assert.False(t, resAuthDouble.Safe) + assert.True(t, hasFinding(resAuthDouble, "auth_header")) + assert.NotContains(t, resAuthDouble.Sanitized, "abcdefghijk") + assert.Contains(t, resAuthDouble.Sanitized, `\"`) + + resAuthUnprefixedSingle := r.Scan("authorization: 'abcdefghijk\\'") + assert.False(t, resAuthUnprefixedSingle.Safe) + assert.True(t, hasFinding(resAuthUnprefixedSingle, "auth_header")) + assert.NotContains(t, resAuthUnprefixedSingle.Sanitized, "abcdefghijk") + assert.Contains(t, resAuthUnprefixedSingle.Sanitized, `\'`) + + resAuthUnprefixedDouble := r.Scan(`authorization: "abcdefghijk\""`) + assert.False(t, resAuthUnprefixedDouble.Safe) + assert.True(t, hasFinding(resAuthUnprefixedDouble, "auth_header")) + assert.NotContains(t, resAuthUnprefixedDouble.Sanitized, "abcdefghijk") + assert.Contains(t, resAuthUnprefixedDouble.Sanitized, `\"`) + }) + + t.Run("json_field with embedded escaped quote preserves valid JSON", func(t *testing.T) { + input := `{"password": "abcdefghijkl\"rest"}` + result := r.Scan(input) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.True(t, json.Valid([]byte(result.Sanitized)), + "output must remain valid JSON: %s", result.Sanitized) + assert.NotContains(t, result.Sanitized, "abcdefghijkl") + }) + + t.Run("json_field masks backslashes in literal quoted values", func(t *testing.T) { + result := r.Scan(`'password': 'ab\\cdef'`) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, `ab\\cdef`) + }) + + t.Run("json_field handles escaped apostrophe through the full value", func(t *testing.T) { + result := r.Scan(`'password': 'abcdefgh\'remaining_secret'`) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "remaining_secret") + }) + + t.Run("json_field counts literal trailing backslash toward minimum", func(t *testing.T) { + result := r.Scan("'password': 'abcdefg\\'") + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "abcdefg") + }) + + t.Run("json_field redacts a double-quoted value ending in a literal backslash", func(t *testing.T) { + // The strict double-quoted branch reads \" as an escaped quote and then + // needs another quote to close, so a value that ends in one literal + // backslash right before its closing quote matched no branch at all. + // Main's `"([^"]{8,})"` masked it, and a log line can carry a password + // with a trailing backslash (#5705). + result := r.Scan("\"password\": \"Abc123xyzQ\\\"\nnext line\n") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "Abc123xyzQ") + }) + + t.Run("json_field redacts a double-quoted value ending in a literal backslash before a field", func(t *testing.T) { + result := r.Scan(`{"password": "Abc123xyzQ\"}`) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "Abc123xyzQ") + }) + + t.Run("json_field redacts a double-quoted value folded across lines", func(t *testing.T) { + // A YAML or log string can fold a double-quoted value across physical + // lines. The strict branch excludes raw CR/LF, so the value must still be + // matchable when its closing quote ends the field or the line (#5705). + result := r.Scan("\"password\": \"line1\nline2line3\"\nnext line\n") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "line2line3") + }) + + t.Run("json_field handles doubled apostrophe in YAML scalar", func(t *testing.T) { + result := r.Scan("'password': 'abcdefgh''remaining_secret'") + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "remaining_secret") + }) + + t.Run("json_field keeps YAML single-quoted value valid when doubled quote falls in the mask prefix", func(t *testing.T) { + // The mask prefix would end on half of the doubled '' pair, leaving a + // lone quote that closes the YAML string early. The value must fall back + // to the fixed placeholder instead (#5705). + result := r.Scan("'api_token': 'abc''defghijk'") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "defghijk") + assert.Equal(t, "'api_token': '***'", result.Sanitized, + "a prefix carrying a quote must not be written back") + }) + + t.Run("json_field handles backslash followed by physical newline", func(t *testing.T) { + result := r.Scan("'password': 'abcdefgh\\\nijklmnop'") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "ijklmnop") + }) + + t.Run("json_field handles adjacent sensitive YAML fields with trailing backslash", func(t *testing.T) { + input := "'password': 'abcdefgh\\'\n'secret': 'ijklmnop'" + result := r.Scan(input) + assert.False(t, result.Safe) + findings := 0 + for _, f := range result.Findings { + if f.Name == "json_field" { + findings++ + } + } + assert.Equal(t, 2, findings, "both adjacent fields must be detected and redacted") + assert.NotContains(t, result.Sanitized, "abcdefgh") + assert.NotContains(t, result.Sanitized, "ijklmnop") + }) + + t.Run("json_field trailing backslash in a flow mapping keeps the next field", func(t *testing.T) { + // Go's regexp alternation is leftmost-first, so the escape-reading branch + // used to match first and read the closing quote as an escaped quote, + // running on to the next quote on the same line and swallowing the field + // that follows in a YAML flow mapping (#5705). + input := `{'api_key': 'abcdefghi\', 'x': 'yyyyyyyyyyyy'}` + result := r.Scan(input) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "abcdefghi") + assert.Contains(t, result.Sanitized, "'x': 'yyyyyyyyyyyy'", "the field that follows must survive intact") + }) + + t.Run("json_field redacts a single-quoted value spanning a raw newline", func(t *testing.T) { + // Base matched `'([^']{8,})'`, which crosses newlines. Handling escaped + // delimiters must not narrow the pattern: a raw newline inside the + // value is still part of the secret. + result := r.Scan("'password': 'line1\nline2line3'") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "line2line3") + }) + + t.Run("json_field multi-line value does not swallow the next field", func(t *testing.T) { + input := "'password': 'line1\nline2line3'\n'secret': 'ijklmnop'" + result := r.Scan(input) + assert.False(t, result.Safe) + findings := 0 + for _, f := range result.Findings { + if f.Name == "json_field" { + findings++ + } + } + assert.Equal(t, 2, findings, "both fields must be detected and redacted") + assert.NotContains(t, result.Sanitized, "line2line3") + assert.NotContains(t, result.Sanitized, "ijklmnop") + }) + + t.Run("json_field minimum counts runes, not bytes", func(t *testing.T) { + // Three CJK characters are nine bytes. The {8,} quantifier the value + // pattern used before it spanned escaped quotes counted characters, so + // a byte count would start masking values it never masked. + short := r.Scan(`{"password": "秘密の鍵"}`) + assert.True(t, short.Safe, "a value below the minimum must not be masked: %s", short.Sanitized) + + exact := r.Scan(`{"password": "秘密の鍵ですよね"}`) // 8 runes + assert.False(t, exact.Safe) + assert.True(t, hasFinding(exact, "json_field")) + }) + + t.Run("mask does not leave dangling escape sequence", func(t *testing.T) { + input1 := `Authorization: Bearer abc\ndefghijkl` + result1 := r.Scan(input1) + assert.False(t, result1.Safe) + assert.Equal(t, "Authorization: Bearer ***", result1.Sanitized) + + input2 := `Authorization: Bearer \u1234efghijkl` + result2 := r.Scan(input2) + assert.False(t, result2.Safe) + assert.Equal(t, "Authorization: Bearer ***", result2.Sanitized) + }) } func TestSSRFValidator(t *testing.T) { diff --git a/internal/security/testdata/review-result.schema.json b/internal/security/testdata/review-result.schema.json new file mode 100644 index 0000000000..2a41318da4 --- /dev/null +++ b/internal/security/testdata/review-result.schema.json @@ -0,0 +1,208 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "review-result.schema.json", + "title": "Review Agent Result", + "description": "Structured output from the review agent, validated by the harness before the post-script runs (ADR 0022).", + "type": "object", + "additionalProperties": false, + "required": ["action", "pr_number", "repo"], + "properties": { + "action": { + "type": "string", + "enum": ["approve", "request-changes", "comment", "reject", "failure"] + }, + "pr_number": { "type": "integer", "minimum": 1 }, + "repo": { "type": "string", "pattern": "^[a-zA-Z0-9._-]+(/[a-zA-Z0-9._-]+)+$" }, + "head_sha": { "type": "string", "pattern": "^[0-9a-fA-F]{40}$|^[0-9a-fA-F]{64}$" }, + "body": { "type": "string", "minLength": 1 }, + "findings": { + "type": "array", + "items": { "$ref": "#/$defs/finding" }, + "minItems": 1 + }, + "reason": { + "type": "string", + "enum": ["tool-failure", "missing-context", "ambiguous-findings", "token-limit", "time-budget"] + }, + "dispositions": { + "type": "array", + "description": "One entry for every open finding id from the prior projection (status absent, open, or reclassified). Ids already resolved or dismissed by a human are closed and must not be answered. A reclassified entry needs a finding with the same id in findings; a dismissed_by_human entry is accepted only when the post-script verifies a resolved review thread from an eligible reviewer, and never for a high or critical finding. Omit on a first review.", + "items": { "$ref": "#/$defs/disposition" } + }, + "label_actions": { + "$ref": "#/$defs/label_actions" + }, + "risk_assessment": { + "description": "Score and level must be consistent: 1=low, 2=moderate, 3=elevated, 4=high, 5=critical.", + "type": "object", + "required": ["score", "level", "rationale"], + "properties": { + "score": { "type": "integer", "minimum": 1, "maximum": 5 }, + "level": { + "type": "string", + "enum": ["low", "moderate", "elevated", "high", "critical"] + }, + "tier1_signals": { + "type": "array", + "items": { "$ref": "#/$defs/risk_signal" } + }, + "tier2_signals": { + "type": "array", + "items": { "$ref": "#/$defs/risk_signal" } + }, + "tier3_signals": { + "type": "array", + "items": { "$ref": "#/$defs/risk_signal" } + }, + "rationale": { "type": "string", "minLength": 1 }, + "degraded": { "type": "string", "minLength": 1 } + }, + "additionalProperties": false, + "allOf": [ + { "if": { "properties": { "score": { "const": 1 } } }, "then": { "properties": { "level": { "const": "low" } } } }, + { "if": { "properties": { "score": { "const": 2 } } }, "then": { "properties": { "level": { "const": "moderate" } } } }, + { "if": { "properties": { "score": { "const": 3 } } }, "then": { "properties": { "level": { "const": "elevated" } } } }, + { "if": { "properties": { "score": { "const": 4 } } }, "then": { "properties": { "level": { "const": "high" } } } }, + { "if": { "properties": { "score": { "const": 5 } } }, "then": { "properties": { "level": { "const": "critical" } } } } + ] + }, + "risk_gated": { + "type": "boolean", + "description": "Set by post-processing when a risk assessment downgrades the verdict. Not present in agent output — added by the harness post-script." + } + }, + "allOf": [ + { + "if": { "properties": { "action": { "const": "approve" } }, "required": ["action"] }, + "then": { "required": ["body", "head_sha"] } + }, + { + "if": { "properties": { "action": { "const": "request-changes" } }, "required": ["action"] }, + "then": { "required": ["body", "head_sha", "findings"] } + }, + { + "if": { "properties": { "action": { "const": "comment" } }, "required": ["action"] }, + "then": { "required": ["body", "head_sha"] } + }, + { + "if": { "properties": { "action": { "const": "reject" } }, "required": ["action"] }, + "then": { "required": ["body", "head_sha", "findings"] } + }, + { + "if": { "properties": { "action": { "const": "failure" } }, "required": ["action"] }, + "then": { "required": ["reason"] } + }, + { + "if": { + "properties": { "action": { "const": "approve" } }, + "required": ["action"] + }, + "then": { + "not": { + "properties": { + "findings": { + "contains": { + "properties": { "category": { "const": "protected-path" } }, + "required": ["category"] + } + } + }, + "required": ["findings"] + } + } + } + ], + "$defs": { + "finding": { + "type": "object", + "required": ["severity", "category", "file", "description"], + "properties": { + "severity": { "type": "string", "enum": ["critical", "high", "medium", "low", "info"] }, + "category": { + "type": "string", + "description": "Canonical dimension categories (the dimension table in skills/pr-review/references/re-review.md, mirrored by allowed_category in pre-review and post-review) plus the non-dimensional categories. Keep all copies in sync.", + "enum": [ + "logic-error", "nil-deref", "off-by-one", "edge-case", "api-contract", "missing-test", "test-inadequate", "pattern-violation", "test-weakened", "test-removed", "mock-loosened", "assertion-weakened", "coverage-reduced", "test-poisoning", "split-payload", "stale-reference", + "auth-bypass", "rbac-violation", "data-exposure", "privilege-escalation", "injection-vuln", "sandbox-escape", "xss", "ssrf", "insecure-deserialization", "prompt-injection", "unicode-steganography", "bidi-override", "homoglyph-attack", "instruction-smuggling", "fail-open", "permission-expansion", "permission-reduction", "role-escalation", "workflow-permission", "secret-exposure", + "scope-exceeded", "tier-mismatch", "unauthorized-change", "scope-creep", "missing-authorization", "misleading-label", "design-direction", "complexity-ratio", "misplaced-abstraction", "architectural-conflict", "design-smell", "over-engineering", "under-engineering", "scope-bundling", + "naming-convention", "error-handling-idiom", "api-shape", "code-organization", "doc-style", "pattern-inconsistency", + "stale-doc", "missing-doc", "incorrect-doc", "incomplete-doc", + "breaking-api", "breaking-schema", "breaking-config", "breaking-cli", "missing-deprecation", "missing-version-bump", "backward-incompatible", + "uxd-evaluate-code-heuristics", + "protected-path", "provenance-warning", "scope-authorization-implicit", "sub-agent-failure" + ] + }, + "file": { "type": "string", "minLength": 1 }, + "line": { "type": "integer", "minimum": 1 }, + "description": { "type": "string", "minLength": 1 }, + "remediation": { "type": "string" }, + "actionable": { + "type": "boolean", + "description": "When true with a non-empty remediation, routes the verdict to request-changes so the fix agent can address the finding automatically." + }, + "id": { + "type": "string", + "pattern": "^f_[a-zA-Z0-9]+$", + "description": "Stable id copied from the prior projection. Omit on a new finding; the post-script assigns f_ plus random hex. Do not derive it from the file, line, or text." + }, + "dimension": { + "type": "string", + "description": "Name of the pr-review persona that produced the finding. Orchestrator-only findings omit it." + } + }, + "additionalProperties": false + }, + "disposition": { + "type": "object", + "required": ["id", "status", "rationale", "evidence"], + "properties": { + "id": { "type": "string", "pattern": "^f_[a-zA-Z0-9]+$" }, + "status": { + "type": "string", + "enum": ["open", "resolved_by_change", "reclassified", "dismissed_by_human"] + }, + "rationale": { "type": "string", "minLength": 1 }, + "evidence": { + "type": "string", + "description": "Code change or human resolution that supports the status. Empty only for open." + } + }, + "additionalProperties": false + }, + "label_actions": { + "type": "object", + "required": ["reason", "actions"], + "properties": { + "reason": { + "type": "string", + "minLength": 1, + "description": "Single sentence explaining why these labels are being applied or removed" + }, + "actions": { + "type": "array", + "minItems": 1, + "maxItems": 20, + "items": { + "type": "object", + "required": ["action", "label"], + "properties": { + "action": { "type": "string", "enum": ["add", "remove"] }, + "label": { "type": "string", "minLength": 1, "pattern": "^[a-zA-Z0-9._/: +-]+$" } + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "risk_signal": { + "type": "object", + "required": ["dimension", "value"], + "properties": { + "dimension": { "type": "string", "minLength": 1 }, + "value": { "type": "string", "minLength": 1 } + }, + "additionalProperties": false + } + } +} diff --git a/internal/security/testdata/review-result.schema.pin b/internal/security/testdata/review-result.schema.pin new file mode 100644 index 0000000000..c256b91513 --- /dev/null +++ b/internal/security/testdata/review-result.schema.pin @@ -0,0 +1,10 @@ +# Pin for internal/security/testdata/review-result.schema.json. +# +# The vendored review-result schema is a test fixture copied from +# fullsend-ai/agents. Re-vendor the schema and update this pin together whenever +# the upstream schema changes. scripts/check-review-schema-pin.sh compares the +# vendored copy against upstream at the commit below and reports drift, so the +# jsonsanitize tests cannot silently validate against an outdated schema. +repo=fullsend-ai/agents +commit=cec09212b99fcd78bf7afc7637d8fe0b2007e109 +path=schemas/review-result.schema.json