Repository navigation
fix(#5705)!: preserve escaping backslashes in JSON strings during redaction - #9699
andrewevansrh wants to merge 78 commits into
Conversation
…and validate JSON integrity
When redacting patterns such as env_assignment, auth_header, and
db_connection_password, matching up to an escaped quote (") previously
consumed the escaping backslash while leaving the unescaped quote
delimiter in the sanitized output, producing corrupted JSON syntax.
Update the value capture character classes to stop before backslashes
that escape delimiter quotes while continuing to redact credentials that
legitimately contain backslashes.
In addition, add post-sanitization JSON structural integrity validation
to scanOutputFiles in the CLI so that if sanitization produces invalid
JSON from a previously valid JSON file, the original file is preserved
instead of corrupting downstream tools.
Closes fullsend-ai#5705
Signed-off-by: anevans <anevans@redhat.com>
… escape-splitting redactions When redacting secret patterns in JSON outputs, raw string replacements could consume escaping backslashes or split escape sequences, corrupting JSON syntax. Implement structural JSON sanitization in scanOutputFiles by parsing JSON files and sanitizing string leaves rather than performing raw text replacement across the entire file, guaranteeing that valid JSON files remain syntactically valid and completely redacted (failing closed). In addition, update the json_field regex to capture escaped characters within quotes, and update mask() to avoid creating dangling or invalid escape sequences when masking secrets. Signed-off-by: anevans <anevans@redhat.com>
Scan object keys and string leaves in sanitizeJSONStructure to avoid leaking credentials in JSON map keys. Decode JSON using dec.UseNumber() and encode with SetEscapeHTML(false) to prevent precision loss on large integers and HTML escaping. Restore character-based quantifier classes in redactor.go while safely preserving quote-escaping backslashes via delimiter inspection. Add boundary tests for env_assignment, auth_header, and db_connection_password at minimum lengths with backslashes. Add test coverage in scan_output_telemetry_test.go for key sanitization, large numbers, and float formatting. Signed-off-by: anevans <anevans@redhat.com>
…p findings Detect duplicate JSON keys while decoding and fall back to plain-text sanitization so all occurrences of duplicate keys are redacted. Ensure backstop findings are always recorded and sanitized output is written even when re-encoding is not valid JSON. Fall back to plain-text sanitization on JSON marshal errors instead of failing open. Preserve line count for single-record .jsonl files and compact JSON files by skipping the structural path for .jsonl/.ndjson and omitting indentation on compact JSON documents. Add regression tests for duplicate JSON keys, single-record JSONL line count preservation, and duplicate key token decoding. Signed-off-by: anevans <anevans@redhat.com>
…m length Call dec.UseNumber() in hasDuplicateJSONKeys to prevent float64 parsing overflow from terminating duplicate key detection early. Apply minimum length checks to captured credentials prior to trimming delimiter-escaping backslashes, ensuring credentials at exact pattern minimums ending in backslashes before quotes are redacted. Add regression and boundary tests for both paths. Signed-off-by: anevans <anevans@redhat.com>
Signed-off-by: anevans <anevans@redhat.com>
Signed-off-by: anevans <anevans@redhat.com>
Signed-off-by: anevans <anevans@redhat.com>
Signed-off-by: anevans <anevans@redhat.com>
Signed-off-by: anevans <anevans@redhat.com>
Signed-off-by: anevans <anevans@redhat.com>
Signed-off-by: anevans <anevans@redhat.com>
Signed-off-by: anevans <anevans@redhat.com>
Signed-off-by: anevans <anevans@redhat.com>
…ntime secrets Signed-off-by: anevans <anevans@redhat.com>
…e keys, and YAML fields Fail closed on raw multiline PEM blocks in JSONL streams regardless of whether individual lines parse as JSON. Replace duplicate-key JSONL records with an error marker when structural findings cannot be safely serialized. Trim trailing newline from the JSONL no-structural-findings backstop encoder to prevent extra blank lines. Prevent trailing literal backslashes in single-quoted YAML fields from consuming adjacent fields in json_field regex. Remove detect-private-key pre-commit exclusion by concatenating test PEM fixture strings. Signed-off-by: anevans <anevans@redhat.com>
PR Summary by QodoPreserve JSON validity and escaping during output redaction
AI Description
Merge Risk
|
|
🤖 Review · Commit: This review was superseded by a newer commit. Check the current pull request HEAD's review status before merging. |
Code Review by Qodo
1.
|
|
🤖 Finished Review · Commit: Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $0.80 This review was superseded by a newer commit. Check the current pull request HEAD's review status before merging. |
… correct chunk docs Record the upstream repo, commit and path for the vendored review-result schema in testdata/review-result.schema.pin. scripts/check-review-schema-pin.sh compares the vendored copy with upstream at the pinned commit (semantically, so reformatting is not drift) and reports drift; its stubbed test runs in make script-test, and release.yml runs the check alongside the existing informational gate pin drift check. Correct the pemBodyRunRe and joined-run comments, and the runtime-implementation guide, to describe the all-single-character rule: a body stored one character per member is reconstructed, an isolated single-character value is kept, and a body whose one-character and longer chunks interleave is a known residual. Signed-off-by: anevans <anevans@redhat.com>
|
🤖 Finished Review · ✅ Success · Started 11:46 AM UTC · Completed 12:00 PM UTC Commit: Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $2.49 |
|
Risk Assessment: elevated (3/5) DetailsScore increased from 2 to 3 because protected paths (.github/workflows/release.yml, scripts/check-review-schema-pin*.sh) and CI workflow modifications were introduced alongside the large diff touching high-churn execution paths (internal/cli/run.go) without a feature flag. |
ReviewFindingsHigh
Medium
Low
Earlier findings
Labels: The PR touches the release workflow and substantial documentation in addition to the Go sanitizer fix. Next steps:
|
|
Finding threads left open (21):
Outdated review threads left open (1):
|
jflowers
left a comment
There was a problem hiding this comment.
Thanks for chasing this one down. The structural JSON path and the backslash trim in redactor.go look right to me, and Mask() returning *** when the prefix has an escape or quote is a nice small fix.
My concern is size. The bug is a regex eating a backslash, and the PR is 6.4k lines. Any chance we can split it into three?
- The redactor escape fix plus
SanitizeJSONDocument/SanitizeJSONLines(this closes #5705) - Private keys that span members or records
- The
run.gopost-script andquietcomment changes
Each one may be fine on its own, but together I can't review them with any confidence. As well, a revert of one piece shouldn't take the other two with it.
| upstream="$(mktemp)" | ||
| trap 'rm -f "${upstream}"' EXIT | ||
|
|
||
| if ! gh api -H "Accept: application/vnd.github.raw" \ |
There was a problem hiding this comment.
This compares the vendored copy with upstream at the pinned commit, so it only fails if someone edits the vendored file. If agents adds an enum value on main, this still passes. Should it compare against agents@main (or warn when the pin is behind HEAD)? Otherwise the release step is a no-op.
There was a problem hiding this comment.
Split, and this one is out of the three.
The drift check (script, its test, the Makefile entry and the release.yml
step) is not in any of the three PRs. The vendored review-result.schema.json
and its .pin stay in part 1, because the schema tests read them; the pin file is
now just the provenance record the test comment refers to.
You are right that as written it only fails when someone edits the vendored copy.
When I send it back as its own PR I will compare against agents@main and report
a stale pin, rather than diffing against the pinned commit — otherwise the release
step reports nothing useful.
Parts: #10082 (redactor + structural JSON), #10084 (spanning
private keys), #10085 (run.go post-script and quiet).
Note: Generated with assistance from DeepSeek V4.1 Flash
| // cannot run on to a later field's quote. The single-quoted branch keeps a | ||
| // raw newline inside the value matchable, as it was before the escape | ||
| // handling was added. The minimum length is enforced in scan, not here. | ||
| {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\[\s\S]|[^"\\\r\n])*)"|"([^"\r\n]*\\)"[ \t]*(?:,|\}|\]|$)|'((?:''|[^'\r\n])*\\)'[ \t]*(?:,|\}|\]|$)|'((?:''|\\\r?\n|\\.|[^'\r\n\\])*[^'\r\n\\])'|'([^']*)'|"((?:\\[\s\S]|[^"\\])*)"[ \t]*(?:,|\}|\]|$))`}, |
There was a problem hiding this comment.
Six capture groups, and correctness depends on Go trying the alternatives left to right. The comments and tests are good, but I worry about the next person who touches this. Would it be simpler to find the quoted value with the regex and read its end with a small scanner in code?
There was a problem hiding this comment.
I did not take this on in the split — it is a real refactor of the json_field
matcher, not a local edit, so it would have added churn to the very PR you asked
to keep small.
The shape today is that scan iterates the submatches of every structural
pattern and masks the first non-empty capture group, so a scanner-based
json_field would have to replace that path for one pattern only, and would have
to reproduce the cases the six branches cover: escaped delimiters inside a JSON
string, a value ending in a literal backslash, YAML's doubled single quote, and a
value folded across physical lines whose closing quote ends the field. Every one
of those has a regression in scanner_test.go, so I would rather do it as its own
change with that test matrix as the safety net, after this fix lands.
Parts: #10082 (redactor + structural JSON), #10084 (spanning
private keys), #10085 (run.go post-script and quiet).
Note: Generated with assistance from DeepSeek V4.1 Flash
| // Requiring the full mix keeps a hex-only run from masking a required field | ||
| // (head_sha, id, file) and loses no realistic body: a 64-character line, or a | ||
| // partial final line, almost always has all four. | ||
| func pemBodyRun(run []byte) bool { |
There was a problem hiding this comment.
The "16+ base64 chars, mixed case plus a digit, not hex only, joined runs" rule feels like it will misfire both ways over time, and the description already names one gap. I'd like to look at this on its own in the split. Do we know how often a review actually hits a key split across members, or is this defensive?
There was a problem hiding this comment.
It is defensive. Nothing in this repo's runs produces a review with a key split
across members — the case came out of review of the sanitizer itself, not from an
incident, and I have no telemetry to put a frequency on it.
You are right that the shape rule is the weak part: it decides from the character
distribution of a joined run, so it can misfire on adjacent ordinary values
(critical + ssrf + README was a real regression in this branch) and it still
misses some splits. The conservative alternative is to fail closed whenever a
region cannot be localized — losing the review, which is the #5705 failure — so
the heuristic exists to keep the review readable.
It is now isolated in part 2 (#10084), and that PR's description
and the doc section name the residual (one-character and longer chunks
alternating). If you would rather drop the localization and fail closed there,
that is a one-PR change on top of part 1.
Parts: #10082 (redactor + structural JSON), #10084 (spanning
private keys), #10085 (run.go post-script and quiet).
Note: Generated with assistance from DeepSeek V4.1 Flash
| } | ||
|
|
||
| // ResetRuntimeSecretsForTest clears the registry for tests. | ||
| func ResetRuntimeSecretsForTest() { |
There was a problem hiding this comment.
Minor. This exports a test hook from production code. internal/cli uses it too, so it may need to stay, but could the internal/security tests use an export_test.go instead?
There was a problem hiding this comment.
It cannot move to export_test.go: internal/cli/scan_output_telemetry_test.go
calls security.ResetRuntimeSecretsForTest (three tests register a runtime value
and need a clean registry), and export_test.go only reaches tests in its own
package. So the hook has to stay exported.
What I did change is the duplication: the internal/security tests are in-package
and now call resetRuntimeSecrets directly, so the exported wrapper is used only
by the cross-package tests, and its doc comment says exactly that. That is in part
1 (#10082).
Parts: #10082 (redactor + structural JSON), #10084 (spanning
private keys), #10085 (run.go post-script and quiet).
Note: Generated with assistance from DeepSeek V4.1 Flash
| origins and warnings are documented in | ||
| [Configuring with Skills § The persona list file](../guides/user/customizing-with-skills.md#the-persona-list-file). | ||
|
|
||
| ### The post-run output scan |
There was a problem hiding this comment.
The new section is about 150 lines and mostly repeats the code comments. Could it be trimmed to what the scan does and why? The details will drift from the code faster than anyone updates the doc.
There was a problem hiding this comment.
Trimmed, and split with the code it describes.
The section is now about 86 added lines across the three parts instead of 154:
part 1 (#10082) describes what the scan walks, the structural JSON path, the
whole-value rescan of the written bytes, and the fail-closed markers (~44 lines);
part 2 (#10084) describes the spanning-block handling (~18
lines); part 3 (#10085) adds the post-script gate and the
quiet behaviour (~24 lines).
I also dropped the paragraphs that restated the per-branch heuristics — the length
floor, the case mix, the joined-run rule, the single-character rule — and left
those to the code comments, keeping the doc to what the scan does and why.
Note: Generated with assistance from DeepSeek V4.1 Flash
|
🤖 Finished Review · ✅ Success · Started 2:42 PM UTC · Completed 3:02 PM UTC Commit: Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $3.34 |
|
Risk Assessment: elevated (3/5) DetailsScore remains elevated at 3 due to protected path changes (.github/workflows/release.yml, scripts/check-review-schema-pin*.sh), CI workflow modification, and high churn in execution paths (internal/cli/run.go) without a feature flag. |
ReviewFindingsMedium
Low
Earlier findings
Next steps:
2 finding(s) below the |
| flush() | ||
| continue | ||
| } | ||
| if len(material) == 1 && !allSingle { |
There was a problem hiding this comment.
[medium] logic-error
Mixed-length body chunks are not reconstructed. After a multi-character chunk, a one-character chunk flushes the pending group. Alternating one-character and longer chunks can therefore keep every group below the recognition threshold, leaving body material intact after the BEGIN and END members are masked. maskMiddleRecordBody repeats the same behavior for JSONL.
Suggested fix: Reconstruct candidate body material independently of chunk length, and apply the same correction to JSONL. Add regression cases with alternating one-character and longer chunks.
| // reconstructed and masked instead of surviving once the markers are | ||
| // gone (#5705). | ||
| spans.covered[i] = true | ||
| flush() |
There was a problem hiding this comment.
[low] logic-error
A recognized body line flushes preceding short fragments without using that line as evidence that the fragments belong to the body. For example, between the markers, "AQAB" followed by "MIIEowIBAAKCAQEAx7" leaves "AQAB" untouched: the short pending group fails pemBodyJoined before the recognized line starts a new group. JSONL has the same asymmetric treatment.
Suggested fix: Evaluate preceding candidate fragments together with the recognized body line before flushing, rather than seeding recognition only in the forward direction.
| if !upper || !lower || !base64Only { | ||
| return false | ||
| } | ||
| return hasMixedUpperRun(joined) |
There was a problem hiding this comment.
[medium] logic-error
The joined-body detector requires adjacent uppercase letters immediately followed by lowercase. That is not a base64 requirement. Short chunks such as "Ab1g", "Cd2h", "Ef3i", and "Gh4j" concatenate to 16 valid base64 characters but fail hasMixedUpperRun; none qualifies individually either. Consequently the body survives while its surrounding markers are removed. The JSONL implementation uses the same detector.
Suggested fix: Do not use the uppercase-run shape as a necessary condition for recognizing material inside an already detected private-key span. Cover valid base64 bodies without adjacent capitals in both document and JSONL tests.
| // a hash or an id (a "sha <hex> <body>" note), and stopping at that first | ||
| // hex-only run wrote the body back after the markers had been masked, where | ||
| // the written-bytes rescan can no longer see the block (#5705). | ||
| for _, run := range privateKeyMaterialRe.FindAll(text, -1) { |
There was a problem hiding this comment.
[low] logic-error
An isolated short body fragment is never masked. For example, [BEGIN, "MIIEb2R5", END] has a framing-spanning private-key match, but the middle value is shorter than privateKeyMaterialRe's 16-character minimum and its joined group is also shorter than 16. The sanitizer reports the block as localized and removes its markers while retaining the body fragment. Short final body lines encounter the same problem when no recognized neighbor remains in their group.
Suggested fix: Handle short fragments within a detected block conservatively instead of treating the per-run length floor as proof that they are safe. Add isolated short-fragment tests for JSON and JSONL.
| continue | ||
| } | ||
| var hit []int | ||
| for i, r := range v.ranges { |
There was a problem hiding this comment.
[low] logic-error
Each private-key match scans the complete leaf-range collection, and leafContaining also starts from the beginning for every match. A document containing many separate blocks therefore takes quadratic work in the number of leaves. Large generated transcripts or arrays with repeated marker pairs can make the mandatory post-run scan disproportionately slow.
Suggested fix: Exploit the ordered, non-overlapping match and leaf ranges with advancing cursors or indexed range lookup. Add a scaling regression test.
| continue | ||
| } | ||
| valBytes := v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end] | ||
| if isSchemaConstrainedField(v.memberKeys[i], string(valBytes)) { |
There was a problem hiding this comment.
[medium] secret-exposure
The schema-field exemption trusts a member's name without validating its value against a schema. Between recognized PEM markers, short body fragments stored under names such as file, category, severity, or id are excluded from reconstruction and flush the pending run. For example, fragments MIIEowIB, AAKCAQEA, and x9Kq2Lm under these names all survive. Marker-bearing boundary values and individually recognizable long body values are protected, but these short fragments are not. The JSONL counterpart has the same exemption. Once the markers are removed, the final whole-value scan cannot recognize the surviving body.
Suggested fix: Do not exempt arbitrary values solely by member name. Validate structural values against their actual constraints and retain a conservative containment path for ambiguous fragments within a detected block. Cover both JSON and JSONL.
| flush() | ||
| continue | ||
| } | ||
| if v.keys[i] { |
There was a problem hiding this comment.
[low] secret-exposure
Short PEM body chunks stored in object key names never join the reconstruction run. maskSpanBody skips every key, while spanningPrivateKeys only masks an interior key when that key independently passes textCarriesKeyMaterial. Thus a body split into keys such as MIIEowIB, AAKCAQEA, and x9Kq2Lm survives between masked boundary markers. Complete recognizable body-line keys are protected; short key-name fragments are not. The JSONL middle-record logic has the same distinction.
Suggested fix: Track candidate body fragments in key names as well as values, retaining their provenance so reconstructed material can be masked without renaming unrelated structural keys.
| flush() | ||
| continue | ||
| } | ||
| if len(material) == 1 && !allSingle { |
There was a problem hiding this comment.
[medium] secret-exposure
Alternating one-character and longer body chunks defeats reconstruction. Each single-character chunk following a longer chunk flushes the candidate run, so an entire body divided into sub-16-character groups can survive even though the enclosing BEGIN and END markers are detected and removed. Uniform single-character chunks and ordinary joined chunks are protected; mixed-length chunk sequences are not. maskMiddleRecordBody repeats this behavior for JSONL.
Suggested fix: Preserve an additional candidate reconstruction across mixed chunk lengths, or conservatively contain ambiguous material within a detected block instead of discarding the evidence at each one-character boundary.
| } | ||
| continue | ||
| } | ||
| if atBoundary || v.valueCarriesKeyMaterial(i) { |
There was a problem hiding this comment.
[low] secret-exposure
An isolated short body fragment immediately before a recognized long body line is left unmasked. maskSpanBody flushes the pending short-fragment group when it encounters the recognized line, before setting bodySeeded. A preceding AQAB therefore survives, while the long line and boundary markers are removed. The direct fallback here only recognizes complete material-shaped values and does not recover that fragment. Short fragments after a recognized line are protected by bodySeeded; short fragments before it are not. JSONL has the same ordering.
Suggested fix: When a recognized body line establishes the candidate group's provenance, include preceding adjacent candidate fragments in its masking decision rather than flushing them as an unrelated group.
| } | ||
| var hit []int | ||
| for i, r := range v.ranges { | ||
| if r.start < match[1] && match[0] < r.end { |
There was a problem hiding this comment.
[low] secret-exposure
Private-key localization only maps string leaves. collectJSONLeaves omits numeric leaves, so digit-only body fragments represented as JSON numbers are absent from both the reconstructed candidate body and the covered-member set. The writer scans those numbers for standalone runtime/prefix secrets, but not as material belonging to the surrounding detected private-key block. Boundary strings and recognizable string body chunks are protected; numeric body fragments can remain after those markers disappear.
Suggested fix: Include numeric scalar provenance in block localization and mask numeric fragments that belong to a detected block, writing a string placeholder where necessary to preserve valid JSON.
|
Finding threads left open (29):
Outdated review threads left open (1):
|
waynesun09
left a comment
There was a problem hiding this comment.
Review sweep: 3 findings, posted inline (1 HIGH, 2 MEDIUM).
| var scanErr *outputScanError | ||
| scanFailed := errors.As(runErr, &scanErr) | ||
| if scanFailed { | ||
| if resultFile, ok := agentResultFile(h, outputDir); ok && scanErr.failedOn(resultFile) { |
There was a problem hiding this comment.
[HIGH] Post-script gate checks the last iteration's result file, but the post-script reads the validated iteration's file
postScriptGate is always given iteration-<runCount>/output (run.go:2503). The post-script instead gets FULLSEND_VALIDATED_ITERATION_DIR=iteration-<validatedIterNum>/output (postScriptRepoEnv, run.go:5326-5327). The post-loop sweep can validate an earlier iteration (run.go:3487).
In that case the guard scanErr.failedOn(resultFile) here checks the last iteration's file, not the one that gets posted. The new scan-only branch (run.go:4527-4536) then runs the post-script whenever the last iteration left a result file that parses.
Example: the sweep validates iteration 1, iteration 2 left a parseable result, and the scan could not write or sanitize iteration-1/output/agent-result.json. The guard passes and the post-script runs. The scaffolded post.sh template already reads FULLSEND_VALIDATED_ITERATION_DIR/agent-result.json (internal/agentnew/templates/post.sh.tmpl:55-57), so it would post the unredacted file.
This is not just latent. On main any scan failure made runErr non-nil and the gate skipped the post-script, so this PR adds the exposure path.
Suggestion: Pass the effective output directory to postScriptGate: the validated iteration's output when ValidationLoop is set and validatedIterNum > 0, else the last iteration's. Use the same path for the failedOn check and the scan-only agentResultFile lookup. Add a test where the sweep validates an earlier iteration, the scan fails on that iteration's result file, and the later iteration's result parses. Assert the post-script is skipped.
Verified: read code at head (run.go:2503, 3487, 4483-4536, 5322-5329; post.sh.tmpl:55-57) and compared to base 4db7ae7 postScriptGate at 99b1662; raised by: DeepSeek
| // cannot run on to a later field's quote. The single-quoted branch keeps a | ||
| // raw newline inside the value matchable, as it was before the escape | ||
| // handling was added. The minimum length is enforced in scan, not here. | ||
| {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\[\s\S]|[^"\\\r\n])*)"|"([^"\r\n]*\\)"[ \t]*(?:,|\}|\]|$)|'((?:''|[^'\r\n])*\\)'[ \t]*(?:,|\}|\]|$)|'((?:''|\\\r?\n|\\.|[^'\r\n\\])*[^'\r\n\\])'|'([^']*)'|"((?:\\[\s\S]|[^"\\])*)"[ \t]*(?:,|\}|\]|$))`}, |
There was a problem hiding this comment.
[MEDIUM] json_field leaves a multi-line double-quoted secret unmasked when prose follows the closing quote (regression from main)
On main, the double-quoted json_field branch "([^"]{8,})" matched across raw newlines. At head, the strict branch stops at \r\n. The only branch that still allows a raw newline needs ,, }, ] or end of line after the closing quote. A quoted multi-line value followed by prose (. Done, and more, )) now matches nothing and is printed in the clear.
This is a follow-up to the earlier thread on f_669fdfcadd395fe6: the abc24a1 fix covers values whose closing quote ends the field or the line, but not this shape. No test pins it.
Suggestion: Add a last fallback alternative with main's semantics, "([^"]{8,})", after the bounded branches. With leftmost-first matching it fires only when every escape-aware branch fails. Add a scanner test for "password": "abcdefgh\n ijklmnop". Done that asserts the value is masked.
Verified: reproduced: go run of head and base json_field regexes on Set "password": "abcdefgh\n ijklmnop". Done and "password": "abcdefgh\nijklmnop" and more; head matched "" for both, base matched the value at 99b1662; raised by: Claude
| masking free text and enum values, which loses the review, and keeping a fragment | ||
| too short to be recognized as key material. Because one member holds only one line | ||
| of a body, the values between the boundary members are also decided on their | ||
| joined text: consecutive base64-only values are concatenated, and if the result |
There was a problem hiding this comment.
[MEDIUM] This paragraph describes a PEM-run heuristic the code no longer implements
The doc says consecutive base64-only values are concatenated and must show "a digit or a run of adjacent capitals", and that "a value with punctuation or whitespace breaks the run". The code does neither:
maskSpanBody(jsonsanitize.go:503) callspemBodyRuns, which pulls the base64 runs out of any value, prose included, and joins them. Whitespace and punctuation no longer break the run.pemBodyJoined(jsonsanitize.go:601-631) no longer accepts a digit. It requireshasMixedUpperRun: two or more capitals followed by lower case. So prose such asUpdated README instructionsbecomesUpdatedREADMEinstructionsand qualifies as body material.
Contributors reading the doc will misjudge what free text gets masked between quoted markers. The bot thread at jsonsanitize.go:621 covers the false positive in code; this one is about the doc contradicting the code.
Suggestion: Rewrite the paragraph to match pemBodyRuns and pemBodyJoined/hasMixedUpperRun, and mention the schema-constrained-field exemption. Or, per the earlier comment on this section's size, cut it to a short summary that points at the code comments.
Verified: read code at head (jsonsanitize.go:268-282, 470-520, 601-650) against the doc lines 683-700 at 99b1662; raised by: DeepSeek
|
Split into three, as asked. Each one is a single commit on its own branch, so a
Each of 2 and 3 is based on the branch below it, so its diff is cumulative until To answer the five inline points briefly: the schema-pin drift check is out of all This PR is superseded by the three and can be closed. Detail is in the individual Note: Generated with assistance from DeepSeek V4.1 Flash |
|
Closing in favor of the three split PRs: #10082 (redactor + structural JSON, closes #5705), #10084 (spanning private keys), #10085 (run.go post-script and Note: Generated with assistance from DeepSeek V4.1 Flash |
Summary
Fixes #5705 by preventing the post-agent output sanitizer from corrupting JSON syntax during secret redaction, while guaranteeing fail-closed security for all output files.
The fix introduces a dual-layer strategy:
internal/security/jsonsanitize.go): Primary defense-in-depth fix for JSON files (such asagent-result.json). Outputs that parse as JSON are decoded into data structures, where object keys and string leaves are recursively scanned and redacted individually before re-encoding. This guarantees that redaction within string values never alters JSON framing syntax.internal/security/redactor.go): Fix for non-JSON files (markdown, JSONL streams, plaintext) and raw text scans. Delimiter-escaping backslashes (such as\"or\') are detected and excluded from credential capture spans so that escaping is preserved without breaking string delimiters, while credentials containing interior or trailing backslashes remain fully matched and redacted.Root cause & background
In the post-agent output scanning pipeline (
scanOutputFiles), regex patterns were previously executed as a raw text find-and-replace across all output files. When an agent's output included code discussion containing environment assignments or credentials inside a JSON string value—for example:{"remediation": "Guard against null values with token_usage = metrics.get(\"token_usage\") or {}"}the raw regex matched up to the quote delimiter (
metrics.get(\), eating the escaping backslash. The redacted replacement produced:swallowing the backslash and leaving an unescaped quote delimiter inside the JSON string. This corrupted the JSON structure and caused downstream tools (
jqinpost-review.sh) to fail with exit status 5 (e.g. in konflux-ci/scribe4jira#32 / workflow run 30361396360 and fullsend-ai/fullsend#7553 / run 42022572317).What changed in this PR
1. Structural JSON Path (
internal/security/jsonsanitize.go)scanOutputFilestreats a file as a single JSON document only whensecurity.IsJSONDocumentaccepts it;.jsonl/.ndjsonfiles are handled per record so a stream is never mistaken for one document.IsJSONDocumentignores a leading UTF-8 BOM, whichjson.Validandbytes.TrimSpaceboth reject, so a BOM-prefixed document no longer falls through to the text scan where a redaction can still break its syntax.SanitizeJSONDocumentstrips the BOM, scans the document, and restores the mark on write, and returns a clean document byte for byte.dec.UseNumber()to keep numbers asjson.Number, avoidingfloat64precision loss for integers above 2^53 (e.g.12345678901234567891) and preserving float formatting like1.0.rewriteJSONTokensvisits every object key and scalar leaf, so an earlier occurrence of a duplicate key is scanned instead of being dropped by map decoding, and member order is preserved (a secret that spans members stays visible in the rewritten bytes).pipeline.Scan(k). A key that sanitizes to nothing (bidi overrides, null bytes) is replaced withredacted, never restored. Names are resolved after the whole object is read: clean keys reserve their names first, and a sanitized name that would collide with a different member is disambiguated (<key>_<N>) while intentional duplicate keys keep sharing one name. The member's original key decides whether its value is sensitive, so a masked key cannot drag a clean value intojson_fieldmasking.misconfiguration) or a path (internal/security/jsonsanitize); every run in the value is checked, so a body that follows a hex prefix (sha <hex> <body>) is still found; a hex-only run is kept, because a PEM body is base64 while a hex run is more likely ahead_shaor a findingid. Object keys keep their names, because a key name is the document's structure, and are masked only when the match starts or ends in them, when the name itself carries a marker, or when the name is itself a line of body material — a key name that is base64 is key material, and keeping it would write the body back after the markers were masked. A key never joins the joined-run test, because letting one join a group that also holds body material would rename required schema keys such asseverityandfile. A review result that merely quotes the header in one finding and the footer in another therefore keeps its shape —action,pr_number,repo,head_shaand each finding'sseverity,category,file,idanddescriptionkeep valuesreview-result.schema.jsonaccepts, so enum masking no longer makes validation reject the review — and values outside the matched span keep their content. A block that cannot be mapped onto leaves fails closed with its own marker.failClosedCrossRecordPrivateKeysbuilds a decoded view of the stream (newJSONLineView) that keeps each record's decoded leaves next to the record they came from, so a private-key block crossing records is found even when a marker is written with\uescapes or the record carries a leading UTF-8 BOM (a BOM-prefixed record is stripped and decoded like any other, instead of being read as plain text). Only the records that carry block content are replaced: the boundary records always, a record between them only when its leaves hold a marker or PEM body material, decided like the single-document path — including the joined run of consecutive base64-only values. A transcript that quotes the header in one record and the footer in a later one therefore keeps its clean records.SanitizeJSONLinesrescans the rebuilt stream for whole-value secrets only (ScanWholeValueSecrets: registered runtime values and private-key blocks), the same set the single-document path scans in its written form. Running the value patterns again re-matched a redaction placeholder followed by JSON escape bytes — in encoded JSON a\nescape is two non-space bytes, soenv_assignmentran past the end of a value the record pass had already masked — and replaced correctly redacted and benign records with the cross-record marker. A within-record whole-value secret is handled bySanitizeJSONDocument, and a block spanning records byfailClosedCrossRecordPrivateKeys.failClosedInvalidJSON,failClosedCrossRecordJSON, andfailClosedSpansMembersJSONeach state why the document was dropped, andsecurity.OutputRemovalrecognizes them.scanOutputFilesfails the run closed when it cannot read, sanitize or write an output file: the walk still visits every remaining file, the file it could not handle is replaced with a marker (or removed) so unredacted bytes do not reach the artifact, and all failures are joined into the run error. The result the agent left is still reported: when the scan failed on some other file and the harness's result file survived it and still holds a JSON object, the post-script runs and the run still fails, while a result file the scan failed on (its write or sanitization failed and the quarantine could not replace it) and one it replaced with a marker are both refused. The scan error is joined with the run's own terminal outcome rather than replacing it, so a run whose agent also failed keeps itsagentFailedErrorand the post-script still receivesFULLSEND_AGENT_EXIT_CODE. The plain-text fallback carries no marker of its own: a document that parses as JSON takes the structural path, so it cannot be turned into invalid JSON there.scanOutputFileswrites a::error::workflow command for a replaced file wheneverGITHUB_ACTIONS=true, which GitHub Actions and Forgejo Actions both set, so a lost review does not pass silently in a run that still exits 0. GitHub Actions renders the command as an error annotation; Forgejo has no annotation view, so its runner prints the line in the step log and the exit status stays 0.2. Regex Redaction & Quote Escape Preservation (
internal/security/redactor.go)env_assignment([^\s"'}\]),;]{8,}),auth_header(12), anddb_connection_password(4), ensuring credentials with multiple backslashes meet required length thresholds."or'), the redactor counts trailing backslashes. If odd, the trailing backslash escapes the delimiter quote and is trimmed from the secret span so the escape remains intact in the text.json_fieldis exempt because its value pattern already consumes escaped delimiters.json_fieldMinimum: Thejson_fieldvalue pattern now spans escaped quotes —"((?:\\[\s\S]|[^"\\])*)"plus three single-quoted alternatives (the literal trailing backslash bounded by a field or line boundary, the escape-reading form, and the raw-newline form) — so it carries no length quantifier. The bounded branch is tried first because Go's regexp alternation is leftmost-first: otherwise{'api_key': 'abcdefghi\', 'x': '…'}read the closing quote as an escape and swallowed the field that follows. Its minimum is enforced by a gate inScanthat counts runes (utf8.RuneCountInString, 8) on the span after the escape trim and beforeMaskis computed, matching the character semantics of the{8,}quantifier it replaced.sanitizeJSONStringapplies the same rune-counted minimum when a sensitive key masks its value.env_assignment,auth_header, anddb_connection_passwordno longer appear in that gate because their patterns already enforce their own minimum.Mask()Safety: Exported assecurity.Maskand updated to output"***"whenever a prefix contains a backslash, avoiding dangling escape sequences.3. Expanded Test Coverage
internal/cli/scan_output_telemetry_test.go: Added multi-case suite (TestScanOutputFiles_PreservesJSONStructuralValidity) verifying:<,>,&) are not escaped.TestScanOutputFiles_EmitsAnnotationWhenOutputIsRemovedpins the::error::line for a replaced file, its absence outside Actions, and that a Forgejo run (GITHUB_ACTIONS=trueplusFORGEJO_ACTIONS=true) writes the same line;TestScanOutputFiles_SanitizesBOMPrefixedJSONStructurallypins the BOM path.TestScanOutputFiles_UnreadableFileFailsClosedandTestScanOutputFiles_UnreadableDirectoryFailsClosedpin that a read failure contains the file and fails the run, andTestScanOutputFiles_QuietReadFailureKeepsPathOutOfMessagepins the quiet contract.internal/security/jsonsanitize_test.go: Unit tests for the sanitizer, including a private key split across members, a cross-member private key in a document that is already being rewritten, a sanitized key that must not steal a clean member's name, two disjoint cross-record JSONL matches separated by a clean record that must survive, a review-result-shaped document (withaction,pr_number,repo,head_sha, and findings carryingseverity,category,file,idanddescription) whose header/footer pair is quoted in different findings and whose sanitized output is validated against thereview-result.schema.jsonconstraints (enum lists, patterns, required members, no additional properties) rather than merely non-empty, a split block that keeps structural enums while masking the key material, a marker split across members, hex values (head_sha, findingid) inside a span, a block marker inside a key name that must be masked, a body that follows a hex prefix in the same value (every material run is checked, not only the first), a path and a long word between quoted markers that keep their content, value-only span coverage, JSONL records holding a redacted or benign env assignment before an escaped newline that must not be replaced, a quoted header and footer that keep the clean records between them, a body split into short digit-free records that is still covered, a BOM-prefixed record carrying a\u-escaped marker, andOutputRemoval/spanningPrivateKeysunit coverage.internal/security/scanner_test.go: Added boundary tests forenv_assignment,auth_header, anddb_connection_passwordat exact minimum lengths with interior and trailing backslashes, plus a rune-vs-byte test for thejson_fieldminimum.Verification
go test ./internal/security/...passed (92.4% statement coverage for the package).go test -run 'TestScanOutputFiles|TestSanitizeJSON' ./internal/cli/andgo test ./internal/security/...passed.make lint/ pre-commit passed cleanly (gofmt,go vet,semgrep security audit,gitlint, secrets, and link checks).go test ./...was also run locally. The only failures are pre-existing on currentmainand environmental:TestRunGatewayRefresh_PendingHandOff*(internal/cli) fails identically on the merge base.TestApplyCIServerTLSCA_TrustsPrivateCAAndRejectsUntrusted(internal/forge/gitlab) fails identically on the merge base (macOS system CA pool).TestCheckKillSwitchStep_ConsultsConfigBaseYAML(internal/scaffold) needs bash 4+ and passes with/opt/homebrew/binfirst inPATH.Closes #5705
Checklist
!for breaking changes)