Skip to content

fix(#5705)!: stop JSON redaction from eating escaping backslashes - #10082

Open
andrewevansrh wants to merge 6 commits into
fullsend-ai:mainfrom
andrewevansrh:agent/5705-json-sanitizer
Open

andrewevansrh wants to merge 6 commits into
fullsend-ai:mainfrom
andrewevansrh:agent/5705-json-sanitizer

Conversation

@andrewevansrh

@andrewevansrh andrewevansrh commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Refs #5705. The post-agent output sanitizer ran every pattern as a raw text
find-and-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
jq in post-review.sh failed with exit status 5.

This PR is the first of three split out of #9699, and the stack lands in this
order:

  1. this one — the redactor escape fix plus the SanitizeJSONDocument /
    SanitizeJSONLines library primitives (Refs Output sanitizer should validate JSON structural integrity after redaction #5705)
  2. fix(#5705): mask private-key blocks that span JSON members or records #10084 — private keys that span members or records
  3. fix(#5705): run the post-script when the scan was the only failure #10085 — the scanOutputFiles wiring, the run.go post-script and quiet
    comment changes, and the docs that describe them

2 and 3 are drafts until they are unblocked: each is based on the branch below it,
so its diff is cumulative today. After this one lands I rebase #10084 onto main,
its diff drops to its own commit and it goes ready for review; the same then
happens for #10085. Reviewing this one is unblocked.

Runtime reach at this commit. The redactor changes take effect immediately in
every existing Pipeline.Scan caller (the text output scan, prompt scanning and
the finding details). The structural sanitizers are library primitives here: the
CLI output scan still calls the text pipeline, so JSON output is not yet routed
through them and #5705 is not closed until #10085 wires them in. The docs that
describe the structural output scan live in #10085 with the code that implements
it, and this PR no longer documents or claims that behaviour.

What changed

  • internal/security/redactor.go: a delimiter-escaping backslash is excluded
    from the captured value, and the mask falls back to *** when the prefix it
    would keep carries an escape or a quote delimiter, so the mask itself cannot
    break the string it is spliced into.
  • The json_field pattern matches escaped and multiline quoted values without
    running on to a later field's quote. A double-quoted value that ends in a
    literal backslash is matched by a bounded branch that keeps the closing quote
    out of the capture, so an adjacent field's delimiter — and its credential — is
    no longer swallowed.
  • The bounded value branches accept a CRLF line end, a last-resort branch masks a
    trailing-backslash value that is followed by neither a field nor a line end, and
    scan prefers the escape reading when that reading closes the string at a JSON
    value boundary and covers more than the bounded one — so
    {"password":"ab\",cdefgh"} is masked whole instead of up to the escaped
    quote.
  • internal/security/jsonsanitize.go: JSON output is rewritten by 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 before the walk and restored on write;
    a clean document comes back byte for byte. An array under a sensitive member
    keeps that member's name for its elements, so {"tokens": ["…"]} is masked even
    though an element matches no pattern of its own; a nested object does not, since
    its members carry their own names. Content that cannot be redacted in
    place is replaced with a valid {"error":"output removed because …"} marker
    rather than corrupted JSON, and a cross-record match replaces only the records
    it covers — a clean record between two disjoint matches, duplicates included,
    is written back unchanged.
  • The whole-value backstop scans the rebuilt document rather than the bytes it
    received, and does so even when no leaf produced a finding, so a private-key
    block whose markers are JSON-escaped and split across leaves is detected and
    the document fails closed instead of being returned unchanged. When that scan
    is clean it also scans the original bytes, which are what a clean document
    writes back: the rebuilt form compacts whitespace, so a registered runtime
    value spanning framing plus whitespace exists only there.
  • internal/security/testdata/review-result.schema.json vendors the harness
    schema so the tests assert that a sanitized review keeps the shape the harness
    validates. review-result.schema.pin records the upstream revision it was
    copied from; refreshing it is a manual step, as the pin comment says.

Breaking change

A masked value is written *** instead of its first four bytes plus ...
whenever that prefix would carry a backslash or a quote delimiter, and
json_field now matches escaped-quote and multiline quoted values it previously
did not. A double-quoted value that ends in a literal backslash is now masked on
a CRLF line or before trailing text, and a valid JSON value whose escaped quote is
followed by a separator is masked whole rather than up to the escaped quote.
Sanitized output text and finding details therefore differ for those inputs.

Verification

  • go test ./internal/security/ (also with -race)
  • go test ./internal/cli/ -run 'TestScanOutput|TestContentCollector'
  • make lint

Note: Generated with assistance from DeepSeek V4.1 Flash

@qodo-code-review

qodo-code-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Fix JSON output redaction corrupting escaped backslashes (#5705)

🐞 Bug fix ✨ Enhancement 🕐 40+ Minutes

Grey Divider

AI Description

• Rewrites JSON and JSONL output through a token-preserving walk, so redaction cannot break syntax.
• Stops secret capture from consuming escaping backslashes, and masks placeholders that would break
 strings.
• Replaces unredactable records with valid fail-closed markers and reports the reason to operators.
Merge Risk 🔴 High

Blast radius 🟡 Medium 💥 2 capabilities

  • 2 affected capabilities within one bounded functional scope: output-secret-redaction.
  • The redactor, scanner, collector, and post-review path form one bounded output-protection integration: they transform or transport the same user-visible content to reviews, CLI output, collected artifacts, and telemetry-derived values.
  • Review finding fields are explicitly sanitized before forge submission, while the other consumers are propagation surfaces of the same credential-redaction behavior.
  • The exported document and JSONL sanitizers are structured-output implementations within the same bounded output-secret-redaction integration.
  • Token rewriting, record preservation, sensitive-key inheritance, decoded whole-value rescanning, original-byte rescanning, and fail-closed localization form one affected end-to-end capability.
Behavioral complexity 🔴 High 🧩 Multiple interactions

  • Before: the sanitizer rescanned rebuilt serialized output and could return original bytes when both the leaf walk and rebuilt scan were clean, and duplicate cross-record alignment preferred the earliest matching record.
  • After: it rescans original bytes before declaring a document clean and chooses the later original record when tied duplicate anchors compete.
  • New correctness conditions: decoded rebuilt content, original bytes actually written, leaf findings, byte-preservation guarantees, rewritten JSON validity, cross-record match coverage, duplicate-record identity, and fail-closed localization must agree without duplicate findings or re-masking placeholders.
  • Existing conditions for escaped markers, duplicate keys, sensitive arrays, CRLF framing, and record alignment remain active.
  • The tie-break change fixes localization of an existing interaction rather than introducing a separate capability.
Potential damage 🔴 High 🩹 Confidentiality

  • If matching, masking, or rescan logic regresses, credentials can remain in review text, CLI output, collected content, or telemetry-derived values.
  • The verified post-review path sends sanitized body and finding fields to the forge, but no downstream boundary independently repairs a missed secret.
  • Reverting restores future redaction behavior, but credentials already emitted into reviews, logs, artifacts, or telemetry require external cleanup and rotation.
Assessed commit 364b1ff
Diagram

graph TD
  A["scanOutputFiles"] --> B{"JSON document or JSONL?"}
  B -->|"single document"| C["SanitizeJSONDocument"]
  B -->|"JSONL records"| D["SanitizeJSONLines"]
  C --> E["SecretRedactor.Scan"]
  D --> E
  E --> F["Mask"]
  C --> G["ScanWholeValueSecrets"]
  D --> G
  G --> H["Fail-closed marker"]
  H --> I["OutputRemoval alert"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Regex-only escape fix
  • ➕ Small diff confined to redactor.go
  • ➕ No new JSON walker to maintain
  • ➖ Does not handle secrets split across members or records
  • ➖ Text-level rewrite can still produce invalid JSON for other patterns
  • ➖ Does not address placeholder re-masking on the serialized bytes
2. Decode into map and re-encode
  • ➕ Simple to implement with encoding/json
  • ➕ Guarantees valid JSON output
  • ➖ Drops duplicate keys, so a secret in an overwritten value is never scanned
  • ➖ Sorts member order and changes the byte stream of clean documents
  • ➖ Re-encoding can rewrite number literals

Recommendation: The PR's approach is justified. A token-preserving walk with per-leaf scanning is the only option found that avoids breaking JSON framing while still catching secrets that span members, and the whole-value-only rescan avoids re-matching placeholders. Dismissed alternatives: a regex-only escape fix, which leaves the chunked-key and framing-spanning cases open; and decoding into a map and re-encoding, which drops duplicate keys and member order, so earlier secret occurrences would go unscanned.

Files changed (11) +2866 / -27

Enhancement (2) +696 / -0
jsonsanitize.goNew token-preserving JSON and JSONL sanitizer with fail-closed markers +660/-0

New token-preserving JSON and JSONL sanitizer with fail-closed markers

• Adds SanitizeJSONDocument and SanitizeJSONLines, which walk JSON tokens, sanitize each key and scalar leaf, and re-encode while keeping member order, duplicate keys, and numbers. Also adds BOM handling, a sensitive-key mask for json_field, key collision renaming, whole-value rescans of serialized output, record-level localization of cross-record matches, and OutputRemoval for operator alerts.

internal/security/jsonsanitize.go

scanner.goAdds Pipeline.ScanWholeValueSecrets for serialized-output rescans +36/-0

Adds Pipeline.ScanWholeValueSecrets for serialized-output rescans

• Runs only scanners that implement ScanWholeValueSecrets, so the structural path can rescan serialized bytes for runtime values and private keys without re-running value patterns.

internal/security/scanner.go

Bug fix (1) +150 / -23
redactor.goExcludes escaping backslashes from captures and hardens Mask +150/-23

Excludes escaping backslashes from captures and hardens Mask

• Trims a trailing backslash that escapes a following quote from the captured secret, and drops the 'already masked' skip so real short secrets are masked. Mask returns *** when its prefix contains a backslash, quote, or escape. The json_field pattern now matches escaped and multiline quoted values with a rune-based minimum, and ScanWholeValueSecrets runs only whole-value patterns.

internal/security/redactor.go

Tests (3) +1948 / -0
jsonsanitize_test.goAdds tests for structural JSON sanitization and fail-closed behavior +1442/-0

Adds tests for structural JSON sanitization and fail-closed behavior

• Covers duplicate keys, chunked PEM bodies across members and records, BOM and CRLF framing, key collisions, the review-result schema shape, idempotence, and the OutputRemoval markers. Some test doc comments appear attached to the wrong functions.

internal/security/jsonsanitize_test.go

scanner_test.goAdds regression tests for backslash, json_field, and Mask behavior +298/-0

Adds regression tests for backslash, json_field, and Mask behavior

• Adds table cases for escaped quotes in JSON strings, backslashes in env, DB, and auth credentials, YAML doubled quotes, multi-line json_field values, rune-counted minimums, and placeholder re-masking.

internal/security/scanner_test.go

review-result.schema.jsonVendors the review-result schema as a test fixture +208/-0

Vendors the review-result schema as a test fixture

• Adds a pinned copy of the harness review-result schema so tests can check that sanitized reviews keep required members, enums, and patterns.

internal/security/testdata/review-result.schema.json

Documentation (4) +62 / -4
runtime-implementation.mdDocuments the post-run output scan and its fail-closed behavior +44/-0

Documents the post-run output scan and its fail-closed behavior

• Adds a section describing which files the output scan covers, how JSON and JSONL are sanitized structurally, and when fail-closed markers replace content. It also covers the GITHUB_ACTIONS error annotation and how read, write, and removal failures are reported.

docs/contributing/runtime-implementation.md

tracing.mdNotes that the connection-string placeholder is itself masked +1/-1

Notes that the connection-string placeholder is itself masked

• Updates the description of the runtime-secret pass so the placeholder left for a long connection-string password is recorded as masked ***, and counts as a finding.

docs/guides/dev/tracing.md

run-artifacts-and-private-data.mdExplains JSON error markers and operator annotations for redaction +14/-1

Explains JSON error markers and operator annotations for redaction

• Describes when a secret replaces a whole JSON document or JSONL record with an error marker, when the run still exits 0, and which platforms emit the ::error:: annotation.

docs/guides/user/run-artifacts-and-private-data.md

content_collector.goUpdates comment on the placeholder re-match behavior +3/-2

Updates comment on the placeholder re-match behavior

• Comment-only change clarifying that a placeholder for a long connection-string password is masked as *** when rescanned, while shorter passwords are not matched.

internal/cli/content_collector.go

Other (1) +10 / -0
review-result.schema.pinPins the vendored schema to an upstream commit +10/-0

Pins the vendored schema to an upstream commit

• Records the upstream repository, commit, and path of the vendored schema, and names a drift-check script that the file references.

internal/security/testdata/review-result.schema.pin

@fullsend-ai-review

fullsend-ai-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 3:49 PM UTC · Completed 4:03 PM UTC

Commit: 2a04c6a · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $3.45

@qodo-code-review

qodo-code-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. JSON output is still redacted as raw text 🐞 Bug ≡ Correctness
Description
scanOutputFiles still passes every output file through whole-file pipeline.Scan and writes
result.Sanitized, without calling SanitizeJSONDocument or SanitizeJSONLines. For JSON
artifacts such as agent-result.json, raw-text rewrites can break framing before the post-script
parses the file, while encoded sensitive keys such as pass\u200bword can leave opaque values
unmasked.
Code

internal/security/jsonsanitize.go[R139-142]

+func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) {
+	if !IsJSONDocument(doc) {
+		return doc, nil, nil
+	}
Evidence
The output-file walker in internal/cli/run.go reads each file, calls pipeline.Scan, and writes
its raw-text result back; it does not call the structural entry points in
internal/security/jsonsanitize.go, whose callers are limited to that file and its tests. The
pipeline applies NFKC to raw file text, which can turn fullwidth quote or backslash characters into
JSON framing characters, and a replacement spanning JSON members can also disrupt framing. The new
structural test masks an encoded sensitive key, but it tests the helper rather than the production
output scan; the post-script subsequently parses the result file.

internal/cli/run.go[7298-7325]
internal/security/unicode.go[218-218]
internal/security/jsonsanitize.go[226-303]
internal/cli/run.go[7259-7270]
internal/cli/run.go[7305-7329]
internal/security/jsonsanitize.go[139-169]
internal/agentnew/templates/post.sh.tmpl[91-99]
internal/cli/run.go[7297-7334]
internal/security/jsonsanitize_test.go[1158-1175]
docs/guides/user/run-artifacts-and-private-data.md[345-351]
Skill: check-patch-coverage
Skill: writing-user-docs

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The production output scan does not use the new structural JSON sanitizers. Raw-text scanning can corrupt JSON before the post-script parses it and can miss sensitive keys whose spelling is encoded in the document.

## Fix Focus Areas
- internal/cli/run.go[7259-7334]
- internal/security/jsonsanitize.go[34-58]
- internal/security/jsonsanitize.go[129-170]
- internal/security/jsonsanitize.go[221-226]

## Recommended Fix
In `scanOutputFiles`, detect JSON documents with `security.IsJSONDocument` and route them through `security.SanitizeJSONDocument`. Route `.jsonl`/`.ndjson` files, or content recognized by `security.IsJSONLines`, through `security.SanitizeJSONLines`. Keep `pipeline.Scan` as the fallback for other files, and handle sanitizer errors without leaving unredacted content available for upload. Add end-to-end output-scan tests covering an escaped quote in `agent-result.json` and an encoded sensitive key.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


2. A later password escapes redaction ✓ Resolved Bug Security

Resolving commit: 429a03d

Resolution reason
Moved the bounded double-quoted branch (ending in a literal backslash before the closing quote)
ahead of the escape-reading double-quoted branch in the json_field regex, so the escape-reading
branch no longer swallows the comma and next field's opening quote; added a regression test covering
two adjacent sensitive double-quoted fields.
Description
The first double-quoted json_field alternative treats a backslash before a quote as an escape and
can consume the next field's opening quote before the bounded fallback is tried. In raw output such
as "api_key": "abcdefghi\", "password": "fake-fake-fake-fake", its capture includes the comma, so
replacement damages the field framing and the password field is not matched.


Remediation recommended

3. Clean duplicate records are discarded ✓ Resolved Bug Correctness

Resolving commit: 429a03d

Resolution reason
The changedRegion first-to-last interval and the per-record counts/bytes.Index check are removed.
failClosedRecordSpans now aligns original records with the redacted stream via
affectedRecords/nextAnchor (longest verbatim run anchors), so only records not paired up are marked
affected, and clean duplicates between matches are copied through. A new test
TestSanitizeJSONLines_DisjointCrossRecordMatchesKeepCleanDuplicateRecords pins exactly the scenario
in the finding.
Description
failClosedRecordSpans treats the entire interval between the first and last stream changes as
affected and retains a record inside it only when its bytes occur once. With two separate
cross-record matches and duplicate clean records between them, it replaces those untouched records
with error markers too.

4. Docs promise fail-closed behaviour that does not run ⊘ Outdated Bug Maintainability
Description
The new docs say JSON files are sanitized structurally and that unredactable content becomes a
{"error":...} marker with a ::error:: annotation. They also say read/write/sanitize failures
fail the run with joined errors. None of this happens in this PR: scanOutputFiles only calls
StepWarn and returns nil when a write fails, which leaves the unredacted file on disk. Operators
and users reading run-artifacts-and-private-data.md will assume an unwritable redaction stops the
run and never reaches the artifact, but today it is uploaded with only a warning.


Informational

5. Test-only registry reset is public production API ✓ Resolved Bug Maintainability

Resolving commit: 429a03d

Resolution reason
The author deleted the exported ResetRuntimeSecretsForTest function (and its comment) from
redactor.go, so production code can no longer clear the global runtime-secret registry through it.
Description
ResetRuntimeSecretsForTest is an exported function in a non-test file. It clears the global
runtime-secret registry, and no code in this PR calls it. Any production caller that imports
internal/security can wipe the registered credential values, after which exact runtime secrets are
no longer masked in output.

Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #9699
✅ Compliance rules (platform): 39 rules
✅ Cross-repo context — repo relationships
  Explored: repo: fullsend-ai/agents (sha: 9061835a) — View relationship
  Explored: repo: fullsend-ai/metrics (sha: 0d77601f) — View relationship
Review mode: Auto: 🧠 Deep: Large security-sensitive sanitizer redesign spans multiple independent logic paths.

Grey Divider

Tip of the day
💡 Did you know, you can move or hide resolved findings to focus on what still needs action

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread internal/security/redactor.go Resolved
Comment thread internal/security/jsonsanitize.go Resolved
Comment thread internal/security/jsonsanitize.go Resolved
Comment thread internal/security/redactor.go Resolved
@github-actions

github-actions Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Site preview

Preview: https://dba39af9-site.fullsend-ai.workers.dev

Commit: 364b1ffdb7ddd0353a3a1a75839171cc519df7ee

@fullsend-ai-review

Copy link
Copy Markdown

Risk Assessment: moderate (2/5)

Details

Large diff driven predominantly by test suites and schemas with elevated historical churn in modified files, balanced by zero protected path or dependency changes, an established contributor, and close alignment with linked issue #5705.

@fullsend-ai-review

Copy link
Copy Markdown

Review

Findings

High

Medium

  • [secret-exposure] internal/security/jsonsanitize.go:139 — Because the sanitizer is not wired in, JSON-escaped credentials (e.g. a PAT starting with a \u0067 escape for g) still bypass the raw-text patterns and can reach artifacts. Pre-existing, not yet closed.
    Remediation: Route output files through the structural sanitizers in scanOutputFiles and add end-to-end tests for escaped credentials in keys and values.
  • [test-inadequate] internal/security/scanner_test.go:284 — The placeholder-rescan subtest fails on its first scan: hunt... is seven bytes, so Mask returns ***, contradicting the require.Equal expecting hunt... and the preceding abcd... → *** subtest. (Traced by reading; tests could not be run in the review sandbox.)
    Remediation: Use a real password of at least ten bytes starting with hunt, assert it becomes hunt..., then assert a second full scan yields ***.
  • [secret-exposure] internal/security/jsonsanitize.go:161 — The cross-member private-key check runs after leaf redaction, which can destroy the BEGIN marker (e.g. a sensitive-named member holding it), leaving the key body intact; JSONL records and Unicode-escaped markers are likewise uncovered. The PR body defers spanning keys to stacked PR 2, and reachability is limited while the sanitizer is unwired.
    Remediation: Detect cross-leaf/cross-record key spans against the original decoded content before masking any leaf, replace the affected document/records when a span cannot be localized, and add regressions.
  • [architectural-conflict] docs/contributing/runtime-implementation.md:637 — This doc and docs/guides/user/run-artifacts-and-private-data.md describe scanOutputFiles structural sanitizing, fail-closed markers and ::error:: annotations that the runtime does not implement at this commit; the BREAKING CHANGE declaration has the same problem.
    Remediation: Land the doc updates and breaking-change marker with the PR that changes scanOutputFiles, or include that integration here.

Low

  • [api-shape] internal/security/redactor.go:76 — ResetRuntimeSecretsForTest is exported but has no callers in the repository.
    Remediation: Omit it until a caller exists; if kept, take testing.TB and register t.Cleanup.
  • [pattern-inconsistency] internal/security/jsonsanitize.go:24 — FailClosedUnwritableJSON is exported while its sibling constants are unexported and nothing outside the package uses any of them.
    Remediation: Unexport it or document why it is exported.
  • [doc-style] internal/security/jsonsanitize_test.go:57 — Many test doc comments do not start with, and describe different scenarios from, the function below them (e.g. lines 57, 121, 141, 161, 552, 581, 723).
    Remediation: Make each comment start with the real function name and describe what it asserts.
  • [design-smell] internal/security/testdata/review-result.schema.pin:5 — The pin cites scripts/check-review-schema-pin.sh, which does not exist in the repository or this PR.
    Remediation: Add the script and wire it into lint/CI, or describe the sync as manual.
  • [breaking-schema] internal/security/jsonsanitize.go:24 — The {"error":"output removed because ..."} marker has no status/findings fields, and no consumer (e.g. post-review.sh reading agent-result.json) handles it; latent until the sanitizer is wired in.
    Remediation: Make readers detect the marker and fail clearly, and document its shape, before wiring the sanitizer in.
  • [backward-incompatible] internal/security/redactor.go:316 — mask is now exported Mask and returns *** instead of xxxx... when the 4-byte prefix contains a backslash, single quote or double quote; the package is internal so no external break.
    Remediation: Keep it internal unless needed and note the placeholder change in release notes.
  • [backward-incompatible] internal/security/redactor.go:428 — The json_field pattern now matches different inputs and masks different bytes (escaped quotes, rune-counted minimum length).
    Remediation: Note the change in release notes and pin it with regression tests.

Labels: The PR changes the output secret-redaction layer.


Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR

fullsend-ai-review[bot]

This comment was marked as outdated.

@fullsend-ai-review fullsend-ai-review Bot added the security Security threat model and related concerns label Dec 3, 2026
@codecov

codecov Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.77108% with 30 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
internal/security/jsonsanitize.go 92.96% 14 Missing and 10 partials ⚠️
internal/security/redactor.go 89.47% 3 Missing and 3 partials ⚠️

📢 Thoughts on this report? Let us know!

Comment thread internal/security/jsonsanitize.go Resolved
@andrewevansrh
andrewevansrh force-pushed the agent/5705-json-sanitizer branch 2 times, most recently from 429a03d to 7153974 Compare December 3, 2026 16:24
@qodo-code-review

Copy link
Copy Markdown

Fixed in 7153974. You are right that the escape-reading double-quoted branch ran first and read the closing " of the first value as an escape, so the capture continued through , and the next field's credential was never matched.

The double-quoted value alternation now has the same bounded branch the single-quoted one already had, ordered before the escape-reading branch: ([^\r\n]*\)[ t]*(?:,|}|]|$) keeps the backslash out of the captured value and only matches when the quote after it is followed by a field or line boundary. Go's leftmost-first alternation then leaves the separator and the second field intact. Regression test: json_field keeps the field after a double-quoted trailing backslash in internal/security/scanner_test.go, over both the bare and the object-wrapped form of your example: both values are masked and , password survives.

Note: Generated with assistance from DeepSeek V4.1 Flash --comment_id=4787827038

Thanks for the update. I checked the fix against the current code, and it matches what you described.

  • Regex order: In internal/security/redactor.go:421, the bounded double-quoted branch "([^"\r\n]*\\)"[ \t]*(?:,|\}|\]|$) now comes before the escape-reading branch "((?:\\[\s\S]|[^"\\\r\n])*)". Go's leftmost-first alternation therefore takes the bounded branch for "abcdefghi\", "password": ..., so the comma and the second field's opening quote are not swallowed.
  • Regression test: internal/security/scanner_test.go:635 (json_field keeps the field after a double-quoted trailing backslash) covers both the bare and the object-wrapped form of the example. It asserts that ", "password" survives and that neither secret appears in the output. I read the test but did not run it.

This corresponds to finding 2 ("A later password escapes redaction"), which is already marked resolved (implemented) in the published review. Finding 1 (JSON output is still redacted as raw text) is still open. Nothing in this change addresses it: scanOutputFiles in internal/cli/run.go still passes output files through the raw-text pipeline.Scan.

@fullsend-ai-review

fullsend-ai-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ⚠️ Cancelled · Started 4:30 PM UTC · Completed 4:41 PM UTC

Commit: 7153974 · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $1.17

This review was superseded by a newer commit. Check the current pull request HEAD's review status before merging.

…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.

Three changes address that:

- 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. A double-quoted json_field value
  that ends in a literal backslash is matched by a bounded branch that
  keeps the closing quote out of the capture, so an adjacent field's
  delimiter and credential are no longer swallowed.
- The json_field pattern spans escaped and multiline quoted values
  without running on to a later field's quote.
- SanitizeJSONDocument and SanitizeJSONLines add a structural path:
  JSON output is rewritten by 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. An array under a sensitive member keeps that
  member's name for its elements, so a token list is masked even when an
  element matches no pattern of its own; a nested object does not, since
  its members carry their own names. Content that cannot be redacted in place is
  replaced with a valid fail-closed JSON marker rather than corrupted
  JSON, and a cross-record match replaces only the records it covers.

The structural path is a library primitive at this commit: the CLI output
scan still calls the text pipeline, and wiring it in, with the operator
alert for a replaced file, lands in the stacked PR that changes
scanOutputFiles (fullsend-ai#10085).

BREAKING CHANGE: a value masked as json_field now yields "***" instead of
its first four bytes plus "..." whenever that prefix would carry a
backslash or a quote delimiter, and json_field matches escaped-quote and
multiline quoted values that it previously did not, so sanitized output
text and finding details differ for those inputs.

Signed-off-by: anevans <anevans@redhat.com>
@fullsend-ai-review

fullsend-ai-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 4:44 PM UTC · Completed 5:00 PM UTC

Commit: f6dc2ce · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $3.24

@fullsend-ai-review

Copy link
Copy Markdown

Review

Findings

High

  • [logic-error] internal/security/jsonsanitize.go:155 — The serialized backstop uses the rebuilt document only when a leaf produced findings. A private-key block split across leaves with a JSON-escaped marker (e.g. \u002d----BEGIN RSA PRIVATE KEY-----) has no complete block in any leaf. The backstop then scans the original escaped bytes, does not match, and returns the key material unchanged with no findings. JSONL records share the blind spot. The sanitizer is library-only at this commit.
    Remediation: run the cross-leaf whole-value scan on the decoded/rebuilt form even when no leaf matched, and add document and JSONL tests with escaped markers split across leaves or records.

Medium

  • [secret-exposure] internal/security/jsonsanitize.go:154 — Same escaped-marker path as above, seen as data exposure: with no leaf match, the original bytes are scanned and the key block is returned unchanged.
    Remediation: scan the rebuilt form for cross-leaf private-key blocks even when no leaf matched, and fail closed on a match.
  • [secret-exposure] internal/security/jsonsanitize.go:161 — The whole-document private-key backstop scans only the rebuilt document, after sensitive-key masking can erase the markers. With the BEGIN marker under secret_begin, the body under payload and the END marker under secret_end, the key material is returned unchanged. JSONL records share the gap.
    Remediation: track private-key spans before per-leaf or per-record redaction destroys their delimiters, then redact all covered material or replace the document/records with a fixed marker. Add tests with sensitive marker-member names.
  • [logic-error] internal/security/redactor.go:421 — The bounded double-quoted json_field branch is listed before the escape-aware branch, so in valid JSON an escaped quote followed by ,, } or ] is taken as the end of the value. {"password":"abcd...", tail-secret"} becomes {"password":"abcd...", tail-secret"}: invalid JSON, with the rest of the value exposed. The suffix leak predates this PR; the broken JSON syntax is new. Affects existing Pipeline.Scan callers.
    Remediation: do not let the literal-trailing-backslash branch win over a valid escape-aware value when the input is valid JSON, and add regressions for an escaped quote followed by ,, } and ].
  • [secret-exposure] internal/security/redactor.go:421 — Same pattern ordering, seen as exposure: {"password":"***",remaining_secret_value"} masks only the abcdefgh\ prefix and leaves remaining_secret_value in the output.
    Remediation: distinguish valid JSON escaped delimiters from literal trailing backslashes before choosing the bounded fallback, and assert the whole decoded value is removed.

Low

  • [design-smell] internal/security/testdata/review-result.schema.pin:5 — The vendored schema is tracked only by a manual pin file, so it can drift silently from upstream.
    Remediation: add an automated drift check against the pinned revision.
  • [api-shape] internal/security/redactor.go:104 — ScanWholeValueSecrets is exported outside the Scanner interface and reached through an unexported wholeValueScanner interface, so scanner API shapes are uneven.
    Remediation: consider an exported capability interface or an option on Scan.
  • [pattern-inconsistency] internal/security/jsonsanitize.go:23 — failClosedCrossRecordJSON says "output contained a cross-record secret" while outputRemovalMarkers maps it to "a secret spanned multiple records"; the other markers use the same clause as their reason.
    Remediation: align the message with its mapped reason.
  • [backward-incompatible] internal/security/redactor.go:316 — mask now returns *** instead of the first four bytes plus ... when the prefix carries a backslash or quote. Declared as breaking in the title and commit footer; informational.
  • [backward-incompatible] internal/security/redactor.go:421 — json_field now matches escaped-quote and multiline quoted values it did not before. Declared as breaking in the title and commit footer; informational.

Earlier findings

  • internal/security/scanner_test.go:284, test-inadequate — resolved; the placeholder-rescan test now asserts that a full second scan re-masks the placeholder and that a whole-value rescan leaves it intact.
  • docs/contributing/runtime-implementation.md:637, architectural-conflict — resolved; that file is no longer part of the PR, and the docs moved to the stacked PR that wires in the structural scan.
  • internal/security/jsonsanitize_test.go:57, doc-style — reclassified to info; "pins that" matches the prevailing test-comment style in the file and repo.
  • internal/security/jsonsanitize.go:24, breaking-schema — reclassified to info; no production code calls the sanitizer or emits its markers at this commit.

Labels: PR changes Go code in internal/security.


Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR

2 finding(s) below the low severity threshold were not posted.

fullsend-ai-review[bot]

This comment was marked as outdated.

@fullsend-ai-review fullsend-ai-review Bot added the go Pull requests that update go code label Dec 3, 2026
@fullsend-ai-review

fullsend-ai-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ⚠️ Cancelled · Started 6:57 PM UTC · Completed 7:08 PM UTC

Commit: abfa104 · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $2.01

This review was superseded by a newer commit. Check the current pull request HEAD's review status before merging.

…y markers

Address the review findings on fullsend-ai#10082:

- json_field accepts an optional CR before the line end in the bounded
  branches, so a double-quoted value ending in a literal backslash is masked
  on a CRLF line instead of going out in clear text.
- A last-resort double-quoted branch masks a trailing-backslash value that is
  followed by neither a field nor a line end, such as
  `"password": "Abc123xyzQ\" (rotated)`, which matched no branch at all.
- scan re-reads a double-quoted value whose closing \" is ambiguous: when the
  escape reading closes the string at a JSON value boundary it covers the
  whole value and wins, so `{"password":"ab\",cdefgh"}` is masked whole and
  stays valid JSON instead of losing the part after the escaped quote. Raw
  text such as `"api_key": "abcdefghi\", "password": ...` still takes the
  bounded reading, so the separator and the second field survive.
- SanitizeJSONDocument scans the rebuilt document for whole-value secrets
  instead of the bytes it received, and does so even when no leaf produced a
  finding. A private-key block whose markers are JSON-escaped and split
  across leaves is now detected and the document fails closed, instead of the
  key material being returned unchanged.
- failClosedCrossRecordJSON states the reason outputRemovalMarkers maps it to.
- The whole-value rescan is unexported again: nothing outside the package
  called it, and the pipeline reaches it through wholeValueScanner.

BREAKING CHANGE: sanitized output differs for two inputs. A double-quoted
value that ends in a literal backslash is now masked on a CRLF line or before
trailing text, and a valid JSON value whose escaped quote is followed by a
separator is masked whole rather than up to the escaped quote.

Note: Generated with assistance from DeepSeek V4.1 Flash
Signed-off-by: Andrew Evans <andrewevansrh@users.noreply.github.com>
@fullsend-ai-review

fullsend-ai-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 7:10 PM UTC · Completed 7:28 PM UTC

Commit: dd29b2c · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $2.94

@fullsend-ai-review

Copy link
Copy Markdown

Risk Assessment: moderate (2/5)

Details

Moderate risk score of 2 preserved for this split PR: large diff driven predominantly by test suites and schemas with elevated regression churn in modified security files, balanced by zero protected path or dependency changes, an established contributor, and close alignment with linked issue #5705.

@fullsend-ai-review

Copy link
Copy Markdown

Review

Findings

Medium

  • [logic-error] internal/security/jsonsanitize.go:165 — SanitizeJSONDocument scans only the compact rebuilt document (redactJSONOutput(rebuilt, p)), but the no-findings branch returns the original bytes. A registered runtime secret that spans JSON framing plus whitespace (for example "alpha": 1,) is in the returned bytes, yet matches neither a decoded leaf nor the rebuilt form, so it is written out unredacted. The old text scan matched registered values against the raw bytes. The trigger needs a registered secret that itself contains JSON structural characters, so I rate it medium.
    Remediation: also run scanWholeValueSecrets on the original serialized body. If a match appears only in the original and cannot be mapped into the rebuilt document, return failClosedInvalidJSON. Add a regression with a registered value spanning whitespace in the original framing.
  • [secret-exposure] internal/security/jsonsanitize.go:165 — Same root cause, seen as a data-exposure risk: registered values containing original JSON framing (for example foo", "b":"bar against {"a":"foo", "b":"bar"}) escape the backstop, and the original secret-bearing bytes are returned.
    Remediation: scan both the original serialized document and the rebuilt form. Fail closed when an original-only match cannot be localized.
  • [secret-exposure] internal/security/jsonsanitize.go:302 — In SanitizeJSONLines, a record with no findings is written back as its original line, and the cross-record backstop at line 302 scans those raw bytes. A private-key block whose -----BEGIN dash is written as \u002d in one record and whose END marker is in a later record is therefore not recognized, because the pattern needs a literal -----BEGIN. The single-document path already scans the decoded form.
    Remediation: build the cross-record scan input from the decoded or canonical form of every record, even records with no findings. Keep the mapping back to the original records, and fail closed for each record the block touches. Add a JSONL regression with an escaped BEGIN marker and an END marker in another record.

Low

  • [design-smell] internal/security/testdata/review-result.schema.pin:5 — The vendored schema pin is refreshed manually and nothing checks it for drift against the upstream schema.
    Remediation: add an automated check, or a sync script run in CI, that validates review-result.schema.json against the pinned upstream revision.
  • [backward-incompatible] internal/security/redactor.go:316 — Redacted output is no longer byte-identical to earlier releases: the escape handling and the *** fallback mask changed. This is intended and the ! in the title and the BREAKING CHANGE footer cover it. Keep the note in the release notes.

Earlier findings

  • internal/security/jsonsanitize.go:139/155, logic-error and secret-exposure — resolved. The whole-value backstop now scans the rebuilt document unconditionally (line 165), so escaped PEM markers split across leaves are detected. New document and JSONL tests cover it.
  • internal/security/jsonsanitize.go:154/161, secret-exposure — resolved. The same change fixes both; line 165 scans the rebuilt bytes even when no leaf produced a finding.
  • internal/security/redactor.go:421, logic-error and secret-exposure — resolved. json_field now accepts CRLF boundaries and has a trailing-backslash fallback, and scan calls resolveJSONFieldDoubleQuote. New tests cover the CRLF, trailing-text and escaped-quote cases.
  • internal/security/redactor.go:76/104, api-shape — resolved. ScanWholeValueSecrets is now the unexported scanWholeValueSecrets.
  • internal/security/jsonsanitize.go:23/24, pattern-inconsistency — resolved. The cross-record marker text now follows the output removed because <reason> template.
  • internal/security/jsonsanitize_test.go:57, doc-style — reclassified to info. The TestX pins ... comment form is the repository's established test-comment style.
  • internal/security/jsonsanitize.go:24, breaking-schema — reclassified to info. It duplicates the informational marker-contract note, and the marker strings are new in this PR.

Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR

2 finding(s) below the low severity threshold were not posted.

fullsend-ai-review[bot]

This comment was marked as outdated.

…anning secrets

SanitizeJSONDocument scanned only the rebuilt document, but a document with no
findings is written back as the bytes that came in. The rebuilt form compacts
whitespace, so a registered runtime value that spans JSON framing plus
whitespace exists only in the original and was returned unredacted — the old
text scan matched it.

The backstop now scans the original bytes as well, but only when the rebuilt
scan is clean, so nothing is reported twice: the rebuilt form still catches
escaped markers and values the decoder can see, and the original form catches
what only its whitespace and escaping spell.

Regression test:
TestSanitizeJSONDocument_FramingSecretAcrossWhitespaceFailsClosed, a registered
value `foo", "b":"bar` inside `{"a":"foo", "b":"bar"}`.

Note: Generated with assistance from DeepSeek V4.1 Flash
Signed-off-by: Andrew Evans <andrewevansrh@users.noreply.github.com>
@fullsend-ai-review

fullsend-ai-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 7:47 PM UTC · Completed 8:00 PM UTC

Commit: 4911942 · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $2.77

@fullsend-ai-review

Copy link
Copy Markdown

Risk Assessment: moderate (2/5)

Details

Moderate risk score of 2 preserved for this split PR: large diff driven predominantly by test suites and schemas with elevated regression churn in modified security files, balanced by zero protected path or dependency changes, an established contributor, and close alignment with linked issue #5705.

@fullsend-ai-review

Copy link
Copy Markdown

Review

Findings

Medium

  • [logic-error] internal/security/jsonsanitize.go:311 — The JSONL cross-record backstop scans the original encoded bytes of clean records, so a JSON-escaped PEM marker (for example \u002d----BEGIN RSA PRIVATE KEY-----) split across records bypasses it and the key material is returned unchanged. This PR already handles the escaped marker within one document and claims cross-record fail-closed behaviour, but the escaped case is not covered across records.
    Remediation: Scan a decoded/rebuilt view of each record for cross-record whole-value secrets, keeping a mapping to the original record spans, or explicitly defer this case to fix(#5705): mask private-key blocks that span JSON members or records #10084 and say so in the code comment. Add a regression with an escaped BEGIN marker, body and END marker in separate records.
  • [secret-exposure] internal/security/jsonsanitize.go:311 — The JSONL whole-stream backstop scans encoded bytes, so JSON-escaped PEM markers split across records evade redaction. The existing cross-record test uses only literal markers.
    Remediation: Scan a decoded/normalized cross-record view while retaining mappings to the original record ranges, and replace all records a detected block covers. Add a regression with a JSON-escaped BEGIN marker in one record, body material in another, and the END marker in a third.

Low

  • [design-smell] internal/security/testdata/review-result.schema.pin:5 — The vendored review-result schema is tied to upstream only by a manual pin file, so the fixture can drift from the upstream contract without any automated signal.
    Remediation: Add an automated drift check or CI gate (similar to scripts/check-agents-gate-pin.sh or hack/lint-mint-embed-sync) that compares the vendored fixture with the pinned upstream revision.

Earlier findings

  • internal/security/jsonsanitize.go:165, logic-error — resolved: the backstop now also scans the original bytes a clean document writes back (jsonsanitize.go lines 166-174, with a new regression test).
  • internal/security/jsonsanitize.go:165, secret-exposure — resolved: a registered runtime value spanning framing plus whitespace is now detected by the same added scan.

Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR

fullsend-ai-review[bot]

This comment was marked as outdated.

@waynesun09 waynesun09 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two findings from a review pass at 4911942. Both were reproduced with go test at that head. Neither one leaks a secret on its own, but each undoes a guarantee that an earlier thread on this PR says is fixed.

Comment thread internal/security/redactor.go Resolved
Comment thread internal/security/jsonsanitize.go Resolved
…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>
@fullsend-ai-review

fullsend-ai-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ⚠️ Cancelled · Started 8:25 PM UTC · Completed 8:33 PM UTC

Commit: b5f395b · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $1.15

This review was superseded by a newer commit. Check the current pull request HEAD's review status before merging.

@fullsend-ai-review

fullsend-ai-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 8:36 PM UTC · Completed 8:51 PM UTC

Commit: 364b1ff · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $3.18

@fullsend-ai-review

Copy link
Copy Markdown

Risk Assessment: moderate (2/5)

Details

Moderate risk score of 2 preserved for this split PR: large diff driven predominantly by test suites and schemas with elevated regression churn in modified security files, balanced by zero protected path or dependency changes, an established contributor, and close alignment with linked issue #5705.

@fullsend-ai-review

Copy link
Copy Markdown

Review

Findings

Medium

  • [logic-error] internal/security/jsonsanitize.go:413 — affectedRecords picks the longest surviving run across the whole stream and marks every record before it as affected, so clean records between two disjoint cross-record matches are replaced with a removal marker (the later-record tie-break added in this push causes the same loss with a single trailing clean record). Fail-safe (content removed, not leaked) but it breaks the guarantee the doc comment and existing test claim.
    Remediation: Keep surviving anchors that precede the chosen run (align the prefixes recursively or localize replacements with exact match spans) and add regressions with clean records both between and after disjoint matches.
  • [logic-error] internal/security/jsonsanitize.go:319 — A JSON-escaped PEM BEGIN marker (\u002d----BEGIN) in one JSONL record and the END marker in another are never joined by the stream backstop; the records come back unchanged. The new comment acknowledges the gap and defers it to fix(#5705): mask private-key blocks that span JSON members or records #10084, but it remains in this PR.
    Remediation: Build the cross-record scan input from the decoded form of every record, keep the mapping to the originals, and fail closed for each record a block touches; add a regression.
  • [secret-exposure] internal/security/jsonsanitize.go:319 — The same escaped-marker gap, seen as exposure: the stream backstop scans encoded bytes and the private_key pattern needs a literal -----BEGIN, so key material split across records is returned in clear. The primitives have no non-test caller yet, which limits immediate exposure.
    Remediation: Scan a decoded view of the entire stream before per-record rewriting and replace every record that intersects a detected block.
  • [secret-exposure] internal/security/redactor.go:493 — The rewritten json_field expression no longer redacts a double-quoted multiline credential when prose follows the closing quote (e.g. "password": "firs..." (rotated)). The base pattern matched this input, so it is a regression for every existing Pipeline.Scan caller.
    Remediation: Handle multiline double-quoted values followed by prose without consuming adjacent fields, and add a regression asserting both credential lines are removed while the trailing annotation survives.

Low

  • [design-smell] internal/security/testdata/review-result.schema.pin:5 — The vendored review-result schema is re-vendored by hand only; nothing checks it for drift against the upstream contract.
    Remediation: Add an automated check (CI or a test) that verifies the fixture against the pinned upstream commit, or reports drift.
  • [backward-incompatible] internal/security/redactor.go:380 — mask() now returns *** instead of the first four bytes plus ... when the kept prefix carries a backslash or quote delimiter. Declared with ! and the BREAKING CHANGE footer; keep it in the release notes.
  • [backward-incompatible] internal/security/redactor.go:493 — json_field was rewritten (7 capture groups, length gate moved into scan) and matches escaped-quote and multiline values it previously did not. Declared as breaking; nothing outside scan depends on the old group layout.

Earlier findings

  • internal/security/testdata/review-result.schema.pin:5, design-smell — resolved: the pin comment no longer references a nonexistent comparison script and describes the manual re-vendoring step.
  • internal/security/jsonsanitize_test.go:57, doc-style — resolved: every Test function's doc comment now begins with its own function name.
  • internal/security/jsonsanitize.go:24, breaking-schema — reclassified to info: the markers are valid JSON, their reasons are documented, detection helpers exist and the sanitizer has no non-test caller in this PR.

Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR

1 finding(s) below the low severity threshold were not posted.

@fullsend-ai-review fullsend-ai-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See the review comment for full details.

}
return affected
}
for ; i < k; i++ {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] logic-error

affectedRecords picks the longest surviving run across the whole stream and marks every record before it as affected, so clean records sitting between two disjoint cross-record matches are replaced with a removal marker. Traced against TestSanitizeJSONLines_DisjointCrossRecordMatchesKeepCleanRecord with two clean trailing records: the clean middle record is a run of 1, the trailing pair a run of 2, the loop at line 413 marks the middle record affected. The new later-record tie-break causes the same loss with a single trailing clean record. The failure is fail-safe (content removed, not leaked) but breaks the guarantee the doc comment and existing test claim.

Suggested fix: Keep surviving anchors that precede the chosen run instead of treating the whole skipped prefix as changed (e.g. align the prefixes recursively, or localize replacements with exact match spans). Add regressions with clean records both between and after disjoint cross-record matches.

// 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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] logic-error

SanitizeJSONLines scans the encoded rebuilt stream for cross-record private keys, so a JSON-escaped PEM BEGIN marker (\u002d----BEGIN) in one record and the END marker in another are never joined and come back unchanged with no findings. The new comment at lines 311-318 acknowledges the gap and defers it to #10084, but the defect remains in this PR.

Suggested fix: Build the cross-record scan input from the decoded form of every record, keep the mapping to the original records, and fail closed for each record a detected block touches. Add a JSONL regression with an escaped BEGIN marker and an END marker in separate records.

// 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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] secret-exposure

JSON-escaped PEM markers split across records still bypass redaction: each record is clean on its own, and the stream backstop scans encoded bytes whose private_key pattern needs a literal -----BEGIN, so the key material is returned in clear. Literal cross-record markers are covered; escaped ones are not. The comment at lines 311-318 defers this to #10084. The primitives have no non-test caller yet, which limits immediate exposure.

Suggested fix: Scan a decoded view of the entire stream before per-record rewriting and replace every record that intersects a detected private-key block. Add a regression with an escaped BEGIN marker and its END marker in separate records.

// 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]*\\)")`},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] secret-exposure

The rewritten json_field expression no longer redacts a double-quoted multiline credential when prose follows its closing quote, e.g. "password": "firs..." (rotated). The ordinary double-quoted branch excludes raw newlines, the multiline branch requires a comma, bracket, brace or line end after the closing quote, and the last-resort branch requires a trailing backslash. The base pattern "([^"]{8,})" matched this input, so this is a regression for every existing Pipeline.Scan caller.

Suggested fix: Handle multiline double-quoted values followed by prose without consuming adjacent fields, and add a regression asserting that both lines of the credential are removed while the trailing annotation survives.

#
# 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] design-smell

The vendored review-result schema fixture is re-vendored by hand only; the pin file itself says nothing checks it automatically, so test constraints can silently diverge from the upstream contract in fullsend-ai/agents.

Suggested fix: Add an automated check (CI or a test) that verifies the vendored review-result.schema.json against the pinned upstream commit, or reports drift.

// 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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] backward-incompatible

Redacted output is no longer byte-identical to earlier releases (escape handling and the *** fallback mask changed). Declared by the ! marker and BREAKING CHANGE footer; keep the note in release notes.

Suggested fix: No code change; keep the breaking-change note in the PR and release notes.

// 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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] backward-incompatible

mask() returns *** instead of the first four bytes plus ... when the kept prefix carries a backslash or quote delimiter, so placeholder text differs for those inputs. The package is internal; only artifact placeholder text changes, and the change is declared with !.

Suggested fix: No code change needed beyond the declared breaking-change marker.

// 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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] backward-incompatible

The fallback *** mask changes sanitized output text and finding details for values whose four-byte prefix carries an escape or quote delimiter. Declared as a breaking change.

Suggested fix: No code change needed; name the placeholder change in the release note.

// 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]*\\)")`},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] backward-incompatible

json_field now matches escaped-quote and multiline quoted values it previously did not, changing sanitized output for those inputs. Declared as a breaking change in the title and commit footer.

Suggested fix: No code change needed beyond the declared breaking-change marker.

// 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]*\\)")`},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] backward-incompatible

The json_field pattern was rewritten (7 capture groups instead of 2; the 8-rune minimum moved from the quantifier into scan). Only scan reads the groups, so nothing in the module breaks, but callers depending on finding counts or exact sanitized text from Pipeline.Scan can see different output.

Suggested fix: Call out the changed matching behavior in the release notes; nothing outside scan depends on the old group layout.

@waynesun09 waynesun09 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two MEDIUM findings from a review-only pass, posted inline.

// 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) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] These per-member masking tests pass only because the whole document is replaced with the fail-closed marker

The comment on TestSanitizeJSONDocument_ShortBodyChunksMasked says a private key split across array members is "neutralized member by member instead of dropping the whole document". TestSanitizeJSONDocument_ChunkedBodyBetweenMarkersMasked and TestSanitizeJSONDocument_BodyLineAsKeyBetweenMarkersMasked make similar per-member claims.

At head, SanitizeJSONDocument returns {"error":"output removed because redaction would invalidate JSON"} for all three inputs. The json.Valid, NotContains and NotEmpty(findings) assertions all pass against that marker. So these tests cannot catch a regression in the per-member masking they describe. Per your earlier replies, the joined-run logic arrives in #10084.

Suggestion: Make the tests prove what their names say: assert that the output is not a fail-closed marker (for example, no output removed because and no OutputRemoval). Otherwise, move the per-member cases to #10084 with the joined-run code, and change the comments here to say the document fails closed at this commit.

Verified: reproduced with a go test probe calling SanitizeJSONDocument with the three test inputs; all three return the fail-closed marker at 364b1ff; raised by: DeepSeek

}

