Skip to content

fix(#5705)!: preserve escaping backslashes in JSON strings during redaction - #9699

Closed
andrewevansrh wants to merge 78 commits into
fullsend-ai:mainfrom
andrewevansrh:agent/5705-output-sanitizer-json-integrity
Closed

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

Conversation

@andrewevansrh

@andrewevansrh andrewevansrh commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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:

  1. Structural JSON Sanitization (internal/security/jsonsanitize.go): Primary defense-in-depth fix for JSON files (such as agent-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.
  2. Escape-Preserving Redaction (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:

{"remediation": "Guard against null values with token_usage = metr...\"token_usage\") or {}"}

swallowing the backslash and leaving an unescaped quote delimiter inside the JSON string. This corrupted the JSON structure and caused downstream tools (jq in post-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)

  • JSON Detection & Validation: scanOutputFiles treats a file as a single JSON document only when security.IsJSONDocument accepts it; .jsonl/.ndjson files are handled per record so a stream is never mistaken for one document.
  • BOM-Tolerant Detection: IsJSONDocument ignores a leading UTF-8 BOM, which json.Valid and bytes.TrimSpace both reject, so a BOM-prefixed document no longer falls through to the text scan where a redaction can still break its syntax. SanitizeJSONDocument strips the BOM, scans the document, and restores the mark on write, and returns a clean document byte for byte.
  • Exact Number Preservation: Uses dec.UseNumber() to keep numbers as json.Number, avoiding float64 precision loss for integers above 2^53 (e.g. 12345678901234567891) and preserving float formatting like 1.0.
  • Order-Preserving Token Walk: rewriteJSONTokens visits 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).
  • Key & Leaf Sanitization: Object keys are scanned via pipeline.Scan(k). A key that sanitizes to nothing (bidi overrides, null bytes) is replaced with redacted, 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 into json_field masking.
  • Member-Level Private-Key Containment: A private-key block whose BEGIN and END markers sit in different members is located in the decoded view and neutralized member by member. The members the match starts and ends in carry marker text (a marker split across members leaves only fragments) and are always masked. A string value between them is masked when it carries a marker or a run that looks like PEM body material — at least 16 characters of the base64 alphabet mixing upper case, lower case and digits with a character outside the hex range — because the length floor alone does not reject a long word (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 a head_sha or a finding id. 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 as severity and file. 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_sha and each finding's severity, category, file, id and description keep values review-result.schema.json accepts, 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.
  • Written Bytes Are Scanned: The bytes actually written are scanned, so a secret that exists only across JSON framing (a private-key block split across members, for example) is caught. Files with zero findings remain byte-for-byte untouched, and a rewritten file keeps the source's trailing-newline framing.
  • JSONL Cross-Record Containment: failClosedCrossRecordPrivateKeys builds 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 \u escapes 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.
  • JSONL Stream Rescan: After the per-record pass, SanitizeJSONLines rescans 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 \n escape is two non-space bytes, so env_assignment ran 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 by SanitizeJSONDocument, and a block spanning records by failClosedCrossRecordPrivateKeys.
  • Fail Closed With Distinct Reasons: failClosedInvalidJSON, failClosedCrossRecordJSON, and failClosedSpansMembersJSON each state why the document was dropped, and security.OutputRemoval recognizes them. scanOutputFiles fails 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 its agentFailedError and the post-script still receives FULLSEND_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. scanOutputFiles writes a ::error:: workflow command for a replaced file whenever GITHUB_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)

  • Character-Based Quantifiers: Retains character-based minimum quantifiers for env_assignment ([^\s"'}\]),;]{8,}), auth_header (12), and db_connection_password (4), ensuring credentials with multiple backslashes meet required length thresholds.
  • Delimiter Escape Protection: When a matched secret ends with a backslash followed immediately by a quote delimiter (" 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_field is exempt because its value pattern already consumes escaped delimiters.
  • json_field Minimum: The json_field value 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 in Scan that counts runes (utf8.RuneCountInString, 8) on the span after the escape trim and before Mask is computed, matching the character semantics of the {8,} quantifier it replaced. sanitizeJSONString applies the same rune-counted minimum when a sensitive key masks its value. env_assignment, auth_header, and db_connection_password no longer appear in that gate because their patterns already enforce their own minimum.
  • Mask() Safety: Exported as security.Mask and 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:
    • Secrets in string values are redacted while preserving JSON syntax.
    • Secrets located in object keys are redacted.
    • Large integer precision (> 2^53) and float formatting are preserved.
    • HTML characters (<, >, &) are not escaped.
    • Key collisions after redaction are handled safely.
    • Private-key markers in separate values are masked member by member, not by dropping the document.
    • TestScanOutputFiles_EmitsAnnotationWhenOutputIsRemoved pins the ::error:: line for a replaced file, its absence outside Actions, and that a Forgejo run (GITHUB_ACTIONS=true plus FORGEJO_ACTIONS=true) writes the same line; TestScanOutputFiles_SanitizesBOMPrefixedJSONStructurally pins the BOM path. TestScanOutputFiles_UnreadableFileFailsClosed and TestScanOutputFiles_UnreadableDirectoryFailsClosed pin that a read failure contains the file and fails the run, and TestScanOutputFiles_QuietReadFailureKeepsPathOutOfMessage pins 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 (with action, pr_number, repo, head_sha, and findings carrying severity, category, file, id and description) whose header/footer pair is quoted in different findings and whose sanitized output is validated against the review-result.schema.json constraints (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, finding id) 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, and OutputRemoval/spanningPrivateKeys unit coverage.
  • internal/security/scanner_test.go: Added boundary tests for env_assignment, auth_header, and db_connection_password at exact minimum lengths with interior and trailing backslashes, plus a rune-vs-byte test for the json_field minimum.

Verification

  • go test ./internal/security/... passed (92.4% statement coverage for the package).
  • go test -run 'TestScanOutputFiles|TestSanitizeJSON' ./internal/cli/ and go 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 current main and 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/bin first in PATH.

Closes #5705

Checklist

  • PR title follows Conventional Commits (correct type, ! for breaking changes)
  • Commits are signed off (DCO) — human and human-directed agent sessions only
  • I wrote this contribution myself and can explain all changes in it

…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>
…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>
@qodo-code-review

qodo-code-review Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Preserve JSON validity and escaping during output redaction

🐞 Bug fix 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Sanitize parsed JSON values and keys without changing string framing or number precision.
• Preserve JSONL records and use valid replacement markers when redaction cannot safely retain
 structure.
• Keep delimiter escapes intact in text redaction and fail the agent run on sanitized-write errors.
Merge Risk 🟡 Medium

Blast radius 🔴 High 💥 3 capabilities

  • 3 affected capabilities span independent functional scopes: post_run_output_security, release_validation.
  • The scanner, sanitizer, redactor and run walk jointly implement one bounded behavior: sanitizing files produced by a completed agent run before artifact handling.
  • The follow-up changes candidate-run boundaries inside that same end-to-end behavior; it does not create a separate serializer capability.
  • False positives, unsupported decoder cases or overly broad cross-member and cross-record classification alter retained bytes of the same bounded post-run artifact behavior; they do not create a separate functional scope.
  • Result publication is a distinct user-visible operation within the same bounded post-run output integration.
  • The scan outcome, typed terminal causes and result-file checks jointly determine whether the safely retained agent result is posted.
  • The script, pinned fixture metadata, Makefile target and release workflow jointly implement one bounded validation behavior: detecting whether the schema used by sanitizer tests has drifted from its pinned upstream source.
  • This is independent of post-run artifact processing because it affects CI validation rather than runtime artifact handling.
Sources

internal/security/testdata/review-result.schema.pin[1-10]

# Pin for internal/security/testdata/review-result.schema.json.
#
# The vendored review-result schema is a test fixture copied from
# fullsend-ai/agents. Re-vendor the schema and update this pin together whenever
# the upstream schema changes. scripts/check-review-schema-pin.sh compares the
# vendored copy against upstream at the commit below and reports drift, so the
# jsonsanitize tests cannot silently validate against an outdated schema.
repo=fullsend-ai/agents
commit=cec09212b99fcd78bf7afc7637d8fe0b2007e109
path=schemas/review-result.schema.json

scripts/check-review-schema-pin.sh[48-66]

if ! jq -e . "${SCHEMA}" >/dev/null 2>&1; then
  fail "Vendored review-result schema is not valid JSON: ${SCHEMA}"
fi

upstream="$(mktemp)"
trap 'rm -f "${upstream}"' EXIT

if ! gh api -H "Accept: application/vnd.github.raw" \
  "repos/${repo}/contents/${path}?ref=${commit}" > "${upstream}" 2>/dev/null; then
  fail "Failed to fetch ${repo}/${path} at ${commit}"
fi

if ! jq -e . "${upstream}" >/dev/null 2>&1; then
  fail "Upstream ${repo}/${path} at ${commit} is not valid JSON"
fi

# Compare the documents semantically: a re-vendored file may be reformatted or
# have its keys reordered without drifting from upstream.
if diff <(jq -S . "${upstream}") <(jq -S . "${SCHEMA}") >/dev/null; then

.github/workflows/release.yml[182-190]

      - name: Review-result schema pin drift check (informational)
        # The vendored review-result schema is a test fixture, not a release
        # input, so a stale pin only weakens a test. Re-vendoring is a
        # maintainer decision, so this annotates the run instead of blocking
        # it (scripts/check-review-schema-pin.sh).
        continue-on-error: true
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: bash scripts/check-review-schema-pin.sh
Behavioral complexity 🟡 Medium 🧩 Multiple interactions

  • Before: text scanning rewrote matching bytes and joined-run handling treated digits or simple uppercase runs as sufficient evidence.
  • After: JSON and JSONL preserve framing, multi-document streams are recognized by content, embedded base64 runs are joined, schema-constrained fields break candidate runs, all-single runs are tracked separately from longer members, and unchanged JSON is returned byte-for-byte.
  • New correctness conditions: every secret must be localized without invalidating syntax or framing; unrelated schema values must survive marker-spanning content; single-character values must join only when they represent a reconstructed body; nonstandard JSON streams must use the correct record path; and clean bytes must not be rewritten merely by newline normalization.
  • The all-single logic is a newly interacting branch/state, while the surrounding tokenization and scanning infrastructure is reused.
Potential damage 🔴 High 🩹 Confidentiality

  • If structural localization, all-single joined-run handling, whole-value rescanning or failure containment misses a secret, an uploaded run artifact can retain credentials or private-key material.
  • Future runs can be protected by reverting or repairing the sanitizer.
  • Already exposed artifacts require deletion and credentials require rotation or equivalent external remediation; automatic compensation is not established.
Assessed commit 99b1662
Diagram

graph TD
  A["Agent outputs"] --> B["Output scan"] --> G["Security pipeline"] --> C{"Output format"}
  C -->|JSON| D["Structural scan"] --> H["Sanitized files"]
  C -->|JSONL| E["Record scan"] --> H
  C -->|Other| F["Text scan"] --> H
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Token-preserving streaming JSON sanitizer
  • ➕ Could sanitize duplicate-key objects without collapsing keys.
  • ➕ Could retain more of the original document layout.
  • ➖ Requires substantially more complex token and byte-range handling.
  • ➖ Raises the risk of another escape-boundary error.

Recommendation: Use the PR's parsed-JSON approach for the incident fix: it keeps redaction away from JSON framing and retains the existing security pipeline. The streaming alternative is worth considering only if preserving duplicate-key documents becomes a requirement; the current fallback favors avoiding unsafe structural rewrites.

Files changed (4) +1224 / -11

Bug fix (2) +556 / -11
run.goRoute output sanitization by format and propagate write failures +498/-6

Route output sanitization by format and propagate write failures

• Adds structural sanitization for single-document JSON, record-wise JSONL handling, duplicate-key detection, serialized-text backstops, and valid fail-closed markers where needed. Preserves numeric representations with json.Number and makes sanitized-write errors fail the post-agent scan.

internal/cli/run.go

redactor.goPreserve quote escapes while masking captured secrets +58/-5

Preserve quote escapes while masking captured secrets

• Adjusts capture handling so an escaping backslash before a quote remains outside the redacted span, while interior backslashes remain eligible for redaction. Extends quoted-field matching, exposes Mask for structural JSON handling, and adds a runtime-secret reset helper for tests.

internal/security/redactor.go

Tests (2) +668 / -0
scan_output_telemetry_test.goCover JSON integrity, JSONL records, and fail-closed output writes +495/-0

Cover JSON integrity, JSONL records, and fail-closed output writes

• Adds regressions for escaped strings, keys, number precision, duplicate keys, cross-value private-key matches, JSONL line counts, and repeated scans. Injected writer failures verify error propagation and quiet-mode path handling.

internal/cli/scan_output_telemetry_test.go

scanner_test.goExercise escape boundaries and quoted credential patterns +173/-0

Exercise escape boundaries and quoted credential patterns

• Adds scanner regressions for escaped JSON quotes, credentials with interior or trailing backslashes, minimum-length captures, and quoted YAML-style fields. Checks that affected JSON remains parseable and credentials are removed.

internal/security/scanner_test.go

@fullsend-ai-review

fullsend-ai-review Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

🤖 Review · ⚠️ Cancelled · Started 11:43 AM UTC · Ended 11:45 AM UTC

Commit: 05deda0 · View workflow run →

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

@qodo-code-review

qodo-code-review Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Encoded secrets survive duplicate JSON keys ✓ Resolved Bug Security

Resolving commit: f66628b

Resolution reason
The duplicate-key path no longer skips structural scanning. SanitizeJSONDocument routes
duplicate-key documents to sanitizeDuplicateKeyDocument, which uses rewriteJSONTokens to walk every
key and scalar token (keeping all duplicate occurrences) and scans each one, then backstops the
serialized output and fails closed with a valid marker when redaction would break JSON. The JSONL
path uses SanitizeJSONLines, which calls SanitizeJSONDocument per record. A test
(TestSanitizeJSONDocument_DuplicateKeyEarlierOccurrenceRedacted and
TestSanitizeJSONLines_DuplicateKeyRecordRedactsEscapedSecret) pins that an escaped secret in an
earlier duplicate value is redacted. The fix uses a token-preserving walk rather than the suggested
fail-closed-marker-for-all approach, but addresses the issue.
Description
scanOutputFilesWithWriter skips structural scanning when hasDuplicateJSONKeys is true, leaving
only a raw-text scan of the file. If an earlier duplicate value contains a registered secret written
with JSON Unicode escapes and a later value replaces it during decoding, neither the raw scan nor a
scan of the decoded last value catches the earlier secret; the same loss occurs in the JSONL
duplicate-key branch.


Remediation recommended

2. Serialized secrets survive the backstop ✓ Resolved Bug Security

Resolving commit: f66628b

Resolution reason
The old run.go name-count backstop (backstopHasNewFinding and the changed-flag logic) is removed.
Serialized-JSON backstopping moves to security.backstopSerializedJSON
(internal/security/jsonsanitize.go), which no longer dismisses backstop findings by name: whenever
the re-serialized document still yields any finding, it is replaced with the redacted text if valid
JSON, or with a fail-closed marker otherwise (private_key or invalid JSON). Also,
SanitizeJSONDocument runs the backstop on the encoded output in every case (including when
structural findings exist), so a second runtime secret spanning serialized leaves is caught and not
written unredacted. Test TestSanitizeJSONDocument_BackstopRedactsSecondRuntimeSecret pins the
two-runtime-secret scenario.
Description
backstopHasNewFinding compares finding names and counts rather than the matches that produced
them. If structural scanning finds one runtime secret in a leaf and serialization exposes a
different registered runtime secret across two leaves, the backstop's one runtime_secret finding
is treated as already handled and the serialized document is written without its redaction.

3. Invisible JSON keys survive sanitization ✓ Resolved Bug Correctness

Resolving commit: f66628b

Resolution reason
When a key has findings and the sanitized key is empty, the key is replaced with the placeholder
"redacted" (with collision suffixing) instead of retaining the original key; a regression test
covers a null-byte key producing valid JSON without that key.
Description
sanitizeJSONStructure retains the original key whenever keyRes.Sanitized is empty, even when the
pipeline reports that the key must be removed. A key consisting solely of a null byte therefore
produces a finding and triggers a rewrite, but the rewritten JSON still contains that null-byte key.

4. Cross-record secrets remain in output ✓ Resolved Bug Security

Resolving commit: f66628b

Resolution reason
The old sanitizeJSONLines (whole-stream scan with private_key-only check) is removed and replaced by
security.SanitizeJSONLines. Its whole-stream scan now runs on the rebuilt stream and, if any finding
remains, failClosedRecordSpans replaces every record overlapping the changed region with a
fail-closed marker, using all stream findings (not only private_key). A new test
TestSanitizeJSONLines_CrossRecordRuntimeSecretFailsClosed registers a runtime secret spanning the
record boundary and asserts the secret is absent and record count is preserved. This is a different
implementation than the suggested prompt but addresses the same issue.
Description
sanitizeJSONLines runs a whole-stream scan but acts on its findings only when one is named
private_key. A registered runtime secret that includes the newline and JSON framing between two
valid records is found by that scan but not by either record's structural scan or backstop, so the
caller leaves the file unchanged.

Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #7553
❌ Tickets: failed to load — Ticket collection could not establish complete evidence
✅ Compliance rules (platform): 96 rules
✅ Skills: 5 invoked
  writing-user-docs
  writing-adrs
  check-patch-coverage
  cutting-releases
  adr-corner
✅ Cross-repo context — repo relationships
  Explored: repo: fullsend-ai/agents (sha: f6907db2) — View relationship
✅ Context preparation
  Commit messages: summarized; full text retained for this review
Review mode: Auto: ⚖️ Balanced: Downgraded extended -> standard: change is below the extended eligibility bar (hunks 14/18, lines 1235/200; both must reach the floor). Router rationale: Dense security-sensitive changes span JSON, JSONL, redaction, and failure 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/cli/run.go Resolved
Comment thread internal/cli/run.go Resolved
Comment thread internal/cli/run.go Resolved
Comment thread internal/cli/run.go Resolved
@fullsend-ai-review

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

Copy link
Copy Markdown

🤖 Finished Review · ⚠️ Cancelled · Started 11:37 AM UTC · Completed 11:42 AM UTC

Commit: 40973ad · View workflow run →

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>
@fullsend-ai-review

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

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 11:46 AM UTC · Completed 12:00 PM UTC

Commit: a7bfefc · View workflow run →

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

@fullsend-ai-review fullsend-ai-review Bot added risk/elevated PR risk: elevated and removed risk/moderate PR risk: moderate labels Dec 3, 2026
@fullsend-ai-review

Copy link
Copy Markdown

Risk Assessment: elevated (3/5)

Details

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

@fullsend-ai-review

Copy link
Copy Markdown

Review

Findings

High

  • [logic-error] internal/security/jsonsanitize.go:508 — Mixed-length PEM chunks still survive sanitization. Between BEGIN/END markers, chunks ["MIIEowIB","A","AKCAQEA","x","9Kq2Lm0"] repeatedly flush (the new allSingle logic flushes whenever a one-character value follows a longer member) before the joined material reaches the pemBodyJoined threshold. Every chunk is individually too short for textCarriesKeyMaterial, so the markers are removed while the body remains recoverable. Uniform one-character chunks are now supported, but uneven chunking still defeats the mechanism. maskMiddleRecordBody (JSONL, ~line 1007) has the same behavior.
    Remediation: Evaluate candidate body material across mixed-length chunks without discarding accumulated evidence at single-character boundaries. Add document and JSONL regression tests for interleaved single-character and longer chunks.
  • [logic-error] internal/security/jsonsanitize.go:500 — A short body fragment preceding a recognized full body line is flushed without being masked. Between BEGIN/END markers, ["MIIEowIB","AAKCAQEAx7Qz9restOfTheBodyWq1Ez"] leaves "MIIEowIB" intact: when the second leaf (a complete body line, valueCarriesKeyMaterial) calls flush(), the pending first fragment fails the joined minimum; bodySeeded only protects subsequent fragments. Same asymmetry in maskMiddleRecordBody. The final rescan cannot detect the surviving material after the markers have been removed.
    Remediation: Use a recognized body line to classify adjacent candidate fragments on both sides, not only following fragments. Add tests with short initial fragments before full body lines for both document and JSONL paths.
  • [logic-error] internal/security/jsonsanitize.go:542 — Key names containing fragmented body material are not sanitized. A middle object key such as "MIIEowIB AAKCAQEA" between BEGIN/END marker members has no individual 16-character run, so textCarriesKeyMaterial returns false; maskSpanBody skips keys altogether (line 478-481) and the ordinary key scan sees neither a complete PEM block nor another secret pattern. The markers disappear while both body fragments remain in the serialized key. The JSONL key path has the same gap.
    Remediation: Classify body fragments carried in key names using their decoded provenance, including multiple short runs, without indiscriminately renaming structural keys. Add document and JSONL cases with whitespace-separated body chunks in a key.
  • [protected-path] .github/workflows/release.yml — This PR modifies protected governance/infrastructure paths: .github/workflows/release.yml (new continue-on-error review-schema pin check step), scripts/check-review-schema-pin.sh and scripts/check-review-schema-pin-test.sh. The PR description explains the JSON sanitizer fix for Output sanitizer should validate JSON structural integrity after redaction #5705 but does not mention or justify these protected-file changes, so the PR lacks justification for modifying governance or infrastructure files. Human approval is always required for protected-path changes.
    Remediation: Explain in the PR description why these protected files change (or move them to a separate, separately-authorized PR). A human maintainer must approve the protected-path changes.

Medium

  • [logic-error] internal/security/jsonsanitize.go:621 — Concatenating ordinary words still produces false PEM detections. Between quoted markers, values such as ["Use","HTTP","client","properly"] become "UseHTTPclientproperly", satisfy the length/case checks and hasMixedUpperRun, and are all replaced; a JSONL transcript containing those words in separate records loses those records entirely.
    Remediation: Preserve textual boundaries when classifying candidate material; do not treat an acronym followed by a separate lowercase word as sufficient PEM evidence. Add prose/acronym regression fixtures.
  • [logic-error] internal/security/jsonsanitize.go:390 — Spanning-block localization performs a complete leaf-range scan for every block. With N leaves and O(N) separate framing-spanning blocks this is O(N^2), plus a linear leafContaining search per match. Large transcripts with repeated private-key examples can make the mandatory post-agent scan disproportionately expensive. The record-level implementation likewise scans all records and leaves for each block.
    Remediation: Use the ordered match offsets and ordered provenance ranges with advancing cursors or indexed range lookup so localization visits only overlapping leaves/records. Add a scaling test with many disjoint blocks.
  • [secret-exposure] internal/security/jsonsanitize.go:484 — Schema-named fields bypass joined-body detection (isSchemaConstrainedField flushes and skips) without validating their values against a schema. Between BEGIN/END private-key markers, storing successive short body chunks under file, category, reason, or other exempt member names preserves them: MIIEowIB, AAKCAQEA, x9Kq2Lm0 are individually below the material-length floor and never joined. Markers are masked but the reconstructable body survives. The JSONL counterpart has the same gap at ~line 987.
    Remediation: Do not infer structural safety from a member name alone. Validate actual structural values in their schema context, include other values in spanning-body detection, or conservatively remove the affected output when localization is uncertain.
  • [secret-exposure] internal/security/jsonsanitize.go:508 — The new allSingle handling catches a body stored entirely one character per value, but a body split into alternating one- and two-character values is still preserved: each single-character value following a longer fragment flushes the candidate group before it reaches pemBodyJoined's 16-byte minimum. BEGIN/END markers are removed while the fragments remain reconstructable. maskMiddleRecordBody repeats this at ~line 1007.
    Remediation: Evaluate a complete candidate body across mixed fragment sizes rather than flushing solely because the next fragment has length one; preserve isolated free-text characters using contextual localization, or fail closed if a detected block cannot be localized.
  • [incorrect-doc] docs/cli/run.md:468 — The 'How a run ends' table in docs/cli/run.md (unchanged by this PR) states that fullsend run returns an error in these cases but omits post-agent output-scan and audit-chain failures introduced in internal/cli/run.go (scanOutputFiles, collectPostScanSecurityArtifacts, postScanRunError): the run now fails closed when the scan cannot read, sanitize or write an output file, even if the agent exited 0 or validation passed.
    Remediation: Update the failure table under 'How a run ends' to document that fullsend run also exits non-zero when the post-agent output scan fails or sandbox audit-log integrity verification fails.
  • [incorrect-doc] docs/cli/run.md:479 — The post-script rules without a validation_loop (docs/cli/run.md, unchanged) say a failed agent still gets its post-script when it left a JSON result file of at most 4 MiB. After postScriptGate/agentResultFile changes in internal/cli/run.go: a scan-only failure also runs the post-script if an intact result file survived; a result file replaced by a fail-closed scan marker or whose sanitization/write failed does not qualify; an agent failure joined with an audit chain failure or timeout skips the post-script.
    Remediation: Update docs/cli/run.md (~line 479) to document scan-only failures, marker-replaced/unwritable result files being ineligible, and audit chain failures skipping the post-script.
  • [incomplete-doc] docs/guides/user/bring-your-own-agent.md:918 — The guide's explanation of post-script execution without a validation_loop (unchanged by this PR) says any agent failure still runs the post-script when the agent left a parseable result file. After the postScriptGate changes in internal/cli/run.go this is incomplete: output-scan failures also run it when an intact result file survived; result files quarantined or replaced with fail-closed markers by the scan do not count; joined audit-chain failures prevent it.
    Remediation: Update docs/guides/user/bring-your-own-agent.md (~line 918) to note scan-failure behavior and that quarantined/marker-replaced result files do not trigger the post-script.

Low

  • [secret-exposure] internal/security/jsonsanitize.go:478 — Short private-key body chunks stored as object keys never participate in reconstruction. An object with BEGIN and END marker keys and intervening keys MIIEowIB, AAKCAQEA, x9Kq2Lm0 retains all three chunks after sanitization; short keys fail the individual material test and are explicitly skipped by the joined test (line 478-481). JSONL key handling also skips reconstruction.
    Remediation: Distinguish validated structural member names from arbitrary keys carrying body fragments, and reconstruct candidate key fragments within a detected block. Fail closed when the distinction cannot be made safely.
  • [injection-vuln] scripts/check-review-schema-pin.sh:67 — The new workflow annotation interpolates repo and path from the pin file into ::error::/::notice:: commands. The fail helper (line 27) only removes literal '::' and does not handle percent-encoded newlines, ANSI escapes or control characters; repo and path are only checked for non-emptiness, and PIN/SCHEMA env paths and an invalid commit value reach annotations unsanitized. The current invocation (release.yml step) uses the checked-in pin file, not fork-event input.
    Remediation: Use one annotation-output helper that encodes percent signs and line endings and rejects/strips control characters; apply it to every dynamic diagnostic and notice value.
  • [scope-creep] scripts/check-review-schema-pin.sh:1 — The incremental diff introduces a review-result schema pin drift-check subsystem (scripts/check-review-schema-pin.sh, scripts/check-review-schema-pin-test.sh, internal/security/testdata/review-result.schema.pin, a Makefile script-test entry, and a new continue-on-error step in .github/workflows/release.yml). It is neither covered by prior-review remediation candidates (only internal/security/jsonsanitize.go) nor authorized by linked issue Output sanitizer should validate JSON structural integrity after redaction #5705, which is scoped to output-sanitizer corruption of JSON structure.
    Remediation: Remove the schema-pin drift tooling (script, test, pin file, Makefile entry, release workflow step) from this PR or justify it in the PR description; alternatively submit it separately with its own issue authorization.

Earlier findings

  • internal/security/jsonsanitize.go:390, logic-error — reclassified from high to medium: the repeated full-range scan is a performance cost that grows with the number of complete private-key blocks, not a correctness or data-exposure failure (still open at the lower severity).
  • Open findings from earlier rounds that this push did not address (the mixed-length PEM chunk, short-fragment, key-name, schema-field and docs findings above) remain open; the latest commits only handled uniform single-character chunks.

Labels: The PR touches the release workflow and substantial documentation in addition to the Go sanitizer fix.


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

Copy link
Copy Markdown

Finding threads left open (21):

  1. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  2. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  3. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  4. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  5. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  6. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  7. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  8. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  9. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  10. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  11. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  12. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  13. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  14. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  15. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  16. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  17. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  18. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  19. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  20. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  21. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.

Outdated review threads left open (1):

  1. Thread: the review bot could not resolve this outdated thread. Reason: FORBIDDEN: Resource not accessible by integration. Next step: resolve it manually.

@fullsend-ai-review fullsend-ai-review Bot added component/ci CI pipelines and checks component/docs User-facing documentation labels Dec 3, 2026

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

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?

  1. The redactor escape fix plus SanitizeJSONDocument / SanitizeJSONLines (this closes #5705)
  2. Private keys that span members or records
  3. The run.go post-script and quiet comment 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" \

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.

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.

@andrewevansrh andrewevansrh Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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]*(?:,|\}|\]|$))`},

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.

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?

@andrewevansrh andrewevansrh Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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 {

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.

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?

@andrewevansrh andrewevansrh Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

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.

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?

@andrewevansrh andrewevansrh Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

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.

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.

@andrewevansrh andrewevansrh Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

@fullsend-ai-review

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

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 2:42 PM UTC · Completed 3:02 PM UTC

Commit: 99b1662 · View workflow run →

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

@fullsend-ai-review

Copy link
Copy Markdown

Risk Assessment: elevated (3/5)

Details

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

@fullsend-ai-review

Copy link
Copy Markdown

Review

Findings

Medium

  • [logic-error] internal/security/jsonsanitize.go:508 — Mixed-length body chunks are not reconstructed: a one-character chunk after a longer one flushes the pending group, so a private-key body split into alternating chunk lengths survives after its BEGIN/END members are masked. The JSONL path (maskMiddleRecordBody) behaves the same.
    Remediation: Reconstruct candidate body material independently of chunk length, in both paths, and add alternating-length regression cases.
  • [secret-exposure] internal/security/jsonsanitize.go:508 — Same mechanism seen from the exposure side: sub-16-character groups of body material survive once the enclosing markers are removed, so the final rescan cannot recognize them.
    Remediation: Contain ambiguous material inside a detected block conservatively instead of discarding evidence at each one-character boundary.
  • [logic-error] internal/security/jsonsanitize.go:621 — pemBodyJoined requires adjacent uppercase letters followed by lowercase (hasMixedUpperRun), which is not a base64 property. Short chunks that join to a valid body without such a run are not recognized.
    Remediation: Do not make the uppercase-run shape a necessary condition for material inside an already detected private-key span; cover both document and JSONL paths.
  • [logic-error] internal/security/jsonsanitize.go:501 — Once bodySeeded is set, every following candidate value is masked, including ordinary prose (pemBodyRuns pulls words out of sentences). Unrelated report text, or a whole JSONL record, is discarded.
    Remediation: Bound propagation from a recognized body line using fragment evidence, and add tests with prose following a body line.
  • [secret-exposure] internal/security/jsonsanitize.go:484 — The schema-field exemption trusts a member's name (file, category, severity, id, ...) without validating its value, so short body fragments stored under those names survive between masked markers. The JSONL counterpart has the same exemption.
    Remediation: Validate structural values against their real constraints instead of exempting by name, and keep a conservative containment path for ambiguous fragments.
  • [incorrect-doc] docs/cli/run.md:468 — "How a run ends" omits that a post-agent output scan failure fails fullsend run, and that the post-script is skipped when the scan could not redact the result file (or still runs while the run fails when the scan failed only on other files).
    Remediation: Add the scan-failure row to the failure table and update the post-script rules at lines 478–482.
  • [incomplete-doc] docs/guides/user/bring-your-own-agent.md:918 — The post-script rule ("still runs when the agent left a parseable result file") has no exception for an output-scan failure on the result file.
    Remediation: Qualify the rule around lines 918–921 and link to the updated run.md section.
  • [protected-path] .github/workflows/release.yml — The PR modifies protected paths (.github/workflows/release.yml, scripts/check-review-schema-pin.sh, scripts/check-review-schema-pin-test.sh). It links Output sanitizer should validate JSON structural integrity after redaction #5705, but neither the PR description nor that issue explains these changes (only a commit message does). Human approval is always required for protected-path changes.

Low

  • [logic-error] internal/security/jsonsanitize.go:500 — A recognized body line flushes preceding short fragments before seeding, so a fragment such as AQAB just before it is left unmasked (JSONL too).
    Remediation: Evaluate preceding candidate fragments together with the recognized body line before flushing.
  • [secret-exposure] internal/security/jsonsanitize.go:416 — Same ordering issue seen from the exposure side: an isolated short fragment before a recognized body line survives.
    Remediation: Include adjacent preceding fragments in the masking decision once a recognized line establishes provenance.
  • [logic-error] internal/security/jsonsanitize.go:542 — An isolated body fragment under the 16-character floor is never masked ([BEGIN, "MIIEb2R5", END]), although the block is reported as localized.
    Remediation: Treat short fragments inside a detected block conservatively; add short-fragment tests for JSON and JSONL.
  • [logic-error] internal/security/jsonsanitize.go:543 — pemBodyRun requires upper, lower, digit and a non-hex character, so a digit-free body line stored as an object key (e.g. MIIEowIBAAKCAQEA) is retained.
    Remediation: Drop the character-mixture requirement for material inside a detected span, including key names.
  • [logic-error] internal/security/jsonsanitize.go:478 — Object keys are skipped when reconstructing split body material, so a body spread over several short key names is never joined (JSONL too).
    Remediation: Include material-bearing key fragments in provenance-based reconstruction, or fail closed when localization is ambiguous.
  • [secret-exposure] internal/security/jsonsanitize.go:478 — Same gap from the exposure side: short PEM chunks in key names survive between masked boundary markers.
    Remediation: Track key-name fragments with provenance so they can be masked without renaming unrelated structural keys.
  • [logic-error] internal/security/jsonsanitize.go:382 — Numeric scalar members inside a detected block have no provenance range (collectJSONLeaves records only strings), so digit-only fragments encoded as JSON numbers are not covered.
    Remediation: Account for numeric members inside detected spans, or fail closed when the span holds material that cannot be localized.
  • [secret-exposure] internal/security/jsonsanitize.go:391 — Same numeric-leaf gap from the exposure side.
    Remediation: Mask numeric fragments that belong to a detected block, writing a string placeholder to keep the JSON valid.
  • [logic-error] internal/security/jsonsanitize.go:390 — Each private-key match scans the whole leaf-range list (and leafContaining restarts from the beginning), so cost grows with matches × leaves.
    Remediation: Use advancing cursors or an indexed range lookup over the ordered ranges; add a scaling test.

Earlier findings

  • internal/security/jsonsanitize.go:508, logic-error — reclassified high → medium: reproduced in the current code, but it needs a body deliberately split into alternating chunk lengths, and the code documents it as a residual.
  • internal/security/jsonsanitize.go:621, logic-error — reclassified high → medium: a real body joins into one long string that almost always contains an uppercase-then-lowercase run.
  • internal/security/jsonsanitize.go:501, logic-error — reclassified high → medium: the effect is over-redaction inside a detected key span, not exposure.
  • internal/security/jsonsanitize.go:542, :543, :478, :382, logic-error — reclassified high → low: the leaks are limited to short or digit-only fragments in contrived encodings.
  • internal/security/jsonsanitize.go:500, :390, logic-error — reclassified medium → low.
  • internal/security/jsonsanitize.go:391, secret-exposure — reclassified medium → low (numeric-only fragments).
  • scripts/check-review-schema-pin.sh:67, injection-vuln — reclassified low → info: the annotated values come from a committed pin file with no untrusted input path.
  • scripts/check-review-schema-pin.sh, scope-creep — reclassified low → info: the drift check supports the vendored schema fixture that the new tests use.

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

flush()
continue
}
if len(material) == 1 && !allSingle {

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

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

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

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

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

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

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

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

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

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

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

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

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

@fullsend-ai-review

Copy link
Copy Markdown

Finding threads left open (29):

  1. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  2. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  3. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  4. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  5. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  6. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  7. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  8. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  9. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  10. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  11. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  12. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  13. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  14. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  15. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  16. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  17. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  18. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  19. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  20. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  21. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  22. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  23. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  24. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  25. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  26. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  27. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  28. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.
  29. Thread: the review threads could not be read, so older copies of this open finding could not be checked. Next step: look for older copies of this finding, keep one thread open and resolve the other copies manually.

Outdated review threads left open (1):

  1. Thread: the review bot could not resolve this outdated thread. Reason: FORBIDDEN: Resource not accessible by integration. Next step: resolve it manually.

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

Review sweep: 3 findings, posted inline (1 HIGH, 2 MEDIUM).

Comment thread internal/cli/run.go
var scanErr *outputScanError
scanFailed := errors.As(runErr, &scanErr)
if scanFailed {
if resultFile, ok := agentResultFile(h, outputDir); ok && scanErr.failedOn(resultFile) {

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.

[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]*(?:,|\}|\]|$))`},

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

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] 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) calls pemBodyRuns, 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 requires hasMixedUpperRun: two or more capitals followed by lower case. So prose such as Updated README instructions becomes UpdatedREADMEinstructions and 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

