Repository navigation
fix(#5705): mask private-key blocks that span JSON members or records - #10084
andrewevansrh wants to merge 2 commits into
Conversation
…slashes
The output sanitizer ran every pattern as a raw text replace over all
output files. When an agent quoted code inside a JSON string value, a
pattern matched up to the quote delimiter and swallowed the backslash
escaping it, so the rewritten document was no longer valid JSON and
downstream jq in post-review.sh failed with exit status 5.
Two changes close that:
- SanitizeJSONDocument and SanitizeJSONLines rewrite JSON output through
a token-preserving walk instead of a text replace. Every object key and
scalar leaf is scanned on its own and re-encoded, so redaction inside a
value cannot touch the framing. Member order, duplicate keys and exact
number literals survive, a leading UTF-8 BOM is stripped and restored,
and a clean document comes back byte for byte.
- The redactor no longer includes a delimiter-escaping backslash in a
captured value, and Mask returns "***" when the prefix it would keep
carries an escape or a quote delimiter, so the mask itself can never
break the string it is spliced into.
Content that cannot be redacted in place is replaced with a valid
fail-closed JSON marker rather than corrupted JSON, and the marker reason
is reported to the operator.
BREAKING CHANGE: a JSON document or JSONL record whose secret cannot be
localized is now replaced with a `{"error":"output removed because …"}`
marker instead of being written back with a broken or partial redaction,
so tooling that reads those files sees the marker where the agent's
content used to be.
Signed-off-by: anevans <anevans@redhat.com>
… or records A JSON document can carry a private key one fragment per member: BEGIN in one string, body lines in the next, END in a third. Masking any single member removes the marker the block's own pattern needs, and the bytes scan that runs after the rewrite sees no block any more, so the body was written back in clear text. Such a block is now detected on a decoded view of the document or stream, before anything is rewritten, and neutralized member by member. The boundary members always carry marker text and are masked even when a marker is split across two of them; a member in between is masked when it carries a marker, a run that looks like PEM body material, or joins with its neighbours into text that does. Object keys keep their names unless the name itself is block content, so a review that merely quotes the PEM header in one finding and the footer in another keeps the shape and the enum values review-result.schema.json requires, instead of being dropped by schema validation. Records carrying part of a block across a record boundary are replaced with a fail-closed marker, because the record framing cannot be rewritten. A body split so that one-character and longer chunks alternate is a known residual; uniform chunks and complete body lines are masked. Signed-off-by: anevans <anevans@redhat.com>
|
🤖 Finished Review · ✅ Success · Started 4:01 PM UTC · Completed 4:18 PM UTC Commit: Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $3.23 |
Site previewPreview: https://8df9d5ad-site.fullsend-ai.workers.dev Commit: |
|
Risk Assessment: elevated (3/5) DetailsLarge diff (4,421 lines) introducing breaking changes to platform-wide output sanitization without a feature flag, compounded by high churn and regression history in modified files. |
ReviewFindingsHigh
Medium
Low
Labels: PR changes Go code in the output sanitizer, a security control. Next steps:
|
| // 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) { |
There was a problem hiding this comment.
[high] logic-error
Production code never calls the structural sanitizers (SanitizeJSONDocument / SanitizeJSONLines). The only callers are jsonsanitize_test.go and SanitizeJSONLines itself; neither the PR head nor the base checkout has a caller in internal/cli, and scanOutputFiles (internal/cli/run.go) still sends every file through pipeline.Scan as a raw text replace. The JSON-preserving walk and the cross-member/cross-record private-key handling therefore never run on run artifacts. docs/contributing/runtime-implementation.md:639-645 in this PR describes scanOutputFiles sanitizing JSON structurally, which does not match the code. The new tests call the helpers directly, so they do not catch the missing wiring.
Suggested fix: Wire JSON document/JSONL detection and SanitizeJSONDocument/SanitizeJSONLines into scanOutputFiles, send sanitizer errors and markers through the fail-closed path, and add end-to-end output-scan tests. If the wiring is meant to land in another stacked PR, say so and keep the runtime-implementation.md claim out until it lands.
| if len(material) == 0 { | ||
| flush() | ||
| continue | ||
| } |
There was a problem hiding this comment.
[high] secret-exposure
A PEM body split into alternating two-character and one-character string values gets past redaction. In maskSpanBody a one-character value following a longer member calls flush() (lines ~504-511), so no group reaches the joined-text threshold and no single fragment passes textCarriesKeyMaterial. The BEGIN/END boundary leaves are masked but the body fragments stay in the output and can be concatenated; once the markers are gone the serialized rescan cannot see the block. The JSONL middle-record logic has the same gap. The PR documents this as a known residual, but a documented gap still lets recoverable key material reach artifacts, and deliberate fragmentation is a realistic exfiltration path.
Suggested fix: Rebuild and classify the full candidate body regardless of fragment length before choosing which leaves to mask; if a block cannot be safely localized, fail closed with a marker. Add regression tests with alternating 1- and 2-character chunks for JSON and JSONL.
| } | ||
|
|
||
| // isSchemaConstrainedField reports whether a value under memberKey is a | ||
| // schema-constrained review field rather than candidate key material. |
There was a problem hiding this comment.
[high] secret-exposure
The schema-field exemption trusts the member name alone and does not check that the document follows the review schema. isSchemaConstrainedField returns true for any value under a key such as file, id or reason that is too short to pass textCarriesKeyMaterial, and maskSpanBody flushes instead of joining it to a candidate run. Body chunks stored under duplicate file members between separate BEGIN and END leaves are therefore all exempted; duplicate members are preserved on rewrite, so the full body is recoverable after the boundary markers are masked. Middle JSONL records are affected the same way.
Suggested fix: Do not exempt secret candidates by member name alone; detect reconstructed key material across all candidate leaves before applying any schema-preservation exception, and fail closed when needed. Add tests for short body chunks under duplicate schema-named members.
| } | ||
|
|
||
| // schemaConstrainedFields is the set of review schema keys whose values are | ||
| // structural (enums, file paths, repository identifiers) rather than key material. |
There was a problem hiding this comment.
[medium] misplaced-abstraction
jsonsanitize.go hardcodes schemaConstrainedFields (action, category, severity, file, head_sha, pr_number, dimension, ...), which are specific to the review agent's output schema, inside the agent-agnostic core security package, with a vendored review-result.schema.json and pin under testdata. This couples a generic output scanner to one agent's schema (ADR 0022 places output schemas in harness configuration) and drives the exemption weakness reported at line 300.
Suggested fix: Take review-specific field knowledge out of internal/security; if schema-aware preservation is needed, pass it in as a generic parameter supplied by the harness or post-script layer.
| // 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 { |
There was a problem hiding this comment.
[low] api-shape
mask was renamed to Mask, but its only callers are inside package security (redactor.go, jsonsanitize.go). Exporting it widens the package API with no outside consumer.
Suggested fix: Rename Mask back to mask and update call sites, unless a sibling stacked PR needs it from outside the package.
| failClosedInvalidJSON = `{"error":"output removed because redaction would invalidate JSON"}` | ||
| failClosedCrossRecordJSON = `{"error":"output removed because output contained a cross-record secret"}` | ||
| failClosedSpansMembersJSON = `{"error":"output removed because a private key block spans JSON framing"}` | ||
| FailClosedUnwritableJSON = `{"error":"output removed because it could not be redacted"}` |
There was a problem hiding this comment.
[low] naming-convention
FailClosedUnwritableJSON is exported but shares a const block with the unexported failClosedInvalidJSON, failClosedCrossRecordJSON and failClosedSpansMembersJSON; outside the package it is used only by tests, so the mixed visibility is inconsistent.
Suggested fix: Rename to failClosedUnwritableJSON if package-internal; otherwise move it out of the block with its own doc comment.
| // value, in document order, in a view where a value split across members reads as | ||
| // one contiguous run of text. Each leaf's range in that view is kept so a match | ||
| // can be mapped back to the members that carry it. | ||
| func collectJSONLeaves(doc []byte) *jsonProvenance { |
There was a problem hiding this comment.
[low] code-organization
The file interleaves single-document JSON sanitization with JSONL helpers: collectJSONLeaves (line 1032) sits between JSONL helpers, and rewriteJSONTokens (line 1193) comes after all JSONL functions.
Suggested fix: Move the single-document helpers next to SanitizeJSONDocument.
| # | ||
| # The vendored review-result schema is a test fixture copied from | ||
| # fullsend-ai/agents. Re-vendor the schema and update this pin together whenever | ||
| # the upstream schema changes. scripts/check-review-schema-pin.sh compares the |
There was a problem hiding this comment.
[low] pattern-inconsistency
The pin file and a comment in jsonsanitize_test.go say scripts/check-review-schema-pin.sh compares the vendored schema against upstream at the pinned commit, but no such script exists (only scripts/check-agents-gate-pin.sh and its test). The comment describes a drift check that is not there.
Suggested fix: Add the script and its CI hook, or remove the reference.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
…tied records Address the remaining review findings on fullsend-ai#10082: - jsonValueBoundaryRe is anchored with \A instead of (?m)^. It runs against the remainder after the escape reading, so the old pattern accepted a boundary on any later line: when unrelated text further down started with }, ] or a blank line, the escape reading won and swallowed `", `, dropping the next key's opening quote. Raw text such as `"api_key": "ZZvalue12\", "passwd_key": "QQother99" more\n}` keeps its separator and both values are masked again. - nextAnchor prefers the later original record on a run-length tie, so a cross-record match no longer pairs the record it covered with an identical clean copy further down the stream. The records `{"v":"aaa"}`, `{"v":"bbb"}`, `{"v":"aaa"}` now keep the clean third record and replace the two the match covered, instead of keeping the covered first copy. - The JSONL stream-scan comment states the one gap it still leaves — a JSON-escaped PEM marker split across records is not joined here — and that fullsend-ai#10084 closes it by scanning a decoded view of the stream before any rewrite. Regression tests: the `\n}` and blank-line separator subtests in TestSecretRedactor, and TestSanitizeJSONLines_TiedDuplicateKeepsLaterCleanCopy. Both fail on 4911942 and pass with this change. Note: Generated with assistance from DeepSeek V4.1 Flash Signed-off-by: anevans <anevans@redhat.com>
jflowers
left a comment
There was a problem hiding this comment.
Council review of part 2 in the #5705 sanitizer stack (6 reviewer runs completed, 1 failed on context limits; 11 findings: 2 HIGH, 5 MEDIUM, 4 LOW).
From what I can tell, the structural rewrite is the right shape for the #5705 problem, and the test coverage is thorough. Two concerns hold this back:
maskSpanBodystill admits a PEM body split into alternating single-character and longer fragments (jsonsanitize.go:645); the joined-text threshold never trips, the file stays valid JSON, and no fail-closed marker fires, so the body reaches the artifact in clear text.schemaConstrainedFieldshardcodes the review agent's schema field names inside the agnosticinternal/securitypackage (jsonsanitize.go:421); every new schema field now requires editing the security core.
The docs describe the JSON structural path, fail-closed markers, and annotations as live behavior while internal/cli/run.go still calls only pipeline.Scan. Since the wiring arrives in a later part of the stack, could the docs say so explicitly?
The remaining findings cover unbounded buffering on large documents, the missing schema-pin script, duplicated span-masking logic between the document and JSONL paths, export hygiene on Mask and FailClosedUnwritableJSON, testify usage versus the go convention pack, and test-isolation details. This review independently corroborates the earlier fullsend-ai-review[bot] CHANGES_REQUESTED on the same head commit.
This review was generated by /uf.review-pr (AI-assisted).
| } | ||
| run = 0 | ||
| default: | ||
| run = 0 |
There was a problem hiding this comment.
[HIGH] secret-exposure · divisor-adversary
A PEM body split into alternating single-character and longer string values still slips through the mask. maskSpanBody flushes its group when a 1-char material block follows a longer member, so the joined text never reaches the pemBodyJoined threshold while each fragment stays below the pemBodyRun length. The document stays valid JSON, so no fail-closed marker fires; the whole-value rescan runs after the rewrite, when the markers are already masked. Would an attacker-controlled JSON structure interleaving 1-char and longer body fragments exfiltrate the key body in clear text here? The docs acknowledge this residual; worth deciding whether the threat model accepts it or the cross-record fail-closed marker should cover it.
| } | ||
| } | ||
| } | ||
| return spans |
There was a problem hiding this comment.
[HIGH] architectural-boundary · divisor-architect
schemaConstrainedFields hardcodes review-result schema field names (action, category, severity, file, head_sha, and more) inside the generic internal/security package. The map couples an agnostic sanitization layer to one consumer's output shape; any new schema field or new consumer requires editing the security package (AP-001, AP-007). Could the field set be injected from the caller instead?
| // schemaConstrainedFields is the set of review schema keys whose values are | ||
| // structural (enums, file paths, repository identifiers) rather than key material. | ||
| // When a quoted marker pair covers a review result, these fields are protected | ||
| // from joining candidate PEM body runs so schema validation is not broken (#5705). |
There was a problem hiding this comment.
[MEDIUM] resilience · divisor-adversary
SanitizeJSONDocument buffers the whole file, builds a decoded view, and rewrites tokens with no size cap (jsonsanitize.go:180, 283). What happens when an agent-influenced output grows the run directory with a very large JSON document? The walk continues after an abort, but the oversized file's fail-closed path depends on marker writes under memory pressure.
| // a body split across members: a chunk on its own may be shorter than the | ||
| // material floor or carry no digit, but the joined body reconstructs both. It | ||
| // still requires upper case, lower case and a base64-only character, which a hex | ||
| // SHA, a lowercase word, a path and free text do not have. |
There was a problem hiding this comment.
[MEDIUM] DRY · divisor-architect
maskSpanBody and maskMiddleRecordBody duplicate near-identical group, join, and flush state; they differ only in marking spans.covered versus covered[record]. The ~70 duplicated lines make a future heuristic fix easy to apply to one path and miss in the other. Would extracting the shared run accumulator keep the document and JSONL paths in sync?
| "encoding/json" | ||
| "fmt" | ||
| "os" | ||
| "strings" |
There was a problem hiding this comment.
[MEDIUM] test-conventions · divisor-gaze-testing
The new test files import testify assert and require (jsonsanitize_test.go:8-9, scanner_test.go:8-9). The go convention pack mandates stdlib testing with t.Errorf/t.Fatalf (TC-001, TC-002); over 100 existing usages show the repo never recorded an exception. Worth picking a direction: migrate the new tests to stdlib, or capture the testify exception as a CR-NNN rule in go-custom.md?
| # | ||
| # The vendored review-result schema is a test fixture copied from | ||
| # fullsend-ai/agents. Re-vendor the schema and update this pin together whenever | ||
| # the upstream schema changes. scripts/check-review-schema-pin.sh compares the |
There was a problem hiding this comment.
[MEDIUM] supply-chain · divisor-adversary
The pin file states that scripts/check-review-schema-pin.sh compares the vendored schema against upstream at cec09212, but no such script exists in the diff or the base checkout. Drift would go undetected, and an outdated schema could let sanitized output fail harness validation silently. Is the script landing in a later part of the stack, or worth adding here?
| // 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 { |
There was a problem hiding this comment.
[MEDIUM] documentation · divisor-architect
FailClosedUnwritableJSON shares a const block with three unexported siblings and lacks an identifier-prefixed GoDoc comment (CS-004, DR-001). Mask is newly exported though its only callers live inside package security. Is the wider API intentional, or could both stay internal until an outside consumer exists?
| // ResetRuntimeSecretsForTest clears the registry. It is exported because tests | ||
| // outside this package (internal/cli drives the output scan end to end) need a | ||
| // clean registry; the tests in this package call resetRuntimeSecrets directly. | ||
| func ResetRuntimeSecretsForTest() { |
There was a problem hiding this comment.
[LOW] test-isolation · divisor-gaze-testing
Nine tests mutate process-global runtimeSecrets through resetRuntimeSecrets with t.Cleanup; the cleanup is correct, but the suite stays order-dependent and unsafe for t.Parallel. The exported ResetRuntimeSecretsForTest also places a test helper in the production API. Worth a build-tagged or internal testutil helper instead?
| if len(runs) == 0 { | ||
| return nil | ||
| } | ||
| var material []byte |
There was a problem hiding this comment.
[LOW] zero-waste · divisor-guard
The ~1.4k lines of structural sanitizers have no caller outside tests in this diff; scanOutputFiles still calls pipeline.Scan. In the declared stacked flow the wiring arrives in the follow-on PR, so this reads as a temporary gap rather than a block. Worth confirming the wiring PR lands before this one merges.
| return "***" | ||
| } | ||
| return value[:4] + "..." | ||
| prefix := value[:4] |
There was a problem hiding this comment.
[LOW] test-coverage · divisor-gaze-testing
Exported Mask and ResetRuntimeSecretsForTest lack dedicated contract tests; coverage is indirect through the integration suite. Would a small unit test pin the prefix rules (escape and quote fallback to ***, rune-count floor) before outside callers depend on them?
Summary
Part 2 of 3 split out of #9699 (part 1: #10082, part 3: #10085).
A JSON document can carry a private key one fragment per member:
BEGINin onestring, body lines in the next,
ENDin a third. Masking any single memberremoves the marker the block's own pattern needs, and the written-bytes scan that
runs after the rewrite sees no block any more, so the body was written back in
clear text.
What changed
jsonsanitize.godetects a private-key block that spans members or records ona decoded view of the document or stream, before anything is rewritten, and
neutralizes it where it lives:
marker is split across two members and neither fragment looks like one alone;
PEM body material, or joins with its neighbours into text that does;
review that merely quotes the PEM header in one finding and the footer in
another keeps the shape and enum values
review-result.schema.jsonrequiresinstead of failing schema validation and being dropped;
fail-closed marker, because the record framing cannot be rewritten.
residual; uniform chunks and complete body lines are masked.
Verification
go test ./internal/security/make lintNote: Generated with assistance from DeepSeek V4.1 Flash