// mask returns a redacted representation of a secret value.
//

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] mask() can split a UTF-8 rune and write invalid UTF-8, even though the new doc comment says the result is safe to splice

mask keeps value[:4], which is the first four bytes, not runes. For a non-ASCII value the cut can land inside a multi-byte character. At head, Scan on "password": "日本語のパスワードです" produces "password": "日\xe6...", and utf8.ValidString on the result is false.

The new doc comment says the returned text is safe to splice into a JSON or YAML string. jq rejects invalid UTF-8, which is the kind of failure #5705 is about. The PR now counts the json_field minimum in runes but still slices the mask prefix in bytes, and text-path Pipeline.Scan callers write the result back without re-encoding it.

Suggestion: Trim the prefix back to a rune boundary (for example, take the first 4 runes, or step back with utf8.RuneStart), or return *** when value[:4] is not valid UTF-8. Add a utf8.ValidString assertion to the "json_field minimum counts runes, not bytes" subtest in scanner_test.go.

Verified: reproduced with a go test probe; NewSecretRedactor().Scan on a Japanese password gives invalid UTF-8 日\xe6... at 364b1ff; raised by: DeepSeek

@jflowers jflowers left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Council verdict: REQUEST CHANGES (7 runs: 2 REQUEST CHANGES, 2 APPROVE WITH ADVISORIES, 3 APPROVE). This review is pinned to commit 4911942. b5f395b ("anchor the JSON boundary check and keep clean tied records") landed while the council ran and appears to target both blocking findings; a fresh review of that commit is the natural next step.