@andrewevansrh

andrewevansrh commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Split into three, as asked. Each one is a single commit on its own branch, so a
revert of one does not take the others, and all three are filed here on
fullsend-ai/fullsend against main so they land in order:

  1. fix(#5705)!: stop JSON redaction from eating escaping backslashes #10082 — the redactor escape fix plus SanitizeJSONDocument /
    SanitizeJSONLines (closes Output sanitizer should validate JSON structural integrity after redaction #5705). Also carries the json_field escapes, the
    Mask prefix guard, the vendored review-result schema and its .pin, and the
    doc section trimmed to what the scan does and why. Ready for review.
  2. fix(#5705): mask private-key blocks that span JSON members or records #10084 — private keys that span members or records. Draft while fix(#5705)!: stop JSON redaction from eating escaping backslashes #10082 is
    open.
  3. fix(#5705): run the post-script when the scan was the only failure #10085 — the run.go post-script and quiet comment changes. Draft while
    fix(#5705): mask private-key blocks that span JSON members or records #10084 is open.

Each of 2 and 3 is based on the branch below it, so its diff is cumulative until
the one below lands. After #10082 merges 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 #10082 is unblocked, and for the other two
git diff agent/5705-json-sanitizer..agent/5705-spanning-private-keys (and then
agent/5705-spanning-private-keys..agent/5705-post-script-gating) is exactly the
delta to read in the meantime.

To answer the five inline points briefly: the schema-pin drift check is out of all
three (it will come back on its own, comparing against agents@main as you
suggested); the six-group json_field pattern is unchanged in part 1 and I would
rather rewrite it against its regression matrix as its own change than inside the
fix you asked me to shrink; the spanning-key heuristic is defensive and now
isolated in part 2, where failing closed instead of guessing is a one-PR switch;
the exported ResetRuntimeSecretsForTest has to stay exported because
internal/cli tests call it, but internal/security tests now call the
unexported function directly; and the doc section is down from 154 added lines to
about 86 across the three parts.

This PR is superseded by the three and can be closed. Detail is in the individual
replies below.

Note: Generated with assistance from DeepSeek V4.1 Flash

@andrewevansrh

andrewevansrh commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Closing in favor of the three split PRs: #10082 (redactor + structural JSON, closes #5705), #10084 (spanning private keys), #10085 (run.go post-script and quiet). Nothing here is lost — the three branches together carry exactly this tree minus the schema-pin drift check.

Note: Generated with assistance from DeepSeek V4.1 Flash

This branch was successfully deployed

1 active deployment
site-preview — 99b16625 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

component/ci CI pipelines and checks component/docs User-facing documentation component/runner Agent runner behavior and lifecycle go Pull requests that update go code risk/elevated PR risk: elevated security Security threat model and related concerns type/bug Confirmed defect in existing behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Output sanitizer should validate JSON structural integrity after redaction

3 participants