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/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..1cfc33bcf9 --- /dev/null +++ b/internal/security/jsonsanitize.go @@ -0,0 +1,740 @@ +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 a secret spanned multiple records"}` + failClosedUnwritableJSON = `{"error":"output removed because it could not be redacted"}` +) + +// 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"}, + {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) + rebuilt, findings, err := rewriteJSONTokens(trimmed, p) + 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) + } + // Scan the rebuilt form, not the bytes that happened to come in, for the + // whole-value secrets a leaf scan cannot see: a registered runtime value, or + // a private-key block that spans JSON framing and so cannot be mapped back to + // a single leaf. The rebuilt form is the document as the decoder sees it, so + // a marker written as an escape (\u002d for the leading dash of a PEM header) + // reads as the marker here even though the encoded bytes never match. That + // matters most when no leaf produced a finding — a block split across leaves + // has no complete marker in any one of them — so the scan cannot be skipped + // just because the walk found nothing. The original bytes are still what gets + // written when the scan is clean, because re-encoding alone must not rewrite + // a clean file (#5705). + sanitizedOut, outputFindings := redactJSONOutput(rebuilt, p) + if len(findings) == 0 && len(outputFindings) == 0 { + // The rebuilt form compacts whitespace, so it differs from the original + // bytes even when nothing was redacted — and the original is what a clean + // document returns. A registered runtime value that spans JSON framing plus + // whitespace exists only in the original, so the bytes that will actually be + // written need their own scan before the document can be called clean + // (#10082). + sanitizedOut, outputFindings = redactJSONOutput(body, p) + } + findings = append(findings, outputFindings...) + if len(findings) == 0 { + // 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), nil, nil + } + return restoreBOM(doc, preserveTrailingNewline(sanitizedOut, body)), findings, nil +} + +// decodedViewNormalizer normalizes decoded JSON text the same way the per-leaf +// scan does, so a key or value is matched and written back in one spelling: +// invisible characters stripped and compatibility forms folded. +var decodedViewNormalizer = NewUnicodeNormalizer() + +// 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 rebuilt form of a document for secrets that only +// appear in the serialized form. Callers pass the walk's rebuilt document rather +// than the bytes received, so a marker or value written with a JSON escape is +// still seen as the text it decodes to; they write the original bytes instead +// when the scan finds nothing. 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 that survives the leaf walk spans JSON framing, + // so it cannot be masked in place without breaking the document. + if finding.Name == "private_key" { + return []byte(failClosedInvalidJSON), 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) { + var ( + out bytes.Buffer + findings []Finding + spans []recordSpan + ) + 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. + // + // The scan runs on the rebuilt stream as encoded, which is deliberate: a + // value pattern over decoded records already ran in the per-record pass. One + // gap follows from that: a private-key marker written as a JSON escape + // (\u002d----BEGIN) in one record and its END marker in another is not a + // literal -----BEGIN here, so the block is not joined. Closing it needs a + // decoded view of the whole stream, built before any record is rewritten; + // #10084 adds that together with the cross-member case. + 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. 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 +} + +// 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, duplicates included. +// +// The per-record pass has already handled every match a single record could +// account for, so a remaining match spans a record boundary. Localization aligns +// the original records with the redacted stream and treats the records it cannot +// pair up as affected, so two disjoint cross-record matches lose only the records +// they actually cover — the clean records between them survive, duplicates +// included. +// +// Alignment is anchored on the longest run of records that the redacted stream +// still carries verbatim, not on the first one: a later untouched copy of a +// record must not stand in for the copy a match covered, and the run that follows +// the true break is the longer one. When two runs of the same length compete, the +// later original record wins, so a covered record is not paired with a clean +// duplicate further down the stream (see nextAnchor). Records aligned by such a +// run are proven untouched, because their bytes survive in order in the redacted +// stream. +func failClosedRecordSpans(stream []byte, spans []recordSpan, scan ScanResult) []byte { + sanitized := []byte(scan.Sanitized) + if bytes.Equal(stream, sanitized) { + // The scan reported a finding without changing a byte, so no record can + // be shown to be affected and none can be replaced without discarding + // content the scan itself kept. + return stream + } + + original := make([]string, len(spans)) + for i, span := range spans { + original[i] = string(stream[span.start:span.end]) + } + affected := affectedRecords(original, jsonlRecords(sanitized)) + + var out bytes.Buffer + cursor := 0 + for i, span := range spans { + out.Write(stream[cursor:span.start]) + if affected[i] { + out.WriteString(failClosedCrossRecordJSON) + } else { + out.WriteString(original[i]) + } + cursor = span.end + } + out.Write(stream[cursor:]) + return out.Bytes() +} + +// affectedRecords reports, per original record, whether the redacted stream no +// longer carries it verbatim. Records the redaction left alone keep their bytes, +// so they can be paired with their copy in redacted; the records between two +// anchors are the ones a replacement rewrote. +func affectedRecords(original, redacted []string) []bool { + affected := make([]bool, len(original)) + positions := make(map[string][]int, len(redacted)) + for i, record := range redacted { + positions[record] = append(positions[record], i) + } + + budget := anchorSearchBudget + i, j := 0, 0 + for i < len(original) { + if j < len(redacted) && original[i] == redacted[j] { + i++ + j++ + continue + } + k, l, run, ok := nextAnchor(original, redacted, positions, i, j, &budget) + if !ok { + // No anchor left in either stream, so every remaining record was + // rewritten (or cannot be told apart from one that was). + for ; i < len(original); i++ { + affected[i] = true + } + return affected + } + for ; i < k; i++ { + affected[i] = true + } + i += run + j = l + run + } + return affected +} + +// anchorSearchBudget bounds the record comparisons one resynchronization may +// spend, so a stream of many identical records cannot cost O(n²). Running out is +// answered conservatively: the remaining records are treated as affected, because +// a replaced record only loses content while a kept one can leak the bytes a match +// covered. +const anchorSearchBudget = 1 << 16 + +// nextAnchor returns the longest run of consecutive records that survives +// verbatim in both streams at or after the given cursors. On a tie it prefers +// the later original record: when a cross-record match covers one of several +// identical records, the copy the redacted stream still carries is the one +// after the break, so pairing it with an earlier copy would keep the record the +// match covered and replace the clean later one (#10082). +func nextAnchor(original, redacted []string, positions map[string][]int, i, j int, budget *int) (int, int, int, bool) { + bestK, bestL, bestRun := 0, 0, 0 + for k := i; k < len(original); k++ { + for _, l := range positions[original[k]] { + if l < j { + continue + } + run := 0 + for k+run < len(original) && l+run < len(redacted) && original[k+run] == redacted[l+run] { + *budget-- + if *budget < 0 { + return 0, 0, 0, false + } + run++ + } + if run > bestRun || (run == bestRun && run > 0 && k > bestK) { + bestK, bestL, bestRun = k, l, run + } + } + } + if bestRun == 0 { + return 0, 0, 0, false + } + return bestK, bestL, bestRun, true +} + +// jsonlRecords returns the non-blank newline-delimited records of data with +// their CRLF framing removed, matching the byte ranges recordSpan describes. +func jsonlRecords(data []byte) []string { + var records []string + for _, line := range bytes.Split(data, []byte("\n")) { + line = bytes.TrimSuffix(line, []byte("\r")) + if len(bytes.TrimSpace(line)) == 0 { + continue + } + records = append(records, string(line)) + } + return records +} + +// rewriteJSONTokens walks every token in doc, sanitizes each object key and +// scalar value, and renders a valid JSON document. Unlike map decoding it +// keeps member order and duplicate keys, so a secret in an earlier, overwritten +// value is still found. +func rewriteJSONTokens(doc []byte, p *Pipeline) ([]byte, []Finding, error) { + dec := json.NewDecoder(bytes.NewReader(doc)) + dec.UseNumber() + var ( + buf bytes.Buffer + w = &jsonRewrite{pipeline: p} + ) + 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 and the findings +// it has collected. +type jsonRewrite struct { + pipeline *Pipeline + findings []Finding +} + +// writeValue writes one JSON value to buf, sanitizing object keys and scalar +// leaves as it goes. memberKey is the member name that governs the value, so +// sensitive-key masking still applies; it is empty for 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, memberKey) + case string: + 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. memberKey is the name that governs this container as +// a whole. +// +// An array keeps that name for its elements: they are the member's value, so +// "tokens": ["..."] is a list of tokens and each element is masked on the +// member's name. An object does not: its members carry their own names, and +// masking every string inside, say, a "credentials" object would mangle values +// such as an expiry timestamp that the member's name does not govern. +func (w *jsonRewrite) writeContainer(dec *json.Decoder, buf *bytes.Buffer, delim json.Delim, memberKey string) 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) + } + sanitizedKey, keyFindings := sanitizeJSONKey(key, w.pipeline) + 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, memberKey); 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..19f7beb93f --- /dev/null +++ b/internal/security/jsonsanitize_test.go @@ -0,0 +1,1636 @@ +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_ShortBodyChunksMasked pins that a private key whose +// body is split across array members into short chunks is neutralized member by +// member instead of dropping the whole document: no chunk of the body and no +// marker survives (#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_BodyLineAsKeyBetweenMarkersMasked pins that a body +// line used as an object key between BEGIN and END keys is masked as key +// material, and that both marker keys are masked too (#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_EscapedMarkersSplitAcrossLeavesFailsClosed pins that +// a private-key block whose markers are JSON-escaped and split across array +// elements is still detected. No single leaf holds a complete block, so the leaf +// walk reports nothing; the whole-value backstop has to scan the decoded form of +// the document rather than the original escaped bytes, where the marker never +// matches (#5705, #10082). +func TestSanitizeJSONDocument_EscapedMarkersSplitAcrossLeavesFailsClosed(t *testing.T) { + p := OutputPipeline() + const body = "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + // Assembled in pieces so the markers are not a literal PEM header in the + // source: the leading dash of the BEGIN marker is JSON-escaped, which is the + // point of the test. + begin := `\u002d----BEGIN RSA` + ` PRIVATE KEY-----` + end := `-----END RSA` + ` PRIVATE KEY-----` + doc := []byte(`{"lines":["` + begin + `","` + body + `","` + end + `"]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "an escaped block split across leaves must produce a finding") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), body, "key material must not survive") + reason, removed := OutputRemoval(out) + assert.True(t, removed, "an unlocalizable block must fail closed: %s", out) + assert.Equal(t, "redaction would invalidate JSON", reason) +} + +// TestSanitizeJSONLines_EscapedMarkersSplitAcrossLeavesFailsClosed is the JSONL +// counterpart: the escaped markers live in one record, so that record is +// replaced with a valid fail-closed marker and the neighbouring record survives. +func TestSanitizeJSONLines_EscapedMarkersSplitAcrossLeavesFailsClosed(t *testing.T) { + p := OutputPipeline() + const body = "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + begin := `\u002d----BEGIN RSA` + ` PRIVATE KEY-----` + end := `-----END RSA` + ` PRIVATE KEY-----` + record := `{"lines":["` + begin + `","` + body + `","` + end + `"]}` + content := []byte(record + "\n" + `{"status":"ok"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), body, "key material must not survive") + assert.Contains(t, string(out), `{"status":"ok"}`, "a clean record must survive") + assert.Equal(t, []string{"redaction would invalidate JSON"}, OutputRecordRemovals(out)) + for _, line := range bytes.Split(bytes.TrimSpace(out), []byte("\n")) { + assert.True(t, json.Valid(line), "every record must stay valid JSON: %s", line) + } +} + +// TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed pins that a +// runtime secret that only exists across JSON framing is still reported and +// removed, and that the bytes written back are valid JSON (#5705). +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_FramingSecretAcrossWhitespaceFailsClosed pins that a +// registered runtime value that spans JSON framing plus whitespace in the +// original document is still removed. The rebuilt form compacts whitespace, so +// the value exists only in the bytes a clean document writes back, and the +// backstop has to scan those too (#10082). +func TestSanitizeJSONDocument_FramingSecretAcrossWhitespaceFailsClosed(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const secret = `foo", "b":"bar` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + doc := []byte(`{"a":"foo", "b":"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, "the value spanning whitespace must not survive") +} + +// TestSanitizeJSONDocument_DuplicateKeySanitizedKeyCollision pins that a key a +// redaction rewrote is disambiguated when its new name collides with a clean key: +// the clean key keeps its value, the sanitized one moves to "_1", and +// intentional duplicate keys survive the rewrite (#5705). +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") +} + +// TestSanitizeJSONLines_DisjointCrossRecordMatchesKeepCleanRecord pins that 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") + } +} + +// TestSanitizeJSONLines_DisjointCrossRecordMatchesKeepCleanDuplicateRecords +// pins that clean records repeated inside the span of two disjoint cross-record +// matches are kept. A single first-to-last changed region treated everything +// between the matches as affected, so an untouched duplicate was replaced with a +// marker although its bytes were still in the redacted stream. +func TestSanitizeJSONLines_DisjointCrossRecordMatchesKeepCleanDuplicateRecords(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" + + "{\"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, 6, "record count must not change") + assert.Equal(t, `{"clean":"middle"}`, lines[2], "a clean duplicate between two matches must survive") + assert.Equal(t, `{"clean":"middle"}`, lines[3], "every clean duplicate between two matches must survive") + for _, i := range []int{0, 1, 4, 5} { + 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") + } +} + +// TestSanitizeJSONLines_RepeatedRecordCoveredByMatchFailsClosed pins that a +// replacement which covers one copy of a repeated record still removes the +// spanning secret from the stream and keeps the record count, even though the +// copies cannot be told apart. +func TestSanitizeJSONLines_RepeatedRecordCoveredByMatchFailsClosed(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const secret = `{"rep":"same"}` + "\n" + `{"s` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + content := []byte( + "{\"rep\":\"same\"}\n" + + "{\"rep\":\"same\"}\n" + + "{\"s\":\"tail\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), secret) + assert.Len(t, strings.Split(strings.TrimSuffix(string(out), "\n"), "\n"), 3, + "record count must not change") +} + +// TestSanitizeJSONLines_TiedDuplicateKeepsLaterCleanCopy pins that a tied +// alignment does not pair a covered record with an identical clean copy further +// down the stream. nextAnchor used to prefer the earliest original record, so +// the record a cross-record match covered was written back verbatim while the +// clean later duplicate was replaced with a marker (review finding on #10082). +func TestSanitizeJSONLines_TiedDuplicateKeepsLaterCleanCopy(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{\"v\":\"bbb\"}\n{\"v\":\"aaa\"}\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, 3, "record count must not change") + for _, i := range []int{0, 1} { + 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", "a covered record must be replaced: %s", lines[i]) + } + assert.Equal(t, `{"v":"aaa"}`, lines[2], "the clean later duplicate must survive") +} + +// 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}, + "unwritable": {failClosedUnwritableJSON, "it could not be redacted", true}, + "bom prefixed": {"\ufeff" + failClosedCrossRecordJSON, "a secret spanned multiple records", 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" + + failClosedInvalidJSON + "\n" + + failClosedCrossRecordJSON + "\n") + assert.Equal(t, + []string{"a secret spanned multiple records", "redaction would invalidate JSON"}, + 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)) +} + +// TestSanitizeJSONDocument_AlreadyMaskedValueNotRemasked pins that sanitizing a +// document twice changes nothing the second time: a redaction placeholder the +// first pass wrote is not taken for a new secret (#5705). +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_SensitiveKeyMasksArrayElements pins that an array +// under a sensitive member keeps that member's name for its elements. Passing an +// empty key to each element meant a value that matched no pattern of its own was +// written back in clear text: {"tokens": ["supersecretvalue"]} survived intact +// (review finding on #10082). +func TestSanitizeJSONDocument_SensitiveKeyMasksArrayElements(t *testing.T) { + p := OutputPipeline() + for name, doc := range map[string]string{ + "flat array": `{"tokens":["supersecretvalue"]}`, + "nested array": `{"api_key":[["supersecretvalue"]]}`, + "mixed array": `{"credentials":["short","supersecretvalue"]}`, + } { + t.Run(name, func(t *testing.T) { + out, findings, err := SanitizeJSONDocument([]byte(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), "supersecretvalue", "an element of a sensitive member must be masked") + for _, f := range findings { + assert.Equal(t, "json_field", f.Name) + } + }) + } + + // A short element stays, exactly as a short scalar value does. + out, _, err := SanitizeJSONDocument([]byte(`{"credentials":["short","supersecretvalue"]}`), p) + require.NoError(t, err) + assert.Contains(t, string(out), `"short"`, "an element below the json_field minimum must not be masked") + + // An object under a sensitive member keeps its own members' names: the + // values there are governed by their own keys, so a timestamp or id is not + // masked just because the object sits under "credentials". + out, findings, err := SanitizeJSONDocument([]byte(`{"credentials":{"expires_at":"2026-01-01T00:00:00Z"}}`), p) + require.NoError(t, err) + assert.Empty(t, findings, "a nested member is governed by its own name, not its parent's") + assert.Equal(t, `{"credentials":{"expires_at":"2026-01-01T00:00:00Z"}}`, string(out)) +} + +// 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_BodySplitAcrossRecordsCovered pins that a key body split +// over several records is neutralized in every record without changing the +// record count, so each surviving line is still valid JSON (#5705). +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") + } +} + +// TestSanitizeJSONLines_CleanDuplicateKeyRecordPreserved pins that a record with +// intentional duplicate keys is written back unchanged when it carries no +// secret, even though a later record in the stream is redacted (#5705). +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") +} + +// TestJSONLRecords pins the record identity used to decide whether a surviving +// record copy was rewritten: CRLF framing is stripped, blank lines are not +// records, and indentation is part of the record. +func TestJSONLRecords(t *testing.T) { + data := []byte("a\nbb\r\n indented \n\nlast") + assert.Equal(t, []string{"a", "bb", " indented ", "last"}, jsonlRecords(data)) + assert.Empty(t, jsonlRecords([]byte("\n\r\n \n"))) +} + +// TestSanitizeJSONLines_CleanBOMRecordPreserved pins that a BOM-prefixed clean +// record is written back as it was while a later record in the same stream is +// redacted, and that the BOM itself survives (#5705). +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_NormalizedMarkersAcrossMembersMasked pins that a block +// spanning members is detected even when no single marker is matched by a leaf +// pattern: the BEGIN marker carries an invisible character that normalization +// strips, and the body must not survive (#5705). +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") +} + +// TestRewriteJSONTokens_RejectsUnusableInput pins that the token walk reports an +// error instead of returning partial bytes when it cannot tokenize the document +// or finds content after the top-level value. SanitizeJSONDocument turns that into +// a fail-closed error rather than writing unscanned bytes (#5705). +func TestRewriteJSONTokens_RejectsUnusableInput(t *testing.T) { + p := OutputPipeline() + for name, doc := range map[string]string{ + "truncated": `{"a":`, + "trailing value": `{"a":1} {"b":2}`, + "trailing token": `{"a":1} 1`, + "bad object head": `{1:2}`, + } { + t.Run(name, func(t *testing.T) { + out, findings, err := rewriteJSONTokens([]byte(doc), p) + require.Error(t, err, "rewriteJSONTokens must not accept %q", doc) + assert.Nil(t, out) + assert.Empty(t, findings) + }) + } +} + +// TestSanitizeJSONDocument_LeavesUnsupportedInputAlone pins that content the +// structural path cannot treat as one JSON document — invalid JSON, plain prose, +// empty input, several documents in a row — is returned unchanged with no +// findings, so the caller falls back to a text scan (#5705). +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. +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_ReviewResultStaysSchemaValid pins that a review +// result survives the structural rewrite with the shape the harness validates: a +// redaction must never rename a member, drop a required one, or rewrite an +// enum-valued field, or the harness rejects the result and the review is never +// posted (#5705). +func TestSanitizeJSONDocument_ReviewResultStaysSchemaValid(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{ + "action": "request-changes", + "pr_number": 9699, + "repo": "fullsend-ai/fullsend", + "head_sha": "a7bfefc244c85ad55517f073cfe7af15d483c2b1", + "body": "Two findings.", + "findings": [ + { + "severity": "high", + "category": "secret-exposure", + "file": "internal/cli/run.go", + "line": 42, + "description": "The token ghp_FAKEtesttoken000000000000000000000000 is written back." + }, + { + "severity": "low", + "category": "doc-style", + "file": "docs/guides/user/run-artifacts-and-private-data.md", + "description": "The guide does not mention the marker." + } + ] + }`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "the token must be reported") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + assertReviewResultSchemaValid(t, out) +} + +// TestSanitizeJSONDocument_KeepsBOM pins that a document carrying a UTF-8 BOM is +// sanitized structurally and keeps its encoding mark. The BOM is not JSON +// whitespace, so without this the document falls through to the plain-text scan, +// 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_ShortBodyChunksCovered is the record-level half of the +// short-chunk rule: a body stored one short chunk per array element between +// records carrying the markers loses every chunk, and the record count is kept +// (#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..7c669aa2bc 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 @@ -87,6 +94,21 @@ func NewSecretRedactor() *SecretRedactor { func (s *SecretRedactor) Name() string { return "secret_redactor" } func (s *SecretRedactor) Scan(text string) ScanResult { + return s.scan(text, false) +} + +// scanWholeValueSecrets masks only the secrets whose match is the entire value: +// registered runtime values and private-key blocks. It is meant for bytes a leaf +// scan has already redacted, where a pattern match can be a redaction +// placeholder plus JSON escape characters rather than a new secret (#5705). +func (s *SecretRedactor) scanWholeValueSecrets(text string) ScanResult { + return s.scan(text, true) +} + +// scan runs the pattern set. wholeValueOnly restricts it to the patterns whose +// match is the whole secret, which are the only ones that can still be present +// in bytes an earlier pass already redacted. +func (s *SecretRedactor) scan(text string, wholeValueOnly bool) ScanResult { result := ScanResult{Safe: true, Sanitized: text} current := text @@ -110,29 +132,37 @@ func (s *SecretRedactor) Scan(text string) ScanResult { // Prefix-based patterns (full match is the secret). // Use ReplaceAll to catch duplicate occurrences of the same secret. - for _, p := range s.prefixPatterns { - // Deduplicate matches so we report each unique secret once. - seen := map[string]bool{} - matches := p.regex.FindAllString(current, -1) - for _, match := range matches { - if seen[match] { - continue + if !wholeValueOnly { + for _, p := range s.prefixPatterns { + // Deduplicate matches so we report each unique secret once. + seen := map[string]bool{} + matches := p.regex.FindAllString(current, -1) + for _, match := range matches { + if seen[match] { + continue + } + seen[match] = true + masked := mask(match) + result.Findings = append(result.Findings, Finding{ + Scanner: "secret_redactor", + Name: p.name, + Severity: "critical", + Detail: fmt.Sprintf("Redacted %s (%d chars) -> %s", p.name, len(match), masked), + }) + current = strings.ReplaceAll(current, match, masked) + result.Safe = false } - seen[match] = true - masked := mask(match) - result.Findings = append(result.Findings, Finding{ - Scanner: "secret_redactor", - Name: p.name, - Severity: "critical", - Detail: fmt.Sprintf("Redacted %s (%d chars) -> %s", p.name, len(match), masked), - }) - current = strings.ReplaceAll(current, match, masked) - result.Safe = false } } - // Structural patterns (capture group is the secret) + // Structural patterns (capture group is the secret). Only the private-key + // block is safe to match in whole-value mode: every other pattern captures a + // value out of surrounding text, so a match on bytes that already carry a + // redaction placeholder can be that placeholder rather than a secret. for _, p := range s.structuralPatterns { + if wholeValueOnly && p.name != "private_key" { + continue + } // Private key: replace full match (no capture group needed). if p.name == "private_key" { matches := p.regex.FindAllString(current, -1) @@ -171,11 +201,61 @@ func (s *SecretRedactor) Scan(text string) ScanResult { if start < 0 || end < 0 { continue } + // A double-quoted value that ends in a backslash is ambiguous: the + // bounded branch the pattern returns first reads the \" as a literal + // backslash before the closing quote, while the escape-reading branch + // reads it as an escaped quote inside the value. Prefer the reading + // that ends the string at a JSON value boundary, so a credential that + // carries an escaped quote stays masked whole (#10082). + if p.name == "json_field" { + if escapeStart, escapeEnd, ok := resolveJSONFieldDoubleQuote(current, loc[0], start, end); ok { + start, end = escapeStart, escapeEnd + } + } secret := current[start:end] if p.name == "json_field" && isExemptJSONField(current, loc[0], loc[1], secret) { continue } + // If the matched secret ends with a backslash and is immediately + // followed by a quote delimiter, the trailing backslash was escaping + // that delimiter (e.g. \" in JSON or code strings). Preserve the + // escape by excluding the backslash from the redacted secret span. + // json_field spans escaped quotes in its own value pattern, so its + // capture already ends at the delimiter it belongs to. + if p.name != "json_field" && end < len(current) && (current[end] == '"' || current[end] == '\'') { + numBackslashes := 0 + for k := len(secret) - 1; k >= 0 && secret[k] == '\\'; k-- { + numBackslashes++ + } + if numBackslashes%2 == 1 { + secret = secret[:len(secret)-1] + end-- + } + } + if len(secret) == 0 { + continue + } + // A captured value is always masked, even when it already looks + // like a mask. The shape of a placeholder (4 characters and "...", + // or "***") is also the shape of a real short secret: + // db_connection_password accepts a value of 4 characters or more, + // so skipping every 7-byte capture that ends in "..." left a real + // password such as postgres://u:abcd...@host in the output. Callers + // that rescan bytes an earlier pass already redacted use + // scanWholeValueSecrets, which runs no value pattern, so they never + // reach this loop; a full Scan over redacted text can therefore + // only be re-masking a placeholder into "***", never a secret into + // itself. + // + // Only json_field needs the length gate here: its value pattern + // matches any length, while env_assignment, auth_header and + // db_connection_password enforce their own minimum in the pattern. + // The gate counts runes and runs on the trimmed span, so the bytes + // actually masked are never shorter than the documented minimum. + if p.name == "json_field" && utf8.RuneCountInString(secret) < minJSONFieldLen { + continue + } masked := mask(secret) result.Findings = append(result.Findings, Finding{ Scanner: "secret_redactor", @@ -207,6 +287,58 @@ func (s *SecretRedactor) Scan(text string) ScanResult { // 8- and 9-byte paths such as /root/qa stay masked, as before #9944. var authorPathValue = regexp.MustCompile(`^/[A-Za-z0-9_./-]{9,}$`) +// jsonFieldEscapeReadingRe is the json_field pattern restricted to the +// escape-reading double-quoted value branch. scan runs it against the same +// match start to compare the escape reading with the bounded reading the full +// pattern returns first; see resolveJSONFieldDoubleQuote. +var jsonFieldEscapeReadingRe = regexp.MustCompile(`(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*"((?:\\[\s\S]|[^"\\\r\n])*)"`) + +// jsonValueBoundaryRe matches the text that may follow a complete JSON string +// value: a member or element separator, a closing bracket, or the end of the +// physical line. +// +// It runs against the remainder of the text after the escape reading's closing +// quote, so it is anchored with \A: a (?m)^ would also accept a boundary on any +// later line, letting the escape reading win whenever unrelated text further +// down the input starts with }, ] or a blank line, and swallow the separator +// that follows the value (#10082). +var jsonValueBoundaryRe = regexp.MustCompile(`\A[ \t]*(?:,|\}|\]|\r?\n|\z)`) + +// resolveJSONFieldDoubleQuote picks between the two readings of a +// double-quoted json_field value that ends in a backslash. The pattern returns +// the bounded reading first, because in raw text — a log line or a YAML flow +// mapping — "api_key": "secret\", "password": "..." means the backslash is +// literal and the value ends at that quote; taking the \" as an escape there +// would run on to the next field's opening quote and swallow the separator. +// The same bytes inside valid JSON mean the opposite: a \" can only be an +// escaped quote, so a value such as {"password":"ab\",cd"} keeps going to the +// later quote, and stopping at the first one would mask a fragment and leave +// the rest of the credential in an invalid document (#10082). +// +// The two readings are told apart by where they end. An escape reading that +// closes the string at a JSON value boundary (a separator, a bracket or the +// line end) is a well-formed string, so it wins when it covers more than the +// bounded reading. When it ends anywhere else — before the next field's key, +// for example — it ran past the real end of the value and the bounded reading +// stands. The returned span is the value to mask. +func resolveJSONFieldDoubleQuote(text string, matchStart, valueStart, valueEnd int) (int, int, bool) { + if matchStart < 0 || matchStart >= len(text) { + return 0, 0, false + } + loc := jsonFieldEscapeReadingRe.FindStringSubmatchIndex(text[matchStart:]) + if loc == nil || loc[0] != 0 || loc[2] < 0 { + return 0, 0, false + } + start, end := matchStart+loc[2], matchStart+loc[3] + if start != valueStart || end <= valueEnd { + return 0, 0, false + } + if !jsonValueBoundaryRe.MatchString(text[matchStart+loc[1]:]) { + return 0, 0, false + } + return start, end, true +} + // isExemptJSONKey reports whether a json_field match has the key "author", // in any case. "author" contains the trigger word "auth" but names a // sender, such as a codex child agent path (#9944). Only that one name is @@ -237,11 +369,41 @@ func isExemptJSONField(text string, matchStart, matchEnd int, secret string) boo return authorPathValue.MatchString(secret) && isExemptJSONKey(text[matchStart:matchEnd]) } +// mask returns a redacted representation of a secret value. +// +// 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 +459,38 @@ func defaultStructuralPatterns() []secretPattern { // the mask keeps it visible. A bare value still ends at the first // space, as in the PostToolUse hook. {"env_assignment", `(?i)(?:^|\s)(?:export\s+)?((?:[A-Za-z0-9]+_)*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|PASSWD|AUTH|API_KEY)(?:_[A-Za-z0-9]+)*)\s*=\s*(?:['"](?:(?:basic|bearer|token)[ \t]+)?)?([^\s"'}\]),;]{8,})['"]?`}, - {"json_field", `(?:"[^"]*(?i:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?i:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"([^"]{8,})"|'([^']{8,})')`}, + // json_field captures a value out of a quoted field. The escape-reading + // branches consume escaped delimiters, so a JSON or YAML string with an + // embedded quote is matched whole. A value that ends in a literal backslash + // right before its closing quote is ambiguous: reading that \" as an escape + // runs on to the next quote on the line, which is usually the next field's + // opening quote, and swallows the separator between the two fields — and + // with it the chance to mask the second field. Each quote style therefore + // has a bounded branch that keeps the backslash out of the captured value + // and matches only when the closing quote is followed by a field or line + // boundary. The boundary accepts an optional CR before the line end, so a + // CRLF line is treated like an LF one. Those bounded branches come before + // the escape-reading ones because Go's regexp alternation is leftmost-first: + // for 'api_key': 'secret\', 'password': '...' and + // "api_key": "secret\", "password": "..." the escape-reading branch would + // otherwise match first and eat the comma. scan corrects that order for a + // double-quoted value whose closing \" continues a valid JSON string rather + // than ending the field (resolveJSONFieldDoubleQuote). The strict + // double-quoted branch stops at a raw newline, so a JSON value ending in \" + // cannot run on to the next line's quote and swallow the field there + // (#9944). A value folded across physical lines (a YAML or log string, not + // JSON) still needs to be matchable when its closing quote ends the field or + // the line: the sixth branch allows raw newlines but only at that boundary, + // so it cannot run on to a later field's quote. A value that ends in a + // literal backslash and is followed by neither a field nor a line end — a + // log line such as "password": "Abc123xyzQ\" (rotated) — is matched by the + // last-resort branch, which takes any trailing-backslash value so it can + // never fall through unmasked. That branch is last so it can only win when + // no bounded or escape-reading branch matches. The single-quoted branch + // keeps a raw newline inside the value matchable, as it was before the + // escape handling was added. The minimum length is enforced in scan, not + // here. + {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"([^"\r\n]*\\)"[ \t]*(?:,|\}|\]|\r?$)|"((?:\\[\s\S]|[^"\\\r\n])*)"|'((?:''|[^'\r\n])*\\)'[ \t]*(?:,|\}|\]|\r?$)|'((?:''|\\\r?\n|\\.|[^'\r\n\\])*[^'\r\n\\])'|'([^']*)'|"((?:\\[\s\S]|[^"\\])*)"[ \t]*(?:,|\}|\]|\r?$)|"([^"\r\n]*\\)")`}, // 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..e27979028f 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..9f0e544394 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,345 @@ 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 keeps the field after a double-quoted trailing backslash", func(t *testing.T) { + // The same leftmost-first trap as the flow mapping above, for double + // quotes: reading the closing \" of the first value as an escape ran on + // to the next field's opening quote, so the comma and the second field's + // credential were swallowed and never masked (review finding on #10082). + for _, input := range []string{ + `"api_key": "abcdefghi\", "password": "fake-fake-fake-fake"`, + `{"api_key": "abcdefghi\", "password": "fake-fake-fake-fake"}`, + } { + result := r.Scan(input) + assert.False(t, result.Safe, "input: %s", input) + assert.Contains(t, result.Sanitized, `", "password"`, + "the separator and the next field's key must survive: %s", result.Sanitized) + assert.NotContains(t, result.Sanitized, "abcdefghi", "input: %s", input) + assert.NotContains(t, result.Sanitized, "fake-fake-fake-fake", + "the second field's secret must be masked: %s", result.Sanitized) + } + }) + + t.Run("json_field redacts a double-quoted value ending in a literal backslash on a CRLF line", func(t *testing.T) { + // A CRLF line ends with \r\n, and (?m)$ only matches before \n, so the + // bounded branch used to reject the CRLF field and the escape-reading + // branch found no closing quote. The value went out in clear text (#10082). + input := "\"api_key\": \"abcdefgh\\\"\r\n\"password\": \"ijklmnopqrst\"" + result := r.Scan(input) + assert.False(t, result.Safe) + assert.NotContains(t, result.Sanitized, "abcdefgh") + assert.NotContains(t, result.Sanitized, "ijklmnopqrst") + assert.Contains(t, result.Sanitized, "\r\n\"password\"", + "the CRLF line break and the next field's key must survive: %q", result.Sanitized) + }) + + t.Run("json_field redacts a double-quoted value ending in a literal backslash before trailing text", func(t *testing.T) { + // The closing quote is followed by text rather than a field or line end, + // so neither bounded branch matched and the value went out in clear text. + // The last-resort branch masks it anyway (#10082). + result := r.Scan("\"password\": \"Abc123xyzQ\\\" (rotated)\nnext line\n") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "Abc123xyzQ") + assert.Contains(t, result.Sanitized, `" (rotated)`, "text after the value must survive") + }) + + t.Run("json_field masks a valid JSON value whose escaped quote is followed by a separator", func(t *testing.T) { + // Inside valid JSON a \" can only be an escaped quote, so a value such as + // "ab\",cdefgh" continues to the later quote. Stopping at the first one + // masked a fragment and left the rest of the value in invalid JSON (#10082). + for _, input := range []string{ + `{"password":"ab\",cdefgh"}`, + `{"password":"ab\",cdefgh","x":1}`, + `{"password":"ab\",cdefgh\""}`, + } { + result := r.Scan(input) + assert.False(t, result.Safe, "input: %s", input) + assert.True(t, json.Valid([]byte(result.Sanitized)), + "output must stay valid JSON for %s: %s", input, result.Sanitized) + assert.NotContains(t, result.Sanitized, "cdefgh", "input: %s", input) + } + }) + + t.Run("json_field keeps the separator when a later line starts with a closing brace", func(t *testing.T) { + // The boundary check runs against the remainder of the text, so a (?m)^ + // also accepted a boundary on any later line: with \n} after the value the + // escape reading won and swallowed `", `, dropping the next key's opening + // quote (review finding on #10082). The check is anchored with \A now. + for _, tail := range []string{"\n}", "\n\nnext"} { + input := `"api_key": "ZZvalue12\", "passwd_key": "QQother99" more` + tail + result := r.Scan(input) + assert.False(t, result.Safe, "tail: %q", tail) + assert.Contains(t, result.Sanitized, `", "passwd_key"`, + "the separator and the next field's key must survive: %s", result.Sanitized) + assert.NotContains(t, result.Sanitized, "ZZvalue12", "tail: %q", tail) + assert.NotContains(t, result.Sanitized, "QQother99", "tail: %q", tail) + } + }) + + 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..ed48fdc812 --- /dev/null +++ b/internal/security/testdata/review-result.schema.pin @@ -0,0 +1,12 @@ +# Pin for internal/security/testdata/review-result.schema.json. +# +# The vendored review-result schema is a test fixture copied from +# fullsend-ai/agents, the repository that defines the review result contract. +# Nothing checks it automatically: re-vendor the schema and update this pin by +# hand whenever the upstream schema changes, with +# `gh api repos//contents/?ref= --jq .content | base64 -d`. +# The pin records the upstream revision the vendored copy came from, so a stale +# fixture can be traced and refreshed. +repo=fullsend-ai/agents +commit=cec09212b99fcd78bf7afc7637d8fe0b2007e109 +path=schemas/review-result.schema.json