from what I can tell, the structural approach is right: escape-aware bounded matching in the redactor, token-preserving re-encoding in the sanitizer, fail-closed markers, and honest BREAKING CHANGE labeling. The happy paths carry strong coverage.

two findings block at 4911942:

  • HIGH jsonsanitize.go:436: the nextAnchor tie-break keeps the earliest run, so a covered duplicate record is written back verbatim while the clean copy is replaced; part of the runtime secret survives, contradicting the failClosedRecordSpans doc comment (adversary + fullsend; escalates waynesun09's open MEDIUM).
  • HIGH jsonsanitize_test.go: no contract test fails on the current implementation for either defective branch; both functions sit at CRAP over 30 with low contract coverage, and add_tests is the cheapest risk reduction (gaze-testing).

four MEDIUM and four LOW findings round out the review (line anchors folded into this body because the PR head moved mid-review; inline positions no longer resolve):

  • MEDIUM redactor.go:299: jsonValueBoundaryRe compiles with (?m), so ^ matches after every newline and the escape-reading check scans the whole remaining suffix; in multiline raw text json_field swallows the separator and the next field (adversary + fullsend, waynesun09's other open MEDIUM).
  • MEDIUM jsonsanitize_test.go:8 and scanner_test.go:1: testify imports and test naming versus the loaded Go pack (gaze-testing). The repo already depends on testify across 688 test files, so this reads as a pack versus repo question.
  • MEDIUM jsonsanitize_test.go:1606: the closing comment pins the error-wrap contract to TestScanOutputFiles_SanitizerErrorContainsFileAndContinues, which exists only in stacked draft #10085 (testing).
  • LOW jsonsanitize.go:652: no assertion pins HTML-character preservation through a rewrite (the #9555 cases were not carried over).
  • LOW jsonsanitize.go:467: dec.UseNumber() passthrough is unpinned; every numeric fixture formats identically as float64.
  • LOW jsonsanitize.go:424: the anchorSearchBudget exhaustion branch has no test.
  • LOW jsonsanitize_test.go:267: the JSONL split/require.Len idiom repeats roughly 16 times; a splitJSONLRecords helper would centralize the framing convention.

CI: all non-skipped checks pass at 4911942. Local gates did not run (UNTRUSTED_HEAD: fork PR whose author has read permission); this review proceeds on CI evidence.

This review was generated by /uf.review-pr (AI-assisted).

This branch was successfully deployed

1 active deployment
site-preview — 364b1ffd Deployed Dec 3, 2026 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code risk/moderate PR risk: moderate security Security threat model and related concerns

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants