diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index de2e46ffd0..a543bd51cb 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -634,6 +634,90 @@ The post-run output scan skips `/skills/` and 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 + +`scanOutputFiles` runs the output pipeline (Unicode normalization, then secret +redaction) over every file under the run directory (`/`, including +`iteration-N/` transcripts) except the skips above, any directory named +`security` (which holds `findings.jsonl`), and the telemetry JSONL. + +A file whose content is one JSON document — or two or more newline-delimited +ones — is sanitized structurally, so redaction never changes its syntax. The +document is rewritten by a token-preserving walk rather than decoded into a map +and re-encoded: member order and duplicate keys survive, so an earlier value that +map decoding would drop is still scanned. Each object key and string value is +scanned on its own; a value whose member name marks it sensitive (key, token, +secret, password, credential, auth) is masked even when the value matches no +pattern, and a sanitized key name that would collide with a different member is +disambiguated (`_`). A leading UTF-8 BOM is stripped before the walk and +restored on write, and a clean document comes back byte for byte. + +After the rewrite the serialized bytes are scanned once more, but only for +whole-value secrets — registered runtime values and private-key blocks — because +those are the only matches a leaf scan cannot see once a member value is masked. +Every other pattern has already been applied to the decoded key or value, so a +match on the serialized bytes would be a redaction placeholder plus JSON escape +characters, not a secret (#5705). + +A private-key block can also span members or records: one string holds the BEGIN +marker, another the body, a third the END marker. Masking any of them would hide +the marker from every later scan, so such a block is detected on a decoded view +of the document or stream before anything is rewritten, and handled where it +lives. The members the match starts and ends in carry marker text, so they are +always masked — even when a marker is split across two members and neither +fragment looks like one alone. A member in between is masked when it carries a +block marker, a run that looks like body material (16+ base64 characters mixing +upper case, lower case and a digit, and not hex only), or when the joined text of +consecutive members does, which is what catches a body split into short chunks. An +object key keeps its name unless the name itself is block content, so a document +that merely quotes the PEM header in one finding and the footer in another keeps +the shape `review-result.schema.json` accepts, including its enum-valued fields. +A body split so that one-character and longer chunks alternate is a known +residual; uniform chunks and complete body lines are masked. Records that carry +part of a block across a record boundary are replaced with a fail-closed marker +instead, because the framing itself cannot be rewritten. + +Some content cannot be redacted in place. A JSON document or JSONL record is +replaced with a valid fail-closed marker instead — never with corrupted +syntax — when a redaction would invalidate the JSON or a match spans record +boundaries. Markers look like `{"error":"output removed because …"}` and are +logged as findings in `security/findings.jsonl`. Because a replaced file loses +everything the agent wrote into it and the run still exits 0, the reason a +marker states is also emitted as a `::error::` workflow command whenever the job +sets `GITHUB_ACTIONS=true`. GitHub Actions renders it as an error annotation. +Forgejo Actions also sets `GITHUB_ACTIONS=true`, so its runner writes the same +line, but Forgejo has no annotation view: the line appears in the step log and +the exit status stays 0. On GitLab the line is not written at all. + +A file that cannot be read, sanitized or written does not stop the walk: every +remaining file is still scanned and redacted, and the run fails closed afterwards +with all failures joined. The unredacted file is replaced with the fail-closed +marker so its bytes do not reach the uploaded artifact when the filesystem allows +it; if the marker write and the fallback removal both fail, that failure is added +to the joined error rather than left unreported. In `quiet` mode the printed log +counts the affected paths instead of naming them (ADR 0163); the run error and +telemetry keep the path and the wrapped cause at every level, and only the +printed line is trimmed. The completion comment counts them too: an output file +name is the agent's to choose and Actions log masking does not apply to a +comment, so at `quiet` a failed scan posts how many files it could not handle +instead of naming one. The scan failure is the only run error the comment +rewrites today; applying the level to the rest is tracked in #9627. + +A failed scan fails the run but does not silence the agent's own result. The +post-script runs after the scan, so when the run failed with a scan error the gate +skips it — unless that scan failure is the run's only failure and the result file +the harness names (`agent-result.json` by default) survived the scan and still +holds a JSON object. Then the post-script runs, posts the result, and the run +still fails, so one unreadable or unwritable file somewhere else under the run +directory cannot turn a completed report into silence. A run that also timed out, +broke its audit chain or reported a transcript error keeps that cause's outcome: +the scan does not turn it into a post-script run, and each cause is kept separate +in the run error (`postScanError`) rather than flattened into one join, so the gate +can tell a scan-only failure from a joined one. A result file the scan replaced +with a fail-closed marker does not count — the marker is valid JSON, but it is not +the agent's result — and neither does one the scan failed on, whose unredacted +bytes may still parse. + ## Agent rule layering When `fullsend run` executes an agent, Claude Code loads instructions from diff --git a/docs/guides/dev/tracing.md b/docs/guides/dev/tracing.md index 7666c7c9ee..018056582d 100644 --- a/docs/guides/dev/tracing.md +++ b/docs/guides/dev/tracing.md @@ -395,7 +395,7 @@ cut can take the `@` that marks a password and the tail cut the `https://` before it (`promptHidesAlterations`) — is recorded `***` whole; the prompt the agent is sent is not changed, and the mask the first scan leaves for a connection-string password of ten or more bytes matches -its own pattern and counts a finding — +its own pattern, counts a finding, and is itself masked `***` — and sets `gen_ai.input.messages` on the span before the runtime starts, so each finalize path carries it. Its findings join the iteration's, and its encoded size is charged against diff --git a/docs/guides/user/run-artifacts-and-private-data.md b/docs/guides/user/run-artifacts-and-private-data.md index 901d5d4ecb..c96ce82a65 100644 --- a/docs/guides/user/run-artifacts-and-private-data.md +++ b/docs/guides/user/run-artifacts-and-private-data.md @@ -345,7 +345,23 @@ Tool results in those files can quote what the agent read, such as the text of a private Jira issue. On a public repository, any signed-in user can download the artifact until it expires. The output scan masks secret literals; it does not remove personal data, customer names or other private -business text. +business text. A secret that cannot be localized replaces the whole JSON +document, or the JSONL record that carries it, with a JSON error marker, and a +file whose redacted content cannot be read, written or computed is replaced by +such a marker and fails the run. If the marker cannot be written and the file +cannot be removed either, the run's error says the unredacted file is still on +disk. A private-key block that spans JSON members is handled in place instead: +object keys keep their names unless a key name is itself a line of the key body, +and each string value — or key name — that carries block text or base64 key +material becomes `[REDACTED PRIVATE KEY]`. When a +replacement happens in a run that still exits 0, the job log says so. On GitHub +Actions this is an error annotation: fullsend writes a `::error::` workflow +command whenever the job sets `GITHUB_ACTIONS=true`, and GitHub Actions renders +it. Forgejo Actions also sets `GITHUB_ACTIONS=true`, so the same `::error::` +line is written there, but Forgejo has no annotation view: its runner prints the +line in the step log and the exit status stays 0. On GitLab the line is not +written at all, so the run's log is the signal. A read, write or sanitize +failure needs no annotation because the run itself fails. `fullsend run` leaves `output/` untouched. At the end of the job, `fullsend prepare-artifacts` builds a filtered copy at the level you set, and diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index dc474e5b60..ff82d9ca3b 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -1611,7 +1611,9 @@ At `quiet`: A setup error before that, such as a config or provider error, prints in full. The level covers the job log only: the status comment on the issue or pull request still carries the full run error - ([#9627](https://github.com/fullsend-ai/fullsend/issues/9627)). + ([#9627](https://github.com/fullsend-ai/fullsend/issues/9627)), except that a + failed output scan posts how many files it could not handle rather than a + name the agent chose. **Agent CLI stderr at `quiet`.** The agent CLI (Claude Code, pi, Codex or OpenCode) writes its own diagnostics to stderr, and they can quote what the diff --git a/internal/cli/content_collector.go b/internal/cli/content_collector.go index b7e5a5addd..452dddc88a 100644 --- a/internal/cli/content_collector.go +++ b/internal/cli/content_collector.go @@ -190,8 +190,9 @@ func attachContent(span trace.Span, res contentResult) { // values, once more after the fold, which can spell out a value that pass // saw in compatibility forms. The mask that first scan leaves for a // connection-string password of ten or more bytes ("abcd...") matches its -// own pattern again, so such a prompt counts a finding here; a shorter -// password is masked "***", which does not. +// own pattern again, so such a prompt counts a finding here and the +// placeholder is masked "***"; a shorter password is masked "***", which +// does not match. // The pipeline also folds compatibility characters the agent received // unfolded. Findings join the iteration's and surface through Result. // diff --git a/internal/cli/run.go b/internal/cli/run.go index abeb20c5d8..4e3fa6faba 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -1582,7 +1582,11 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep status = "cancelled" } else if runErr != nil { status = "failure" - detail = runErr.Error() + // Actions log masking does not apply to this comment, so an + // error that can quote text the agent chose supplies fixed + // wording at quiet (failureStatusDetail). Telemetry and the + // root span keep the full error. + detail = failureStatusDetail(runErr, progressVerbosity) } else if runSkipped { status = "skipped" detail = runSkipReason @@ -3513,33 +3517,19 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // 9f. Post-agent output scan — redact secrets from extracted output. if h.SecurityEnabled() { printer.StepStart("Running post-agent output scan") - if err := scanOutputFiles(runDir, securityTraceID, progressVerbosity, printer); err != nil { - printer.StepWarn(failureLine("Output scan error", err, progressVerbosity)) + scanErr := scanOutputFiles(runDir, securityTraceID, progressVerbosity, printer) + if scanErr != nil { + printer.StepFail(failureLine("Output scan failed", scanErr, progressVerbosity)) } - - // Extract sandbox-side security findings for audit trail. - findingsDir := filepath.Join(runDir, "security") - if err := os.MkdirAll(findingsDir, 0o755); err == nil { - remoteFindingsDir := sandbox.SandboxWorkspace + "/.security/" - if dlErr := sandbox.Download(sandboxName, remoteFindingsDir, findingsDir); dlErr != nil { - printer.StepInfo("No sandbox security findings to extract") - } else { - printer.StepDone("Security findings extracted") - } - } - - findingsJSONL := filepath.Join(runDir, "security", "findings.jsonl") - if _, statErr := os.Stat(findingsJSONL); statErr == nil { - cv, verifyErr := security.VerifyChain(findingsJSONL) - if verifyErr != nil { - printer.StepWarn(failureLine("Audit log verification error", verifyErr, progressVerbosity)) - } else if !cv.Valid { - line, chainErr := auditChainFailure(cv.BrokenMsg, progressVerbosity) - printer.StepFail(line) - return chainErr - } else if cv.Entries > 0 { - printer.StepDone(fmt.Sprintf("Audit log integrity verified (%d entries)", cv.Entries)) - } + // Collect the sandbox audit trail even when the scan failed: those runs + // are the ones where it matters most. + if err := collectPostScanSecurityArtifacts(runDir, sandboxName, printer, progressVerbosity, scanErr, sandbox.Download); err != nil { + // Join the terminal outcome rather than return the scan failure + // alone. A run whose agent also failed keeps its agentFailedError, + // so the post-script gate still runs the post-script with + // FULLSEND_AGENT_EXIT_CODE set and the run error names both causes + // (#5705). + return postScanRunError(runTerminalError(h.ValidationLoop != nil, validationPassed, lastIterTimedOut, lastExitCode, agentExitReason, runCount, lastIterElapsed, timeout), err) } } @@ -4399,6 +4389,72 @@ func runTerminalError(hasLoop, validationPassed, timedOut bool, exitCode int, ex return nil } +// postScanRunError combines the run's own terminal outcome with the failure of +// the post-agent output scan and the sandbox audit collection. The scan failure +// must not replace an agent failure: the post-script gate keys off +// agentFailedError to run the post-script with FULLSEND_AGENT_EXIT_CODE set, and +// the run error has to name every cause (#5705). Each cause also stays +// identifiable, so postScriptGate can tell a scan-only failure, which may still +// post the result the scan left intact, from one joined with a timeout or a +// broken audit chain, which must skip. +func postScanRunError(terminalErr, artifactsErr error) error { + e := &postScanError{terminal: terminalErr} + var artifacts *postScanArtifactsError + if errors.As(artifactsErr, &artifacts) { + e.scan, e.chain = artifacts.scan, artifacts.chain + } else { + e.scan = artifactsErr + } + return e +} + +// postScanError is the run error once the post-agent scan has run. It keeps the +// run's terminal outcome, the output-scan failure and the audit-chain failure +// apart instead of flattening them into one join, because the post-script gate +// treats a scan-only failure differently from a run that also timed out or broke +// its audit chain (#5705). Every cause stays reachable through errors.As. +type postScanError struct { + terminal error + scan error + chain error +} + +func (e *postScanError) Error() string { + return errors.Join(e.terminal, e.scan, e.chain).Error() +} + +func (e *postScanError) Unwrap() []error { + errs := make([]error, 0, 3) + for _, err := range []error{e.terminal, e.scan, e.chain} { + if err != nil { + errs = append(errs, err) + } + } + return errs +} + +// postScanArtifactsError is what collectPostScanSecurityArtifacts returns: the +// output-scan failure and the audit-chain failure kept apart so postScanRunError +// can preserve the distinction (#5705). +type postScanArtifactsError struct { + scan error + chain error +} + +func (e *postScanArtifactsError) Error() string { + return errors.Join(e.scan, e.chain).Error() +} + +func (e *postScanArtifactsError) Unwrap() []error { + errs := make([]error, 0, 2) + for _, err := range []error{e.scan, e.chain} { + if err != nil { + errs = append(errs, err) + } + } + return errs +} + // agentFailedError ends a run without a validation_loop whose agent failed // (#8305). The post-script gate tells it apart from other run errors. type agentFailedError struct { @@ -4419,15 +4475,45 @@ type postScriptDecision struct { // postScriptGate decides whether the post-script runs once the agent is done. // With a validation_loop it needs a validated result (ADR 0022). Without one -// it runs after a successful agent, and after a failed agent only when the -// agent left a result file that parses (#8305), so the result is still -// reported while the run fails. --no-post-script is checked by the caller. +// it runs after a successful agent, after a failed agent only when the agent +// left a result file that parses (#8305), and after a failed output scan only +// when that scan is the run's only failure and it left a result file that +// parses, so the result is still reported while the run fails. --no-post-script +// is checked by the caller. func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverride bool, runErr error, outputDir string) postScriptDecision { if h.ValidationLoop != nil && !validationPassed { return postScriptDecision{message: "Skipping post-script: validation did not pass"} } + // A result file the scan could not write or sanitize is only still parseable + // because the quarantine could not replace it either: its bytes were never + // redacted, so posting it would publish them (#5705). This is checked before + // the agent-failure branch because a joined error can hold both causes, and + // that branch would otherwise post the file without ever consulting the scan + // failure. + var scanErr *outputScanError + scanFailed := errors.As(runErr, &scanErr) + if scanFailed { + if resultFile, ok := agentResultFile(h, outputDir); ok && scanErr.failedOn(resultFile) { + return postScriptDecision{message: "Skipping post-script: the output scan could not redact the result file"} + } + } + // A scan-only failure may still report the result it left intact, but a run + // that also timed out, broke its audit chain or reported a transcript error + // keeps that cause's outcome: the scan must not turn it into a post-script + // run (#5705). + scanOnly := scanFailed && scanOnlyRunError(runErr) var agentErr *agentFailedError if errors.As(runErr, &agentErr) { + if scanFailed && !scanOnly { + return postScriptDecision{message: "Skipping post-script: agent run failed"} + } + // A broken audit chain or any other terminal cause joined with the + // agent failure must skip the post-script even when the output scan was + // clean: on main that chain error was the run error by itself, so the + // result was never posted (#5705). + if postScanBlocksAgentFailure(runErr) { + return postScriptDecision{message: "Skipping post-script: agent run failed"} + } resultFile, ok := agentResultFile(h, outputDir) if !ok { return postScriptDecision{message: fmt.Sprintf("Skipping post-script: agent failed with exit code %d and left no result file that parses", agentErr.exitCode)} @@ -4438,6 +4524,21 @@ func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverrid agentExitCode: agentErr.exitCode, } } + // A scan failure fails the run, but one unreadable, unwritable or + // unsanitizable file anywhere under the run directory must not turn a + // completed report into silence: when the agent's own result file survived + // the scan and still parses, the post-script runs and the run still fails + // (#5705). + if scanOnly && !transcriptErrorOverride { + resultFile, ok := agentResultFile(h, outputDir) + if !ok { + return postScriptDecision{message: "Skipping post-script: the output scan failed and left no result file that parses"} + } + return postScriptDecision{ + run: true, + message: fmt.Sprintf("The output scan failed but left %s: running the post-script; the run still fails", filepath.Base(resultFile)), + } + } if runErr != nil { return postScriptDecision{message: "Skipping post-script: agent run failed"} } @@ -4447,6 +4548,54 @@ func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverrid return postScriptDecision{run: true} } +// postScanBlocksAgentFailure reports whether a post-scan run error carries, next +// to an agent failure, a cause that must skip the post-script: a broken audit +// chain or any terminal cause other than the agent failure itself. A scan-only +// post-scan error around the agent failure does not block; postScriptGate handles +// that case itself so the intact result is still reported (#5705). +func postScanBlocksAgentFailure(runErr error) bool { + var postScan *postScanError + if !errors.As(runErr, &postScan) { + return false + } + if postScan.chain != nil { + return true + } + if postScan.terminal == nil { + return false + } + var agentErr *agentFailedError + return !errors.As(postScan.terminal, &agentErr) +} + +// scanOnlyRunError reports whether the output scan is the run's only failure, or +// shares it with nothing worse than a failed agent, which the gate handles on its +// own. A timeout, a broken audit chain or any other joined cause makes a scan +// failure ineligible to run the post-script: on main a broken chain returned the +// chain error alone and skipped it (#5705). +func scanOnlyRunError(runErr error) bool { + var postScan *postScanError + if errors.As(runErr, &postScan) { + if postScan.chain != nil { + return false + } + if postScan.terminal == nil { + return true + } + var agentErr *agentFailedError + return errors.As(postScan.terminal, &agentErr) + } + // A run error that did not come through postScanRunError holds no separate + // causes to inspect, so it counts as scan-only only when it is a single + // error chain: a bare scan failure or one wrapped for the quiet wording. + var scanErr *outputScanError + if !errors.As(runErr, &scanErr) { + return false + } + _, joined := runErr.(interface{ Unwrap() []error }) + return !joined +} + // agentResultMaxBytes caps how much of the sandbox-written result file the // runner reads; a larger file counts as no result. const agentResultMaxBytes = 4 << 20 @@ -4476,6 +4625,15 @@ func agentResultFile(h *harness.Harness, outputDir string) (string, bool) { if json.Unmarshal(data, &obj) != nil || obj == nil { return "", false } + // A file the output scan replaced with a fail-closed marker is valid JSON + // but not the agent's result: posting it would report a marker as the + // review (#5705). + if _, removed := security.OutputRemoval(data); removed { + return "", false + } + if bytes.Equal(bytes.TrimSpace(data), []byte(unwritableOutputMarker)) { + return "", false + } return path, true } @@ -5263,6 +5421,30 @@ func auditChainFailure(brokenMsg, progressVerbosity string) (string, error) { // the quiet progress level. const quietRunErrorMessage = "agent run failed (error details are not printed at progress level quiet; see telemetry or the run artifact)" +// quietStatusDetailer lets an error state the fixed text the completion comment +// may carry for it at the quiet progress level, such as a count of affected +// files in place of their agent-chosen names. +type quietStatusDetailer interface { + QuietStatusDetail() string +} + +// failureStatusDetail returns the failure detail the completion comment posts +// for err. Actions log masking does not apply to that comment, so at quiet an +// error whose text can carry something the agent chose supplies a fixed wording +// through quietStatusDetailer. Every other error posts its message as before: +// ADR 0163 covers the job log only, and applying the level to the whole comment +// is tracked in #9627. The run error keeps the full text for telemetry and the +// root span at every level. +func failureStatusDetail(err error, progressVerbosity string) string { + if config.ProgressIsQuiet(progressVerbosity) { + var detailer quietStatusDetailer + if errors.As(err, &detailer) { + return detailer.QuietStatusDetail() + } + } + return err.Error() +} + // quietRunErr is the run's final error at quiet: it prints as // quietRunErrorMessage and keeps the original for errors.Is, errors.As and // the exit code. @@ -7257,6 +7439,19 @@ func printExtractedOutputFiles(printer *ui.Printer, extracted []string, elapsed // (ADR 0163) it prints counts only: file paths and finding details, which // can carry agent-chosen names and matched text, stay in findings.jsonl. func scanOutputFiles(outputDir, traceID, progressVerbosity string, printer *ui.Printer) error { + return scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity, printer, os.WriteFile, + security.SanitizeJSONDocument, security.SanitizeJSONLines) +} + +// sanitizeDocumentFn sanitizes one JSON document. It is injected as a parameter +// rather than read from a package global so tests can stub the decoder-limit +// failure without introducing mutable package state. +type sanitizeDocumentFn func([]byte, *security.Pipeline) ([]byte, []security.Finding, error) + +// sanitizeLinesFn sanitizes one JSONL stream record by record. +type sanitizeLinesFn func([]byte, *security.Pipeline) ([]byte, []security.Finding, error) + +func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, printer *ui.Printer, writeFile func(string, []byte, os.FileMode) error, sanitizeDocument sanitizeDocumentFn, sanitizeLines sanitizeLinesFn) error { quiet := config.ProgressIsQuiet(progressVerbosity) if _, err := os.Stat(outputDir); os.IsNotExist(err) { printer.StepInfo("No output files to scan") @@ -7265,13 +7460,24 @@ func scanOutputFiles(outputDir, traceID, progressVerbosity string, printer *ui.P pipeline := security.OutputPipeline() findingCount := 0 - // At quiet, unreadable and unwritable files are counted, not named. - unreadable, unwritable := 0, 0 + // At quiet, unreadable, unwritable and unsanitizable files are counted, not + // named, in the printed log. The collected failures still name each file and + // wrap its cause, so telemetry keeps the full text, and the returned error's + // QuietStatusDetail gives the completion comment the count (ADR 0163). + unreadable, unwritable, unsanitizable := 0, 0, 0 + // Write and sanitizer failures are collected rather than returned from the + // walk callback so every remaining file is still scanned and redacted. The + // run still fails closed once the walk finishes (#5705). + var writeErrs []error findingsPath := filepath.Join(outputDir, "security", "findings.jsonl") err := filepath.WalkDir(outputDir, func(path string, d os.DirEntry, err error) error { if err != nil { - return nil // skip unreadable entries + // An entry the walk cannot open is output that cannot be scanned: + // everything under it would reach the artifact unredacted. The walk + // continues and the run fails closed once it finishes (#5705). + writeErrs = append(writeErrs, walkFailure(outputDir, path, err, &unreadable)) + return nil } if d.IsDir() { // Skip the security findings directory itself. @@ -7297,21 +7503,88 @@ func scanOutputFiles(outputDir, traceID, progressVerbosity string, printer *ui.P return nil } content, readErr := os.ReadFile(path) + relPath, _ := filepath.Rel(outputDir, path) if readErr != nil { - if quiet { - unreadable++ + // A file that cannot be read cannot be scanned, so its bytes would + // reach the artifact unredacted. It is contained like a write + // failure and the run fails closed (#5705). + writeErrs = append(writeErrs, readFailure(path, relPath, readErr, &unreadable)) + return nil + } + ext := strings.ToLower(filepath.Ext(path)) + + // JSONL and NDJSON are sanitized record by record so one record never + // rewrites another (#5705). Multi-document streams in files with other + // extensions (such as a .json file holding multiple records) are also + // recognized by content and handled per record rather than falling + // through to the plain-text scan. + isLines := ext == ".jsonl" || ext == ".ndjson" || (!security.IsJSONDocument(content) && security.IsJSONLines(content)) + if isLines { + out, jsonLineFindings, scanErr := sanitizeLines(content, pipeline) + if scanErr != nil { + writeErrs = append(writeErrs, sanitizeFailure(path, relPath, scanErr, &unsanitizable)) return nil } - relPath, _ := filepath.Rel(outputDir, path) - printer.StepWarn(fmt.Sprintf("Could not read %s: %v", relPath, readErr)) + // A record that was replaced with a marker is not a whole-file + // marker, so this is the only place its loss reaches an operator. + // The alert is gated on findings so a clean file that already + // contains a marker-equal line (a re-scanned artifact, a fixture, + // or a line the agent wrote on purpose) does not raise a false + // error when this pass removed nothing. + if len(jsonLineFindings) > 0 || !bytes.Equal(out, content) { + alertOnRecordRemoval(printer, out) + findingCount += len(jsonLineFindings) + for _, f := range jsonLineFindings { + if !quiet { + printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s: %s", f.Name, relPath, f.Detail)) + } + security.AppendFinding(findingsPath, security.TracedFinding{ + TraceID: traceID, Timestamp: time.Now().UTC().Format(time.RFC3339), + Phase: "host_output", Finding: f, + }) + } + if writeErr := writeFile(path, out, 0o644); writeErr != nil { + writeErrs = append(writeErrs, writeFailure(path, relPath, writeErr, &unwritable)) + } + } return nil } + // Structurally sanitize valid JSON so redaction never breaks JSON + // syntax and fails closed (#5705). The test tolerates a leading UTF-8 + // BOM, so a document that carries one is not left to the text scan, + // where a redaction could still break its syntax. Non-JSON files fall + // through to the plain text scan below. + if security.IsJSONDocument(content) { + out, jsonFindings, jsonErr := sanitizeDocument(content, pipeline) + if jsonErr != nil { + writeErrs = append(writeErrs, sanitizeFailure(path, relPath, jsonErr, &unsanitizable)) + return nil + } + if len(jsonFindings) > 0 || !bytes.Equal(out, content) { + findingCount += len(jsonFindings) + for _, f := range jsonFindings { + if !quiet { + printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s: %s", f.Name, relPath, f.Detail)) + } + security.AppendFinding(findingsPath, security.TracedFinding{ + TraceID: traceID, Timestamp: time.Now().UTC().Format(time.RFC3339), + Phase: "host_output", Finding: f, + }) + } + alertOnOutputRemoval(printer, out) + if writeErr := writeFile(path, out, 0o644); writeErr != nil { + writeErrs = append(writeErrs, writeFailure(path, relPath, writeErr, &unwritable)) + } + } + return nil + } + + // Non-JSON files: run plain text pipeline scan. text := string(content) result := pipeline.Scan(text) if len(result.Findings) > 0 { findingCount += len(result.Findings) - relPath, _ := filepath.Rel(outputDir, path) for _, f := range result.Findings { if !quiet { printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s: %s", f.Name, relPath, f.Detail)) @@ -7325,13 +7598,13 @@ func scanOutputFiles(outputDir, traceID, progressVerbosity string, printer *ui.P }) } // Sanitized may be empty when all content was invisible characters. + // Nothing here writes a fail-closed marker: a document that parsed + // as JSON took the structural path above, so this text scan cannot + // turn valid JSON into invalid JSON, and the alert has nothing to + // report. out := result.Sanitized - if writeErr := os.WriteFile(path, []byte(out), 0o644); writeErr != nil { - if quiet { - unwritable++ - } else { - printer.StepWarn(fmt.Sprintf("Could not write sanitized %s: %v", relPath, writeErr)) - } + if writeErr := writeFile(path, []byte(out), 0o644); writeErr != nil { + writeErrs = append(writeErrs, writeFailure(path, relPath, writeErr, &unwritable)) } } return nil @@ -7346,15 +7619,251 @@ func scanOutputFiles(outputDir, traceID, progressVerbosity string, printer *ui.P if unwritable > 0 { printer.StepWarn(fmt.Sprintf("Could not write %d sanitized output file(s)", unwritable)) } + if unsanitizable > 0 { + printer.StepWarn(fmt.Sprintf("Could not sanitize %d output file(s)", unsanitizable)) + } if findingCount > 0 { printer.StepWarn(fmt.Sprintf("Sanitized %d finding(s) in output files", findingCount)) } else { printer.StepDone("Output files clean — no issues found") } + if err := errors.Join(writeErrs...); err != nil { + return &outputScanError{ + err: err, + files: unreadable + unwritable + unsanitizable, + failed: failedOutputPaths(writeErrs), + } + } return nil } -// injectTraceID appends the FULLSEND_TRACE_ID to the sandbox .env file. +// failedOutputPaths collects the paths of the output files the scan could not +// handle. The gate needs them to tell a result file that survived the scan from +// one the scan failed on, and the paths stay internal: they name agent-chosen +// files, so they never reach a printed line (ADR 0163). +func failedOutputPaths(errs []error) []string { + var paths []string + for _, err := range errs { + var failure *outputFileFailure + if errors.As(err, &failure) { + paths = append(paths, failure.path) + } + } + return paths +} + +// outputFileFailure records one output file the scan could not read, sanitize or +// write, with the path it could not handle. The path is not part of the message +// the quiet level prints; it is kept so the post-script gate can refuse to post a +// result file this scan could not redact (#5705). +type outputFileFailure struct { + path string + err error +} + +func (e *outputFileFailure) Error() string { return e.err.Error() } +func (e *outputFileFailure) Unwrap() error { return e.err } + +// postAgentScanFailurePrefix labels a failed post-agent output scan in the run +// error and in the fixed text the completion comment carries at quiet. +const postAgentScanFailurePrefix = "post-agent output scan failed" + +// outputScanError is the run error for a post-agent output scan that could not +// handle some output files. Its message names each file and wraps the cause, so +// telemetry and the root span keep the detail (ADR 0163). At the quiet progress +// level the completion comment gets QuietStatusDetail instead: an output file +// name is the agent's to choose, and the comment is posted where anyone who can +// see the issue or pull request reads it (#5705). +type outputScanError struct { + err error + files int + // failed holds the paths of the output files the scan could not handle. The + // post-script gate uses it to tell a result file that survived the scan from + // one whose write or sanitization failed, which can still parse when the + // quarantine could not replace it (#5705). Like every other path here it is + // internal: never printed, never posted. + failed []string +} + +func (e *outputScanError) Error() string { return e.err.Error() } +func (e *outputScanError) Unwrap() error { return e.err } + +// failedOn reports whether the scan could not handle path, or any directory that +// contains it, so the bytes at path were never guaranteed redacted. +func (e *outputScanError) failedOn(path string) bool { + for _, failed := range e.failed { + if failed == path { + return true + } + // A directory the walk could not open was never scanned, and neither was + // anything under it. + if strings.HasPrefix(path, failed+string(os.PathSeparator)) { + return true + } + } + return false +} + +// QuietStatusDetail is the fixed text the completion comment carries at quiet: +// how many output files the scan could not handle, never a name or a cause. +func (e *outputScanError) QuietStatusDetail() string { + return fmt.Sprintf("%s: %d file(s) could not be scanned", postAgentScanFailurePrefix, e.files) +} + +// alertOnOutputRemoval emits a ::error:: workflow command when an output file +// was replaced whole by a fail-closed marker. Everything the agent wrote into +// that file is gone, and a lost review that only shows up as one scan line is +// the silent failure #5705 set out to fix. GitHub Actions renders the command as +// an error annotation; Forgejo Actions sets GITHUB_ACTIONS too but prints the +// line in the step log, since it has no annotation view. Only the marker's fixed +// reason reaches the line: a file path or a matched value could carry +// agent-chosen text (ADR 0163). +func alertOnOutputRemoval(printer *ui.Printer, sanitized []byte) { + reason, removed := security.OutputRemoval(sanitized) + if !removed || os.Getenv("GITHUB_ACTIONS") != "true" { + return + } + printer.Raw("::error::Output file replaced with a fail-closed marker: " + reason + "\n") +} + +// alertOnRecordRemoval emits a ::error:: workflow command for each distinct +// reason a JSONL record was replaced with a fail-closed marker. Such a file +// keeps its records, so it is never a whole-file marker, and the record's loss +// would otherwise show up only as one scan line — the silent failure #5705 set +// out to fix. GitHub Actions renders the command as an annotation; Forgejo +// prints it in the step log. Only the marker's fixed reason reaches the line, +// never a path or a matched value (ADR 0163). +func alertOnRecordRemoval(printer *ui.Printer, sanitized []byte) { + if os.Getenv("GITHUB_ACTIONS") != "true" { + return + } + for _, reason := range security.OutputRecordRemovals(sanitized) { + printer.Raw("::error::Output record replaced with a fail-closed marker: " + reason + "\n") + } +} + +// writeFailure records a sanitized-output write error. The returned error always +// names the file and wraps the cause, whatever the progress level: only printed +// lines are trimmed at quiet (the count warnings below, failureLine and +// quietRunError), while the run error recorded by telemetry keeps the full text. +// The completion comment posts a count instead of the agent-chosen name at quiet +// (failureStatusDetail, ADR 0163). +func writeFailure(path, relPath string, writeErr error, unwritable *int) error { + *unwritable = *unwritable + 1 + quarantineErr := quarantineOutput(path) + return &outputFileFailure{path: path, err: errors.Join( + fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr), quarantineErr)} +} + +// readFailure records an output file that could not be read. Its bytes cannot be +// scanned, so it is contained like a write failure: the file is replaced with a +// marker, or removed, when the filesystem allows it, and the run fails closed +// afterwards (#5705). Like every failure here, the error names the file at every +// progress level; only the printed line is trimmed at quiet, and the completion +// comment gets a count (failureStatusDetail, ADR 0163). +func readFailure(path, relPath string, readErr error, unreadable *int) error { + *unreadable = *unreadable + 1 + quarantineErr := quarantineOutput(path) + return &outputFileFailure{path: path, err: errors.Join( + fmt.Errorf("could not read %s: %w", relPath, readErr), quarantineErr)} +} + +// walkFailure records an entry the walk could not open. Nothing under it was +// scanned, so the run fails closed instead of shipping those bytes as an +// artifact (#5705). The entry is not quarantined: it may be a directory, and the +// files it holds were never opened. The path stays in the error at every +// progress level; only the printed line is trimmed at quiet, and the completion +// comment gets a count (failureStatusDetail, ADR 0163). +func walkFailure(outputDir, path string, walkErr error, unreadable *int) error { + *unreadable = *unreadable + 1 + relPath, err := filepath.Rel(outputDir, path) + if err != nil { + relPath = path + } + return &outputFileFailure{path: path, err: fmt.Errorf("could not read %s: %w", relPath, walkErr)} +} + +// sanitizeFailure records a sanitization error and contains the file it could +// not sanitize, so the walk continues to the remaining files instead of leaving +// them unredacted. The unredacted bytes are replaced with the marker when the +// filesystem allows it, as on a write failure (#5705). The error names the file +// and wraps the cause at every progress level; the completion comment gets a +// count at quiet (failureStatusDetail, ADR 0163). +func sanitizeFailure(path, relPath string, scanErr error, unsanitizable *int) error { + *unsanitizable = *unsanitizable + 1 + quarantineErr := quarantineOutput(path) + return &outputFileFailure{path: path, err: errors.Join( + fmt.Errorf("could not sanitize %s: %w", relPath, scanErr), quarantineErr)} +} + +// quarantineOutput replaces path with the fail-closed marker, removing it if even +// that write fails, so unredacted bytes do not reach the uploaded artifact. When +// neither works — a read-only directory is the common case — the original file is +// still on disk, and the returned error says so instead of leaving the failed +// quarantine unreported while the run's failure looks like a plain write error. +func quarantineOutput(path string) error { + if err := os.WriteFile(path, []byte(unwritableOutputMarker), 0o644); err == nil { + return nil + } + if err := os.Remove(path); err != nil { + // No path reaches the message: the file name can be agent-chosen + // (ADR 0163), and the caller already names it when it is safe to. + return errors.New("unredacted output file could not be replaced or removed") + } + return nil +} + +// unwritableOutputMarker replaces a file whose sanitized content could not be +// computed or written. It is valid JSON so downstream parsers keep working. +const unwritableOutputMarker = security.FailClosedUnwritableJSON + +// downloadFindingsFn extracts the sandbox-side findings directory. It is a +// parameter of collectPostScanSecurityArtifacts rather than a package global so +// tests can observe the ordering contract without a sandbox and without mutable +// package state. +type downloadFindingsFn func(sandboxName, remoteDir, localDir string) error + +// collectPostScanSecurityArtifacts extracts the sandbox-side security findings +// and verifies the audit hash chain. scanErr is the outcome of the host output +// scan; it is returned after the audit trail has been collected, so a failed +// scan never skips the artifacts that explain the failure. +func collectPostScanSecurityArtifacts(runDir, sandboxName string, printer *ui.Printer, progressVerbosity string, scanErr error, downloadFindings downloadFindingsFn) error { + findingsDir := filepath.Join(runDir, "security") + if err := os.MkdirAll(findingsDir, 0o755); err == nil { + remoteFindingsDir := sandbox.SandboxWorkspace + "/.security/" + if dlErr := downloadFindings(sandboxName, remoteFindingsDir, findingsDir); dlErr != nil { + printer.StepInfo("No sandbox security findings to extract") + } else { + printer.StepDone("Security findings extracted") + } + } + var chainErr error + findingsJSONL := filepath.Join(runDir, "security", "findings.jsonl") + if _, statErr := os.Stat(findingsJSONL); statErr == nil { + cv, verifyErr := security.VerifyChain(findingsJSONL) + switch { + case verifyErr != nil: + printer.StepWarn(failureLine("Audit log verification error", verifyErr, progressVerbosity)) + case !cv.Valid: + line, err := auditChainFailure(cv.BrokenMsg, progressVerbosity) + printer.StepFail(line) + chainErr = err + case cv.Entries > 0: + printer.StepDone(fmt.Sprintf("Audit log integrity verified (%d entries)", cv.Entries)) + } + } + if scanErr != nil { + // The wrap keeps a scan error's own fixed quiet wording reachable + // through errors.As, so the completion comment can post a count instead + // of the agent-chosen file names (outputScanError, ADR 0163). + scanErr = fmt.Errorf("%s: %w", postAgentScanFailurePrefix, scanErr) + } + if scanErr == nil && chainErr == nil { + return nil + } + return &postScanArtifactsError{scan: scanErr, chain: chainErr} +} + func injectTraceID(sandboxName, traceID string) error { if !security.IsShellSafeTraceID(traceID) { return fmt.Errorf("invalid trace ID format: %q", traceID) diff --git a/internal/cli/run_postscan_test.go b/internal/cli/run_postscan_test.go new file mode 100644 index 0000000000..929d79d495 --- /dev/null +++ b/internal/cli/run_postscan_test.go @@ -0,0 +1,132 @@ +package cli + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/security" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// TestCollectPostScanSecurityArtifactsRunsOnScanFailure pins that a failed host +// output scan still extracts the sandbox audit trail and still reports the scan +// failure. +func TestCollectPostScanSecurityArtifactsRunsOnScanFailure(t *testing.T) { + runDir := t.TempDir() + var downloaded bool + download := func(_, _, _ string) error { + downloaded = true + return nil + } + + var buf bytes.Buffer + scanErr := errors.New("could not write sanitized output file") + err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), "", scanErr, download) + + require.Error(t, err) + assert.True(t, downloaded, "sandbox findings must be extracted even when the scan failed") + assert.Contains(t, err.Error(), "post-agent output scan failed") + assert.Contains(t, buf.String(), "Security findings extracted") +} + +// TestCollectPostScanSecurityArtifactsKeepsQuietStatusDetail pins that the wrap +// collectPostScanSecurityArtifacts adds around the scan error keeps the scan's +// fixed quiet wording reachable, so the completion comment can post a count of +// files instead of the agent-chosen names (ADR 0163). +func TestCollectPostScanSecurityArtifactsKeepsQuietStatusDetail(t *testing.T) { + runDir := t.TempDir() + download := func(_, _, _ string) error { return errors.New("no findings") } + + const name = "@org/team-secret.json" + scanErr := &outputScanError{err: fmt.Errorf("could not read %s: denied", name), files: 1} + var buf bytes.Buffer + err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), config.ProgressVerbosityQuiet, scanErr, download) + + require.Error(t, err) + assert.Contains(t, err.Error(), name, "the run error keeps the path for telemetry") + assert.Equal(t, "post-agent output scan failed: 1 file(s) could not be scanned", + failureStatusDetail(err, config.ProgressVerbosityQuiet)) + assert.Contains(t, failureStatusDetail(err, ""), name, "full posts the error as before") +} + +// TestCollectPostScanSecurityArtifactsAuditChainBranches pins the three branches +// behind the findings.jsonl guard: a valid chain is reported as verified, a +// tampered chain fails the run through chainErr, and a verification error is only +// a warning. The earlier tests use an empty run directory, so os.Stat fails and +// none of these branches runs — a regression that dropped chainErr would pass. +func TestCollectPostScanSecurityArtifactsAuditChainBranches(t *testing.T) { + download := func(_, _, _ string) error { return errors.New("no sandbox findings") } + + t.Run("valid chain is verified", func(t *testing.T) { + runDir := t.TempDir() + writeAuditChain(t, runDir, false) + + var buf bytes.Buffer + err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), "", nil, download) + require.NoError(t, err) + assert.Contains(t, buf.String(), "Audit log integrity verified (2 entries)") + }) + + t.Run("tampered chain fails the run", func(t *testing.T) { + runDir := t.TempDir() + writeAuditChain(t, runDir, true) + + var buf bytes.Buffer + err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), "", nil, download) + require.Error(t, err, "a tampered chain must reach the run error") + assert.Contains(t, err.Error(), "audit log integrity check failed") + assert.Contains(t, buf.String(), "Audit log integrity check FAILED") + }) + + t.Run("verification error is a warning only", func(t *testing.T) { + runDir := t.TempDir() + // A findings file that is a directory makes VerifyChain fail to open it, + // which the collector reports as a warning rather than a run failure. + require.NoError(t, os.MkdirAll(filepath.Join(runDir, "security", "findings.jsonl"), 0o755)) + + var buf bytes.Buffer + err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), "", nil, download) + require.NoError(t, err, "a verification error must not fail the run") + assert.Contains(t, buf.String(), "Audit log verification error") + }) +} + +// writeAuditChain stages runDir/security/findings.jsonl. With tamper set, the +// last record's detail is changed after the chain is written, so VerifyChain +// reports a hash mismatch. +func writeAuditChain(t *testing.T, runDir string, tamper bool) { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Join(runDir, "security"), 0o755)) + path := filepath.Join(runDir, "security", "findings.jsonl") + for _, detail := range []string{"first", "second"} { + require.NoError(t, security.AppendFinding(path, security.TracedFinding{ + TraceID: "trace-id", + Phase: "host_output", + Finding: security.Finding{Scanner: "secret_redactor", Name: "test", Severity: "low", Detail: detail}, + })) + } + if !tamper { + return + } + raw, err := os.ReadFile(path) + require.NoError(t, err) + lines := strings.Split(strings.TrimSuffix(string(raw), "\n"), "\n") + require.Len(t, lines, 2) + var entry security.TracedFinding + require.NoError(t, json.Unmarshal([]byte(lines[1]), &entry)) + entry.Detail = "TAMPERED" + newLine, err := json.Marshal(entry) + require.NoError(t, err) + lines[1] = string(newLine) + require.NoError(t, os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600)) +} diff --git a/internal/cli/run_progress_test.go b/internal/cli/run_progress_test.go index d3c436e8a5..e0d466e18a 100644 --- a/internal/cli/run_progress_test.go +++ b/internal/cli/run_progress_test.go @@ -286,6 +286,30 @@ func TestFailureLine(t *testing.T) { } } +// At quiet the completion comment must not carry text the agent can write, such +// as an output file name, so an error that quotes one supplies a fixed wording. +// Every other error posts its message as before (ADR 0163 covers the job log +// only; applying it to the whole comment is #9627), and the run error keeps the +// full text either way. +func TestFailureStatusDetail(t *testing.T) { + const agentName = "SECRET-NAME.json" + scanErr := &outputScanError{err: fmt.Errorf("could not read %s: denied", agentName), files: 2} + for _, level := range []string{"", config.ProgressVerbosityFull, config.ProgressVerbosityTools} { + assert.Equal(t, "could not read SECRET-NAME.json: denied", failureStatusDetail(scanErr, level), + "level %q posts the error as before", level) + } + for _, level := range []string{config.ProgressVerbosityQuiet, "bogus"} { + assert.Equal(t, "post-agent output scan failed: 2 file(s) could not be scanned", + failureStatusDetail(scanErr, level)) + } + + plain := fmt.Errorf("could not copy %s", agentName) + for _, level := range []string{"", config.ProgressVerbosityFull, config.ProgressVerbosityTools, config.ProgressVerbosityQuiet} { + assert.Equal(t, "could not copy SECRET-NAME.json", failureStatusDetail(plain, level), + "an error with no fixed wording posts its message as before") + } +} + func TestAuditChainFailure(t *testing.T) { const broken = "entry 2: hash mismatch: expected abc, got SECRET-HASH" for _, level := range []string{"", config.ProgressVerbosityFull, config.ProgressVerbosityTools} { diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index 991ac0df9c..c0be68e32f 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -5,6 +5,7 @@ import ( "context" "debug/elf" "encoding/json" + "errors" "fmt" "io" "net" @@ -5567,6 +5568,180 @@ func TestPostScriptGate(t *testing.T) { got := postScriptGate(noLoop, false, false, timedOut, writeResult(t, "agent-result.json", `{}`)) assert.False(t, got.run) }) + t.Run("no loop, output scan failed, valid result", func(t *testing.T) { + t.Parallel() + // collectPostScanSecurityArtifacts wraps the scan error, so the gate + // must find it through the wrap and the post-scan join. + scanErr := &outputScanError{err: errors.New("could not write sanitized notes.md: no space left on device"), files: 1} + var buf bytes.Buffer + artifactsErr := collectPostScanSecurityArtifacts(t.TempDir(), "sandbox", ui.New(&buf), "", + scanErr, func(_, _, _ string) error { return errors.New("no findings") }) + runErr := postScanRunError(nil, artifactsErr) + got := postScriptGate(noLoop, false, false, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.True(t, got.run, "an intact result must still be posted when the scan is the only failure") + assert.Zero(t, got.agentExitCode) + assert.Contains(t, got.message, "agent-result.json") + assert.Contains(t, got.message, "the run still fails") + }) + t.Run("no loop, output scan and audit chain both failed", func(t *testing.T) { + t.Parallel() + // A broken chain skipped the post-script on main; a scan failure joined + // with it must not turn that into a posted result (#5705). + scanErr := fmt.Errorf("%s: %w", postAgentScanFailurePrefix, + &outputScanError{err: errors.New("could not write sanitized notes.md"), files: 1}) + runErr := postScanRunError(nil, &postScanArtifactsError{ + scan: scanErr, + chain: errors.New("audit log integrity check failed: hash mismatch"), + }) + got := postScriptGate(noLoop, false, false, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.False(t, got.run, "a broken audit chain must still skip the post-script") + assert.Contains(t, got.message, "agent run failed") + }) + t.Run("no loop, timeout and scan failed", func(t *testing.T) { + t.Parallel() + // A timeout alone skips with "agent run failed"; the scan must not + // override it just because an intact result file exists (#5705). + timedOut := runTerminalError(false, false, true, -1, "", 1, time.Hour, time.Hour) + scanErr := fmt.Errorf("%s: %w", postAgentScanFailurePrefix, + &outputScanError{err: errors.New("could not read notes.md"), files: 1}) + runErr := postScanRunError(timedOut, &postScanArtifactsError{scan: scanErr}) + got := postScriptGate(noLoop, false, false, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.False(t, got.run) + assert.Contains(t, got.message, "agent run failed") + }) + t.Run("no loop, transcript error override and scan failed", func(t *testing.T) { + t.Parallel() + // The transcript override alone skips the post-script; a scan failure + // joined with it must not post the result anyway (#5705). + scanErr := fmt.Errorf("%s: %w", postAgentScanFailurePrefix, + &outputScanError{err: errors.New("could not read notes.md"), files: 1}) + runErr := postScanRunError(nil, &postScanArtifactsError{scan: scanErr}) + got := postScriptGate(noLoop, false, true, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.False(t, got.run) + }) + t.Run("no loop, failed agent and broken audit chain", func(t *testing.T) { + t.Parallel() + // The agent-failure branch reports a result, but a joined chain failure + // still skips it the way it did on main (#5705). + scanErr := fmt.Errorf("%s: %w", postAgentScanFailurePrefix, + &outputScanError{err: errors.New("could not read notes.md"), files: 1}) + runErr := postScanRunError(agentFailed, &postScanArtifactsError{ + scan: scanErr, + chain: errors.New("audit log integrity check failed: hash mismatch"), + }) + got := postScriptGate(noLoop, false, false, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.False(t, got.run) + assert.Contains(t, got.message, "agent run failed") + }) + t.Run("no loop, failed agent and broken audit chain without a scan failure", func(t *testing.T) { + t.Parallel() + // The scan succeeded but the audit chain is broken. On main the chain + // error alone was the run error and skipped the post-script; the + // agent-failure branch must not post the result just because + // agent-result.json parses (#5705). + runErr := postScanRunError(agentFailed, &postScanArtifactsError{ + chain: errors.New("audit log integrity check failed: hash mismatch"), + }) + got := postScriptGate(noLoop, false, false, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.False(t, got.run, "a broken audit chain must skip the post-script even without a scan failure") + assert.Contains(t, got.message, "agent run failed") + }) + t.Run("no loop, output scan failed, no result", func(t *testing.T) { + t.Parallel() + got := postScriptGate(noLoop, false, false, &outputScanError{err: errors.New("could not read notes.md"), files: 1}, t.TempDir()) + assert.False(t, got.run) + assert.Contains(t, got.message, "left no result file that parses") + }) + t.Run("no loop, output scan quarantined the result", func(t *testing.T) { + t.Parallel() + // The quarantine marker is valid JSON, so it would otherwise pass for a + // result and be posted as the review. + for _, marker := range []string{ + unwritableOutputMarker, + `{"error":"output removed because redaction would invalidate JSON"}`, + `{"error":"output removed because a private key block spans JSON framing"}`, + } { + dir := writeResult(t, "agent-result.json", marker) + got := postScriptGate(noLoop, false, false, &outputScanError{err: errors.New("could not sanitize agent-result.json"), files: 1}, dir) + assert.False(t, got.run, marker) + assert.Contains(t, got.message, "left no result file that parses", marker) + } + }) + t.Run("no loop, output scan could not redact the result", func(t *testing.T) { + t.Parallel() + // The scan's write or sanitize failed *and* the quarantine could not + // replace the file, so the unredacted bytes are still on disk and still + // parse. Posting them would publish exactly what the scan failed to redact. + for _, unredacted := range []string{ + `{"action":"approve","body":"token ghp_FAKEtesttoken000000000000000000000000"}`, + `{"action":"approve","body":"secret"}`, + } { + dir := writeResult(t, "agent-result.json", unredacted) + resultPath := filepath.Join(dir, "agent-result.json") + scanErr := &outputScanError{ + err: errors.New("could not write sanitized agent-result.json: no space left on device"), + files: 1, + failed: []string{resultPath}, + } + got := postScriptGate(noLoop, false, false, scanErr, dir) + assert.False(t, got.run, "a result file the scan could not redact must not be posted") + assert.Contains(t, got.message, "could not redact the result file") + + // A failure on a directory above the result file hides it the same + // way: the walk never scanned what is under it. + parent := &outputScanError{err: errors.New("could not read iteration-1"), files: 1, failed: []string{dir}} + assert.False(t, postScriptGate(noLoop, false, false, parent, dir).run) + } + }) + t.Run("no loop, failed agent and failed scan, valid result", func(t *testing.T) { + t.Parallel() + // Step 9f joins the terminal error with the scan error, so an agent that + // also failed keeps its agentFailedError through the join. + scanErr := &outputScanError{err: errors.New("could not write sanitized notes.md: no space left on device"), files: 1} + runErr := postScanRunError(agentFailed, fmt.Errorf("%s: %w", postAgentScanFailurePrefix, scanErr)) + var agentErr *agentFailedError + var scanAsErr *outputScanError + require.ErrorAs(t, runErr, &agentErr, "the agent failure must survive the join") + require.ErrorAs(t, runErr, &scanAsErr, "the scan failure must survive the join") + assert.Contains(t, runErr.Error(), "agent failed with exit code 1") + assert.Contains(t, runErr.Error(), "post-agent output scan failed") + + got := postScriptGate(noLoop, false, false, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.True(t, got.run, "an intact result is still posted") + assert.Equal(t, 1, got.agentExitCode, + "the post-script runs with FULLSEND_AGENT_EXIT_CODE after an agent failure") + }) + t.Run("no loop, failed agent and failed scan that could not redact the result", func(t *testing.T) { + t.Parallel() + // The agent-failure branch must not bypass the scan's failedOn check: a + // joined error holds both causes, and the result file whose redaction + // failed (and whose quarantine could not replace it) is still unredacted. + dir := writeResult(t, "agent-result.json", `{"action":"approve","body":"token ghp_FAKEtesttoken000000000000000000000000"}`) + resultPath := filepath.Join(dir, "agent-result.json") + scanErr := &outputScanError{ + err: errors.New("could not write sanitized agent-result.json: no space left on device"), + files: 1, + failed: []string{resultPath}, + } + runErr := postScanRunError(agentFailed, fmt.Errorf("%s: %w", postAgentScanFailurePrefix, scanErr)) + + got := postScriptGate(noLoop, false, false, runErr, dir) + assert.False(t, got.run, "a joined agent+scan failure must still refuse the unredacted result") + assert.Contains(t, got.message, "could not redact the result file") + }) + t.Run("no loop, failed agent, quarantined result", func(t *testing.T) { + t.Parallel() + dir := writeResult(t, "agent-result.json", unwritableOutputMarker) + assert.False(t, postScriptGate(noLoop, false, false, agentFailed, dir).run, + "a marker must never be posted as the agent's result") + }) + t.Run("loop, output scan failed with a result present", func(t *testing.T) { + t.Parallel() + got := postScriptGate(withLoop, false, false, &outputScanError{err: errors.New("could not read notes.md"), files: 1}, + writeResult(t, "agent-result.json", `{}`)) + assert.False(t, got.run, "ADR 0022 still requires a validated result") + assert.Equal(t, "Skipping post-script: validation did not pass", got.message) + }) t.Run("loop, validation passed", func(t *testing.T) { t.Parallel() assert.True(t, postScriptGate(withLoop, true, false, nil, t.TempDir()).run) diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 608485e85f..d41e9dbec6 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -2,18 +2,40 @@ package cli import ( "bytes" + "encoding/json" + "errors" + "fmt" "os" + "os/exec" "path/filepath" + "sort" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/fullsend-ai/fullsend/internal/security" "github.com/fullsend-ai/fullsend/internal/telemetry" "github.com/fullsend-ai/fullsend/internal/ui" ) +// pemBegin and pemEnd are the private-key markers used by the fixtures. They are +// split at definition so a source scan does not read this as key material, and +// defined once so every fixture is testing the same marker shape. +var ( + pemBegin = "-----BEGIN RSA" + " PRIVATE KEY-----" + pemEnd = "-----END RSA" + " PRIVATE KEY-----" +) + +// scanOutputFilesWithDefaults is the scanOutputFilesWithWriter call most tests +// want: real structural sanitizers and an injected writer. It keeps the +// injection seam a parameter rather than a mutable package global. +func scanOutputFilesWithDefaults(outputDir, traceID, progressVerbosity string, printer *ui.Printer, writeFile func(string, []byte, os.FileMode) error) error { + return scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity, printer, writeFile, + security.SanitizeJSONDocument, security.SanitizeJSONLines) +} + // TestScanOutputFiles_SkipsTelemetryArtifacts pins that the host-side output // redaction scan does NOT rewrite the telemetry JSONL file. It is still held // open for append during the scan, so an in-place rewrite would truncate it @@ -81,3 +103,830 @@ func TestScanOutputFiles_SkipsStagedSkillsAndPersonaManifest(t *testing.T) { assert.NotEqual(t, secret, string(got), p) } } + +// TestScanOutputFiles_PreservesJSONStructuralValidity pins that if an output +// file was valid JSON before sanitization, scanOutputFiles structurally sanitizes +// string leaves so that the file on disk remains structurally valid JSON and +// secrets are completely redacted (fail-closed, #5705). +func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { + dir := t.TempDir() + + // Case 1: Standard secret token in string field. + jsonFile1 := filepath.Join(dir, "agent-result.json") + validJSON1 := `{"action":"comment","body":"Token: ghp_FAKEtesttoken000000000000000000000000\n"}` + require.NoError(t, os.WriteFile(jsonFile1, []byte(validJSON1), 0o644)) + + // Case 2: json_field with an embedded escaped quote and secret. + jsonFile2 := filepath.Join(dir, "escaped.json") + validJSON2 := `{"findings":[{"password":"secret_password_1234\"rest"}]}` + require.NoError(t, os.WriteFile(jsonFile2, []byte(validJSON2), 0o644)) + + // Case 3: A secret containing a backslash / newline split. + jsonFile3 := filepath.Join(dir, "split.json") + validJSON3 := `{"auth":"Authorization: Bearer abc\ndefghijkl1234"}` + require.NoError(t, os.WriteFile(jsonFile3, []byte(validJSON3), 0o644)) + + // Case 4: Secret token in object key, large integers (> 2^53), float precision, and HTML characters. + jsonFile4 := filepath.Join(dir, "key_and_numbers.json") + validJSON4 := `{"ghp_FAKEtesttoken000000000000000000000000": 12345678901234567891, "ratio": 1.0, "html": "&val"}` + require.NoError(t, os.WriteFile(jsonFile4, []byte(validJSON4), 0o644)) + + // Case 5: Slices containing string secrets and colliding keys. + jsonFile5 := filepath.Join(dir, "slice_and_collision.json") + validJSON5 := `{"tokens":["ghp_FAKEtesttoken000000000000000000000001"],"ghp_FAKEtesttoken000000000000000000000002":1,"ghp_FAKEtesttoken000000000000000000000003":2}` + require.NoError(t, os.WriteFile(jsonFile5, []byte(validJSON5), 0o644)) + + // Structural findings plus a private-key marker spanning separate values + // must still be written as valid JSON, with the masked members carrying + // neither marker. + jsonFile8 := filepath.Join(dir, "private_key_and_password.json") + validJSON8 := `["see -----BEGIN RSA` + ` PRIVATE KEY----- marker", {"note": "and -----END RSA` + ` PRIVATE KEY----- marker", "password": "a-long-sensitive-value"}]` + require.NoError(t, os.WriteFile(jsonFile8, []byte(validJSON8), 0o644)) + + // Regression for #5705: an env assignment mentioned in ordinary prose is + // redacted structurally without corrupting JSON syntax. + jsonFile6 := filepath.Join(dir, "scribe_secret_backend.json") + validJSON6 := `{"body":"Changed SCRIBE_SECRET_BACKEND=environment_backend"}` + require.NoError(t, os.WriteFile(jsonFile6, []byte(validJSON6), 0o644)) + + // The private-key pattern can match across separate JSON string values in + // raw text, even though neither value contains a complete key block. + // Structural scanning must not let such a cross-value match corrupt JSON, + // and must mask only the members it covers rather than drop the document. + jsonFile7 := filepath.Join(dir, "private_key_markers.json") + validJSON7 := `["see -----BEGIN RSA` + ` PRIVATE KEY----- marker", {"note": "and -----END RSA` + ` PRIVATE KEY----- marker"}]` + require.NoError(t, os.WriteFile(jsonFile7, []byte(validJSON7), 0o644)) + + jsonFile9 := filepath.Join(dir, "split_pem_lines.json") + validJSON9 := `["-----BEGIN RSA` + ` PRIVATE KEY-----","MIIEpAIBAAKCAQEA0000000000000000","-----END RSA` + ` PRIVATE KEY-----"]` + require.NoError(t, os.WriteFile(jsonFile9, []byte(validJSON9), 0o644)) + + var buf bytes.Buffer + printer := ui.New(&buf) + require.NoError(t, scanOutputFiles(dir, "trace-id", "", printer)) + + for _, p := range []struct { + path string + secret string + }{ + {jsonFile1, "ghp_FAKEtest"}, + {jsonFile2, "secret_password_1234"}, + {jsonFile3, "abcdefghijkl1234"}, + {jsonFile4, "ghp_FAKEtest"}, + {jsonFile5, "ghp_FAKEtest"}, + } { + content, err := os.ReadFile(p.path) + require.NoError(t, err) + assert.True(t, json.Valid(content), "sanitized %s must remain valid JSON: %s", filepath.Base(p.path), string(content)) + assert.NotContains(t, string(content), p.secret, "secret must be redacted from %s", filepath.Base(p.path)) + } + + // Decode the escaped-newline case and check the decoded credential. The + // unescaped spelling does not occur in the raw JSON, so a raw substring + // assertion alone would pass even if sanitization missed it. + content3, err := os.ReadFile(jsonFile3) + require.NoError(t, err) + var split struct { + Auth string `json:"auth"` + } + require.NoError(t, json.Unmarshal(content3, &split)) + assert.NotContains(t, split.Auth, "abc\ndefghijkl1234", "decoded credential must be redacted") + var escapedResult struct { + Findings []struct { + Password string `json:"password"` + } `json:"findings"` + } + escapedBytes, err := os.ReadFile(jsonFile2) + require.NoError(t, err) + require.NoError(t, json.Unmarshal(escapedBytes, &escapedResult)) + require.Len(t, escapedResult.Findings, 1) + assert.NotContains(t, escapedResult.Findings[0].Password, "secret_password_1234", "embedded secret must be redacted") + assert.Equal(t, "secr...", escapedResult.Findings[0].Password, "the value is wholly masked without changing surrounding JSON") + + content4, err := os.ReadFile(jsonFile4) + require.NoError(t, err) + assert.Contains(t, string(content4), "12345678901234567891", "large integer precision must be preserved") + assert.Contains(t, string(content4), "1.0", "float formatting must be preserved") + assert.Contains(t, string(content4), "&val", "HTML characters must not be escaped") + var keySanitized map[string]json.RawMessage + require.NoError(t, json.Unmarshal(content4, &keySanitized)) + for key := range keySanitized { + assert.NotContains(t, key, "ghp_FAKEtest", "secret must be redacted from JSON object keys") + } + + content5, err := os.ReadFile(jsonFile5) + require.NoError(t, err) + var collisionResult struct { + Tokens []string `json:"tokens"` + } + var collisionDocument map[string]json.RawMessage + require.NoError(t, json.Unmarshal(content5, &collisionDocument)) + require.NoError(t, json.Unmarshal(content5, &collisionResult)) + assert.Len(t, collisionResult.Tokens, 1) + assert.NotContains(t, collisionResult.Tokens[0], "ghp_FAKEtest", "array token must be redacted and retained") + + var preservedValues []int + var sanitizedKeys []string + for key, rawValue := range collisionDocument { + if key == "tokens" { + continue + } + sanitizedKeys = append(sanitizedKeys, key) + var value int + require.NoError(t, json.Unmarshal(rawValue, &value)) + preservedValues = append(preservedValues, value) + } + assert.ElementsMatch(t, []int{1, 2}, preservedValues, "both colliding-key values must survive under distinct sanitized keys") + assert.Len(t, sanitizedKeys, 2, "both colliding keys must be retained") + sort.Strings(sanitizedKeys) + assert.NotEqual(t, sanitizedKeys[0], sanitizedKeys[1], "colliding keys must be made distinct") + + content6, err := os.ReadFile(jsonFile6) + require.NoError(t, err) + assert.True(t, json.Valid(content6), "sanitized #5705 fixture must remain valid JSON") + var scribeResult map[string]string + require.NoError(t, json.Unmarshal(content6, &scribeResult)) + assert.NotContains(t, scribeResult["body"], "SCRIBE_SECRET_BACKEND=environment_backend", "incident-shaped assignment should be redacted") + assert.Contains(t, scribeResult["body"], "SCRIBE_SECRET_BACKEND=", "assignment context should remain visible") + + content7, err := os.ReadFile(jsonFile7) + require.NoError(t, err) + assert.True(t, json.Valid(content7), "cross-value private-key match must not corrupt JSON") + assert.NotContains(t, string(content7), "PRIVATE KEY-----", "both marker members must be masked") + assert.NotContains(t, string(content7), "output removed", "the document must be kept, not dropped") + content8, err := os.ReadFile(jsonFile8) + require.NoError(t, err) + assert.True(t, json.Valid(content8), "backstop handling must preserve valid JSON") + assert.NotContains(t, string(content8), "PRIVATE KEY-----", + "masking a password member must not hide the private-key markers") + assert.NotContains(t, string(content8), "output removed", "the document must be kept, not dropped") + content9, err := os.ReadFile(jsonFile9) + require.NoError(t, err) + assert.True(t, json.Valid(content9)) + assert.NotContains(t, string(content9), "PRIVATE KEY-----", "split PEM-like material must be masked") + assert.NotContains(t, string(content9), "MIIEpAIBAAKCAQEA", "base64 key material between the markers must be masked") + + // jq is the parser implicated by the original incident; exercise it when + // available, while keeping the Go validity assertions portable. + if _, err := exec.LookPath("jq"); err == nil { + cmd := exec.Command("jq", ".", jsonFile6) + assert.NoError(t, cmd.Run(), "jq must parse the sanitized incident-shaped fixture") + } else { + t.Logf("jq not found; the incident-fidelity jq parse check did not run (json.Valid was the only proxy)") + } +} + +// TestScanOutputFiles_DuplicateJSONKeys verifies that JSON files containing +// duplicate keys (which Go's map[string]any decoding drops) still have secrets +// redacted via the fail-closed fallback scan (#5705). +func TestScanOutputFiles_DuplicateJSONKeys(t *testing.T) { + dir := t.TempDir() + dupFile := filepath.Join(dir, "duplicate_keys.json") + secret := "ghp_FAKEtesttoken000000000000000000000000" + content := fmt.Sprintf(`{"a":"x %s","a":"second"}`, secret) + require.NoError(t, os.WriteFile(dupFile, []byte(content), 0o644)) + + dupWithLargeNumFile := filepath.Join(dir, "duplicate_with_large_num.json") + contentWithLargeNum := fmt.Sprintf(`{"large":1e1000,"a":"x %s","a":"second"}`, secret) + require.NoError(t, os.WriteFile(dupWithLargeNumFile, []byte(contentWithLargeNum), 0o644)) + + var buf bytes.Buffer + printer := ui.New(&buf) + require.NoError(t, scanOutputFiles(dir, "trace-id", "", printer)) + + got, err := os.ReadFile(dupFile) + require.NoError(t, err) + assert.NotContains(t, string(got), secret) + assert.Contains(t, string(got), "second") + + gotLarge, err := os.ReadFile(dupWithLargeNumFile) + require.NoError(t, err) + assert.NotContains(t, string(gotLarge), secret) + assert.Contains(t, string(gotLarge), "second") +} + +// TestScanOutputFiles_SingleRecordJSONL_PreservesLineCount verifies that +// single-record .jsonl files are processed through the line-preserving text scan +// rather than being reformatted into multi-line JSON (#5705). +func TestScanOutputFiles_SingleRecordJSONL_PreservesLineCount(t *testing.T) { + dir := t.TempDir() + jsonlFile := filepath.Join(dir, "events.jsonl") + secret := "ghp_FAKEtesttoken000000000000000000000000" + content := fmt.Sprintf(`{"action":"comment","body":"%s"}`+"\n", secret) + require.NoError(t, os.WriteFile(jsonlFile, []byte(content), 0o644)) + + var buf bytes.Buffer + printer := ui.New(&buf) + require.NoError(t, scanOutputFiles(dir, "trace-id", "", printer)) + + got, err := os.ReadFile(jsonlFile) + require.NoError(t, err) + assert.NotContains(t, string(got), secret) + assert.Equal(t, 1, strings.Count(string(got), "\n"), "single-record jsonl must remain exactly 1 line") + lines := strings.Split(strings.TrimSpace(string(got)), "\n") + assert.Len(t, lines, 1) +} + +func TestScanOutputFiles_JSONLCrossValuePrivateKeyRemainsValid(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "events.jsonl") + content := ` ["-----BEGIN RSA` + ` PRIVATE KEY-----","MIIEpAIBAAKCAQEA0000000000000000","-----END RSA` + ` PRIVATE KEY-----"]` + "\n" + require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{}))) + got, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, 1, strings.Count(string(got), "\n")) + line := strings.TrimSpace(string(got)) + assert.True(t, json.Valid([]byte(line)), "each JSONL record must remain valid JSON: %s", line) + assert.NotContains(t, line, "PRIVATE KEY-----", "the members carrying the markers must be masked") + assert.NotContains(t, line, "MIIEpAIBAAKCAQEA", "base64 key material between the markers must be masked") + assert.NotContains(t, line, "output removed", "the record must be kept, not dropped") +} + +func TestScanOutputFiles_JSONLRawMultilinePEMRemainsValid(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "raw_pem.jsonl") + begin := pemBegin + end := pemEnd + content := fmt.Sprintf("%s\nMIIEpAIBAAKCAQEA0123456789abcdefghijklmnop\n%s\n", begin, end) + require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{}))) + got, err := os.ReadFile(path) + require.NoError(t, err) + lines := strings.Split(strings.TrimSuffix(string(got), "\n"), "\n") + require.Len(t, lines, 3) + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each line must be valid JSON: %s", line) + assert.Contains(t, line, "output removed") + assert.NotContains(t, line, "MIIEpAIBAAKCAQEA") + } +} + +// TestScanOutputFiles_EmitsAnnotationWhenOutputIsRemoved pins that a whole-file +// fail-closed replacement is announced as a workflow command. A review lost to +// redaction must not pass silently: the run still exits 0, so the line is the +// only signal an operator gets (#5705). Forgejo Actions runners also set +// GITHUB_ACTIONS=true, so the same ::error:: line is written there, which is why +// the check is the variable and not the forge. GitHub Actions renders that line +// 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. +func TestScanOutputFiles_EmitsAnnotationWhenOutputIsRemoved(t *testing.T) { + const secret = `"v1","k2"` + security.ResetRuntimeSecretsForTest() + require.True(t, security.RegisterRuntimeSecret(secret)) + t.Cleanup(security.ResetRuntimeSecretsForTest) + + for name, tc := range map[string]struct { + env map[string]string + want string + }{ + "github actions": { + env: map[string]string{"GITHUB_ACTIONS": "true"}, + want: "::error::Output file replaced with a fail-closed marker: redaction would invalidate JSON", + }, + "forgejo actions": { + env: map[string]string{"GITHUB_ACTIONS": "true", "FORGEJO_ACTIONS": "true"}, + want: "::error::Output file replaced with a fail-closed marker: redaction would invalidate JSON", + }, + "local run": {env: nil, want: ""}, + } { + t.Run(name, func(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "") + t.Setenv("FORGEJO_ACTIONS", "") + for key, value := range tc.env { + t.Setenv(key, value) + } + dir := t.TempDir() + path := filepath.Join(dir, "agent-result.json") + // The secret spans the closing quote, comma and next key, so it + // cannot be redacted in place without breaking the document. + require.NoError(t, os.WriteFile(path, []byte(`{"k1":"v1","k2":"v2"}`), 0o644)) + + var output bytes.Buffer + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&output))) + + got, err := os.ReadFile(path) + require.NoError(t, err) + assert.True(t, json.Valid(got), "a replaced file must still be valid JSON: %s", got) + assert.NotContains(t, string(got), secret) + if tc.want == "" { + assert.NotContains(t, output.String(), "::error::") + return + } + assert.Contains(t, output.String(), tc.want) + }) + } +} + +// TestScanOutputFiles_EmitsAnnotationForBOMPrefixedRemoval pins that the UTF-8 +// BOM a replaced file keeps does not hide the loss. The mark is framing, not +// content, so a BOM-prefixed document that was replaced whole is still announced; +// before this the marker read as ordinary content and the run stayed silent +// (#5705). +func TestScanOutputFiles_EmitsAnnotationForBOMPrefixedRemoval(t *testing.T) { + const secret = `"v1","k2"` + security.ResetRuntimeSecretsForTest() + require.True(t, security.RegisterRuntimeSecret(secret)) + t.Cleanup(security.ResetRuntimeSecretsForTest) + t.Setenv("GITHUB_ACTIONS", "true") + + dir := t.TempDir() + path := filepath.Join(dir, "agent-result.json") + content := append([]byte("\ufeff"), []byte(`{"k1":"v1","k2":"v2"}`)...) + require.NoError(t, os.WriteFile(path, content, 0o644)) + + var output bytes.Buffer + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&output))) + + got, err := os.ReadFile(path) + require.NoError(t, err) + assert.True(t, bytes.HasPrefix(got, []byte("\ufeff")), "the encoding mark must survive: %q", got) + assert.True(t, json.Valid(bytes.TrimPrefix(got, []byte("\ufeff"))), "a replaced file must still be valid JSON: %s", got) + assert.NotContains(t, string(got), secret) + assert.Contains(t, output.String(), "::error::Output file replaced with a fail-closed marker") +} + +func TestScanOutputFiles_QuietJSONFallbackDoesNotPrintPath(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "agent-chosen-secret-name.json") + content := `{"token":"ghp_FAKEtesttoken000000000000000000000000","token":"second"}` + require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) + var output bytes.Buffer + require.NoError(t, scanOutputFiles(dir, "trace-id", "quiet", ui.New(&output))) + assert.NotContains(t, output.String(), "agent-chosen-secret-name.json") +} + +func TestScanOutputFiles_ReturnsErrorWhenSanitizedWriteFails(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "secret.txt") + require.NoError(t, os.WriteFile(path, []byte("Token: ghp_FAKEtesttoken000000000000000000000000"), 0o644)) + + err := scanOutputFilesWithDefaults(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { + return os.ErrPermission + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "could not write sanitized secret.txt") +} + +// TestScanOutputFiles_ReportsFailedQuarantine pins that a quarantine that cannot +// replace or remove the file is reported: the unredacted bytes are still on disk +// and the run's failure must say so, instead of looking like a plain write error +// (#5705). +func TestScanOutputFiles_ReportsFailedQuarantine(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("permission checks do not apply to root") + } + dir := t.TempDir() + path := filepath.Join(dir, "secret.txt") + require.NoError(t, os.WriteFile(path, []byte("Token: ghp_FAKEtesttoken000000000000000000000000"), 0o444)) + require.NoError(t, os.Chmod(dir, 0o555)) + t.Cleanup(func() { _ = os.Chmod(dir, 0o755) }) + if f, err := os.Create(filepath.Join(dir, "probe")); err == nil { + _ = f.Close() + _ = os.Remove(f.Name()) + t.Skip("filesystem does not enforce unwritable directory permissions") + } + + err := scanOutputFilesWithDefaults(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { + return os.ErrPermission + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "could not write sanitized secret.txt") + assert.Contains(t, err.Error(), "unredacted output file could not be replaced or removed", + "a failed quarantine must reach the joined error") + + var scanErr *outputScanError + require.ErrorAs(t, err, &scanErr) + assert.True(t, scanErr.failedOn(path), + "the file whose write and quarantine both failed must be recorded, so the gate cannot post its unredacted bytes") + assert.False(t, scanErr.failedOn(filepath.Join(dir, "other.json")), "a file the scan handled is not recorded") +} + +// TestScanOutputFiles_SanitizerErrorContainsFileAndContinues pins that a +// sanitizer error is contained the way a write failure is: the file it could not +// sanitize is replaced with the marker, the walk continues to the remaining +// files, and the run still fails closed. The sanitizers only fail on a decoder +// limit, so the failure is injected. +func TestScanOutputFiles_SanitizerErrorContainsFileAndContinues(t *testing.T) { + failingSanitizer := func([]byte, *security.Pipeline) ([]byte, []security.Finding, error) { + return nil, nil, errors.New("decoder limit") + } + + dir := t.TempDir() + failing := filepath.Join(dir, "a-result.json") + require.NoError(t, os.WriteFile(failing, []byte(`{"body":"ghp_FAKEtesttoken000000000000000000000000"}`), 0o644)) + later := filepath.Join(dir, "b-notes.txt") + require.NoError(t, os.WriteFile(later, []byte("Token: ghp_FAKEtesttoken000000000000000000000000"), 0o644)) + + err := scanOutputFilesWithWriter(dir, "trace-id", "", ui.New(&bytes.Buffer{}), os.WriteFile, failingSanitizer, security.SanitizeJSONLines) + require.Error(t, err) + assert.Contains(t, err.Error(), "could not sanitize a-result.json") + + got, readErr := os.ReadFile(failing) + require.NoError(t, readErr) + assert.Equal(t, unwritableOutputMarker, string(got), "an unsanitizable file must be contained") + assert.NotContains(t, string(got), "ghp_FAKEtesttoken") + + got, readErr = os.ReadFile(later) + require.NoError(t, readErr) + assert.NotContains(t, string(got), "ghp_FAKEtesttoken", + "the walk must continue past a sanitizer error and redact the remaining files") +} + +// TestScanOutputFiles_EmitsAnnotationForJSONLRecordRemoval pins that a replaced +// JSONL record is announced too. The file keeps its record framing, so it is +// never a whole-file marker, and without the annotation a lost record would only +// show up as one scan line (#5705). +func TestScanOutputFiles_EmitsAnnotationForJSONLRecordRemoval(t *testing.T) { + begin := pemBegin + end := pemEnd + content := "{\"event\":\"start\",\"text\":\"" + begin + "\"}\n" + + "{\"event\":\"body\",\"text\":\"MIIEpAIBAAKCAQEA0123456789abcdef\"}\n" + + "{\"event\":\"end\",\"text\":\"" + end + "\"}\n" + + for name, tc := range map[string]struct { + env map[string]string + want string + }{ + "github actions": { + env: map[string]string{"GITHUB_ACTIONS": "true"}, + want: "::error::Output record replaced with a fail-closed marker: a secret spanned multiple records", + }, + "forgejo actions": { + env: map[string]string{"GITHUB_ACTIONS": "true", "FORGEJO_ACTIONS": "true"}, + want: "::error::Output record replaced with a fail-closed marker: a secret spanned multiple records", + }, + "local run": {env: nil, want: ""}, + } { + t.Run(name, func(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "") + t.Setenv("FORGEJO_ACTIONS", "") + for key, value := range tc.env { + t.Setenv(key, value) + } + dir := t.TempDir() + path := filepath.Join(dir, "transcript.jsonl") + require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) + + var output bytes.Buffer + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&output))) + + got, err := os.ReadFile(path) + require.NoError(t, err) + assert.NotContains(t, string(got), "MIIEpAIBAAKCAQEA") + if tc.want == "" { + assert.NotContains(t, output.String(), "::error::") + return + } + assert.Contains(t, output.String(), tc.want) + }) + } +} + +// TestScanOutputFiles_HandlesJSONLAndNDJSON drives the record-scanning route over +// both extensions: .ndjson is accepted alongside .jsonl, but every other JSONL +// fixture names a .jsonl file. A multi-record .ndjson file that fell to the plain +// text scan could still have its record syntax broken by an in-place redaction, +// which is the corruption class #5705 set out to eliminate. +func TestScanOutputFiles_HandlesJSONLAndNDJSON(t *testing.T) { + content := "{\"event\":\"start\",\"text\":\"" + pemBegin + "\"}\n" + + "{\"event\":\"body\",\"text\":\"MIIEpAIBAAKCAQEA0123456789abcdef\"}\n" + + "{\"event\":\"end\",\"text\":\"" + pemEnd + "\"}\n" + + for _, ext := range []string{".jsonl", ".ndjson", ".json"} { + t.Run(ext, func(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "") + dir := t.TempDir() + path := filepath.Join(dir, "transcript"+ext) + require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) + + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{}))) + + got, err := os.ReadFile(path) + require.NoError(t, err) + assert.NotContains(t, string(got), "MIIEpAIBAAKCAQEA", "the body must not survive in %s", ext) + lines := strings.Split(strings.TrimSuffix(string(got), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change in %s", ext) + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON in %s: %s", ext, line) + } + }) + } +} + +// TestScanOutputFiles_WritesWhenBytesModifiedEvenWithZeroFindings pins that +// any byte change produced by the structural sanitizer is written to disk, +// even if findings slice is empty, preventing silent data drops (#5705). +func TestScanOutputFiles_WritesWhenBytesModifiedEvenWithZeroFindings(t *testing.T) { + dir := t.TempDir() + docPath := filepath.Join(dir, "doc.json") + require.NoError(t, os.WriteFile(docPath, []byte(`{"a": 1}`), 0o644)) + + stubDoc := func(in []byte, p *security.Pipeline) ([]byte, []security.Finding, error) { + return []byte(`{"a": 2}`), nil, nil + } + require.NoError(t, scanOutputFilesWithWriter(dir, "trace", "", ui.New(&bytes.Buffer{}), os.WriteFile, stubDoc, security.SanitizeJSONLines)) + got, err := os.ReadFile(docPath) + require.NoError(t, err) + assert.Equal(t, `{"a": 2}`, string(got)) +} + +// TestScanOutputFiles_NoAnnotationForPreexistingMarkerLine pins that a clean +// JSONL file that already holds a marker-equal line raises no error annotation: +// this pass removed nothing, so an operator should not be told a record was lost. +// Such a line is a re-scanned artifact, a fixture, or a line the agent wrote on +// purpose (#5705). +func TestScanOutputFiles_NoAnnotationForPreexistingMarkerLine(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + content := `{"error":"output removed because output contained a cross-record secret"}` + "\n" + + `{"event":"done"}` + "\n" + dir := t.TempDir() + path := filepath.Join(dir, "transcript.jsonl") + require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) + + var output bytes.Buffer + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&output))) + + assert.NotContains(t, output.String(), "::error::", "a clean stream must not raise an annotation") + got, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, content, string(got), "a clean stream must be written back unchanged") +} + +// TestScanOutputFiles_QuietWriteFailureKeepsPathAndCause pins that a quiet run +// still reports what failed in the error it returns: the file and the wrapped +// write error reach telemetry and the root span, and only the printed line is +// trimmed (failureLine, quietRunError) under ADR 0163. +func TestScanOutputFiles_QuietWriteFailureKeepsPathAndCause(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "secret.json") + require.NoError(t, os.WriteFile(path, []byte(`{"token":"ghp_FAKEtesttoken000000000000000000000000"}`), 0o644)) + writeErr := errors.New("no space left on device") + err := scanOutputFilesWithDefaults(dir, "trace-id", "quiet", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { + return writeErr + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "could not write sanitized secret.json", + "the run error keeps the path at quiet, so telemetry can name it") + assert.ErrorIs(t, err, writeErr, "the run error keeps the wrapped cause at quiet") +} + +// TestScanOutputFiles_ContinuesRedactingAfterWriteFailure pins that one +// unwritable file does not stop the walk: every other file is still redacted, +// and the run fails closed with the collected error afterwards. +func TestScanOutputFiles_ContinuesRedactingAfterWriteFailure(t *testing.T) { + dir := t.TempDir() + first := filepath.Join(dir, "a-secret.txt") + second := filepath.Join(dir, "b-secret.txt") + const secret = "ghp_FAKEtesttoken000000000000000000000000" + require.NoError(t, os.WriteFile(first, []byte("Token: "+secret), 0o644)) + require.NoError(t, os.WriteFile(second, []byte("Token: "+secret), 0o644)) + + err := scanOutputFilesWithDefaults(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(path string, data []byte, mode os.FileMode) error { + if path == first { + return os.ErrPermission + } + return os.WriteFile(path, data, mode) + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "could not write sanitized a-secret.txt") + + got, readErr := os.ReadFile(second) + require.NoError(t, readErr) + assert.NotContains(t, string(got), secret, "files after a write failure must still be redacted") +} + +func TestScanOutputFiles_BackstopDoesNotRemaskExistingMask(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "agent-result.json") + content := "{\n \"body\": \"Guard against null values with token_usage = metrics.get(\\\"token_usage\\\") or {}\"\n}" + require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) + + var output bytes.Buffer + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&output))) + first, err := os.ReadFile(path) + require.NoError(t, err) + assert.Contains(t, string(first), "metr...", "the first redaction should retain its informative prefix") + assert.NotContains(t, output.String(), "(backstop)", "the structural mask should not be redacted again") + + assert.Equal(t, 1, strings.Count(output.String(), "Sanitized [env_assignment]"), "one secret should create one finding") + + // Rescanning the already-sanitized document must be idempotent. + var secondOutput bytes.Buffer + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&secondOutput))) + second, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, first, second) +} + +// TestScanOutputFiles_CleanJSON verifies that clean JSON files with no findings +// remain completely untouched byte-for-byte. +func TestScanOutputFiles_CleanJSON(t *testing.T) { + dir := t.TempDir() + cleanFile := filepath.Join(dir, "clean.json") + content := `{"count": 42, "status": "ok"}` + require.NoError(t, os.WriteFile(cleanFile, []byte(content), 0o644)) + + var buf bytes.Buffer + printer := ui.New(&buf) + require.NoError(t, scanOutputFiles(dir, "trace-id", "", printer)) + + got, err := os.ReadFile(cleanFile) + require.NoError(t, err) + assert.Equal(t, content, string(got), "clean JSON should remain byte-for-byte identical") +} + +func TestScanOutputFiles_NumericRuntimeSecretRedacted(t *testing.T) { + const secretNum = "123456789012" + security.ResetRuntimeSecretsForTest() + t.Cleanup(security.ResetRuntimeSecretsForTest) + require.True(t, security.RegisterRuntimeSecret(secretNum)) + + dir := t.TempDir() + jsonPath := filepath.Join(dir, "numeric.json") + require.NoError(t, os.WriteFile(jsonPath, []byte(fmt.Sprintf(`{"id":%s}`, secretNum)), 0o644)) + + jsonlPath := filepath.Join(dir, "numeric.jsonl") + require.NoError(t, os.WriteFile(jsonlPath, []byte(fmt.Sprintf(`{"id":%s}`+"\n", secretNum)), 0o644)) + + var output bytes.Buffer + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&output))) + + gotJSON, err := os.ReadFile(jsonPath) + require.NoError(t, err) + assert.NotContains(t, string(gotJSON), secretNum) + assert.True(t, json.Valid(gotJSON)) + + gotJSONL, err := os.ReadFile(jsonlPath) + require.NoError(t, err) + assert.NotContains(t, string(gotJSONL), secretNum) + lines := strings.Split(strings.TrimSpace(string(gotJSONL)), "\n") + require.Len(t, lines, 1) + assert.True(t, json.Valid([]byte(lines[0]))) +} + +// TestScanOutputFiles_WriteFailureRemovesUnredactedBytes pins that a file whose +// sanitized content cannot be written is replaced with a fail-closed marker, so +// the unredacted bytes cannot reach the uploaded artifact. +func TestScanOutputFiles_WriteFailureRemovesUnredactedBytes(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "secret.txt") + const secret = "ghp_FAKEtesttoken000000000000000000000000" + require.NoError(t, os.WriteFile(path, []byte("Token: "+secret), 0o644)) + + err := scanOutputFilesWithDefaults(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { + return os.ErrPermission + }) + require.Error(t, err) + + got, readErr := os.ReadFile(path) + require.NoError(t, readErr) + assert.NotContains(t, string(got), secret, "the unredacted bytes must not survive a write failure") + assert.JSONEq(t, `{"error":"output removed because it could not be redacted"}`, string(got)) +} + +// TestScanOutputFiles_UnreadableFileFailsClosed pins that a file the scan cannot +// read does not reach the artifact unredacted. Its bytes were never scanned, so +// the file is contained with the fail-closed marker, the rest of the walk still +// runs, and the run fails closed (#5705). Before this, the file was only named in +// a warning and shipped. +func TestScanOutputFiles_UnreadableFileFailsClosed(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("permission checks do not apply to root") + } + dir := t.TempDir() + unreadable := filepath.Join(dir, "a-unreadable.txt") + const secret = "ghp_FAKEtesttoken000000000000000000000000" + require.NoError(t, os.WriteFile(unreadable, []byte("Token: "+secret), 0o644)) + require.NoError(t, os.Chmod(unreadable, 0o000)) + t.Cleanup(func() { _ = os.Chmod(unreadable, 0o644) }) + if file, err := os.Open(unreadable); err == nil { + _ = file.Close() + t.Skip("filesystem does not enforce unreadable file permissions") + } + later := filepath.Join(dir, "b-notes.txt") + require.NoError(t, os.WriteFile(later, []byte("Token: "+secret), 0o644)) + + err := scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{})) + require.Error(t, err) + assert.Contains(t, err.Error(), "could not read a-unreadable.txt") + + // The walk continued to the file after the unreadable one. + got, readErr := os.ReadFile(later) + require.NoError(t, readErr) + assert.NotContains(t, string(got), secret, "a later file must still be redacted") + + // The unreadable file is contained: its unredacted bytes are gone, either + // replaced by the marker or removed when it cannot be written. + contained, readErr := os.ReadFile(unreadable) + if readErr == nil { + assert.NotContains(t, string(contained), secret, "the unredacted bytes must not survive") + assert.JSONEq(t, `{"error":"output removed because it could not be redacted"}`, string(contained)) + } else { + assert.True(t, os.IsNotExist(readErr), "an unreadable file that cannot be replaced must be removed: %v", readErr) + } +} + +// TestScanOutputFiles_UnreadableDirectoryFailsClosed pins that a directory the +// walk cannot open fails the run: nothing under it was scanned, so its bytes +// would otherwise reach the artifact unredacted (#5705). +func TestScanOutputFiles_UnreadableDirectoryFailsClosed(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("permission checks do not apply to root") + } + dir := t.TempDir() + blocked := filepath.Join(dir, "agent-dir") + require.NoError(t, os.MkdirAll(blocked, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(blocked, "notes.txt"), []byte("Token: ghp_FAKEtesttoken000000000000000000000000"), 0o644)) + require.NoError(t, os.Chmod(blocked, 0o000)) + t.Cleanup(func() { _ = os.Chmod(blocked, 0o755) }) + if entries, err := os.ReadDir(blocked); err == nil { + _ = entries + t.Skip("filesystem does not enforce unreadable directory permissions") + } + + err := scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{})) + require.Error(t, err) + assert.Contains(t, err.Error(), "could not read agent-dir") +} + +// TestScanOutputFiles_QuietReadFailureKeepsPathInErrorOnly pins the quiet +// contract for a read failure: the file name — which can be agent-chosen +// (ADR 0163) — stays out of the printed log but stays in the run error, so +// telemetry records which file could not be scanned. +func TestScanOutputFiles_QuietReadFailureKeepsPathInErrorOnly(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("permission checks do not apply to root") + } + dir := t.TempDir() + path := filepath.Join(dir, "agent-chosen-secret-name.txt") + require.NoError(t, os.WriteFile(path, []byte("Token: ghp_FAKEtesttoken000000000000000000000000"), 0o644)) + require.NoError(t, os.Chmod(path, 0o000)) + t.Cleanup(func() { _ = os.Chmod(path, 0o644) }) + if file, err := os.Open(path); err == nil { + _ = file.Close() + t.Skip("filesystem does not enforce unreadable file permissions") + } + + var output bytes.Buffer + err := scanOutputFiles(dir, "trace-id", "quiet", ui.New(&output)) + require.Error(t, err) + assert.Contains(t, err.Error(), "agent-chosen-secret-name.txt", + "the run error keeps the path at quiet, so telemetry can name it") + assert.NotContains(t, output.String(), "agent-chosen-secret-name.txt", + "the printed log must not name an agent-chosen file at quiet") +} + +// TestScanOutputFiles_QuietScanFailureStatusDetailOmitsAgentName pins the +// completion-comment channel at quiet: the run error keeps the agent-chosen +// output file name for telemetry, while the detail the comment posts carries +// the count alone. Actions log masking does not apply to a comment, and the +// name is the agent's to choose (#5705, ADR 0163). +func TestScanOutputFiles_QuietScanFailureStatusDetailOmitsAgentName(t *testing.T) { + dir := t.TempDir() + const name = "@org/team-secret.json" + path := filepath.Join(dir, name) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(`{"token":"ghp_FAKEtesttoken000000000000000000000000"}`), 0o644)) + writeErr := errors.New("no space left on device") + + err := scanOutputFilesWithDefaults(dir, "trace-id", "quiet", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { + return writeErr + }) + require.Error(t, err) + assert.Contains(t, err.Error(), name, "the run error keeps the path for telemetry") + assert.ErrorIs(t, err, writeErr, "the run error keeps the wrapped cause for telemetry") + + detail := failureStatusDetail(err, "quiet") + assert.NotContains(t, detail, name, "the completion comment must not post an agent-chosen name") + assert.NotContains(t, detail, "no space left on device") + assert.Equal(t, "post-agent output scan failed: 1 file(s) could not be scanned", detail) + + assert.Contains(t, failureStatusDetail(err, ""), name, "full posts the error as before") +} + +// TestScanOutputFiles_SanitizesBOMPrefixedJSONStructurally pins that a JSON +// document that starts with a UTF-8 BOM still takes the structural path. The BOM +// is not JSON whitespace, so before this it fell through to the plain-text scan, +// which cannot guarantee the document keeps valid JSON syntax (#5705). +func TestScanOutputFiles_SanitizesBOMPrefixedJSONStructurally(t *testing.T) { + begin := pemBegin + end := pemEnd + doc := `{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `","verdict":"approve"}` + + dir := t.TempDir() + path := filepath.Join(dir, "agent-result.json") + require.NoError(t, os.WriteFile(path, append([]byte("\ufeff"), doc...), 0o644)) + + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{}))) + + got, err := os.ReadFile(path) + require.NoError(t, err) + bom := []byte("\ufeff") + require.True(t, bytes.HasPrefix(got, bom), "a BOM-prefixed file keeps its encoding mark: %q", got) + body := bytes.TrimPrefix(got, bom) + assert.True(t, json.Valid(body), "the sanitized document must stay valid JSON: %s", body) + assert.NotContains(t, string(body), "BEGIN RSA") + assert.NotContains(t, string(body), "MIIEpAIBAAKCAQEA") + assert.Contains(t, string(body), `"verdict":"approve"`, "a member outside the block must survive") +} diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go new file mode 100644 index 0000000000..08108282fc --- /dev/null +++ b/internal/security/jsonsanitize.go @@ -0,0 +1,1478 @@ +package security + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "regexp" + "strconv" + "strings" + "unicode/utf8" +) + +// JSON output that cannot be redacted without corrupting its structure is +// replaced with one of these valid JSON markers so downstream parsers (jq, the +// retro and eval tooling) keep working while no secret reaches the artifact. +// Each marker names the reason its content was dropped: the CLI turns that +// reason into an operator alert, because a replaced file loses whatever the +// agent wrote into it (#5705). +const ( + failClosedInvalidJSON = `{"error":"output removed because redaction would invalidate JSON"}` + failClosedCrossRecordJSON = `{"error":"output removed because output contained a cross-record secret"}` + failClosedSpansMembersJSON = `{"error":"output removed because a private key block spans JSON framing"}` + FailClosedUnwritableJSON = `{"error":"output removed because it could not be redacted"}` +) + +// privateKeyMask replaces each JSON string value that carries key material from a +// private-key block spanning JSON framing, and any key name that carries block +// text itself. +const privateKeyMask = "[REDACTED PRIVATE KEY]" + +// utf8BOM is the encoding mark some tooling writes at the start of a UTF-8 +// file. encoding/json does not accept it as leading content, so a document that +// carries one has to lose the prefix before it can be parsed and get it back on +// write. Without that, the file falls through to the plain-text scan, where a +// redaction can still break the JSON syntax the BOM was hiding (#5705). +var utf8BOM = []byte{0xEF, 0xBB, 0xBF} + +// IsJSONDocument reports whether doc is one JSON document, tolerating a leading +// UTF-8 BOM. SanitizeJSONDocument uses the same test, so callers route exactly +// the documents here that it will treat structurally. +func IsJSONDocument(doc []byte) bool { + return json.Valid(bytes.TrimSpace(bytes.TrimPrefix(doc, utf8BOM))) +} + +// IsJSONLines reports whether content consists of two or more non-empty lines +// where every non-empty line is a valid JSON document. Callers use it to detect +// a multi-document JSON stream regardless of file extension (#5705). +func IsJSONLines(content []byte) bool { + lines := bytes.Split(content, []byte("\n")) + nonEmpty := 0 + for _, line := range lines { + trimmed := bytes.TrimSpace(bytes.TrimPrefix(bytes.TrimSpace(line), utf8BOM)) + if len(trimmed) == 0 { + continue + } + if !json.Valid(trimmed) { + return false + } + nonEmpty++ + } + return nonEmpty >= 2 +} + +// restoreBOM puts back the UTF-8 BOM the structural path strips, so a +// BOM-prefixed file keeps its encoding mark. +func restoreBOM(original, sanitized []byte) []byte { + if !bytes.HasPrefix(original, utf8BOM) { + return sanitized + } + out := make([]byte, 0, len(utf8BOM)+len(sanitized)) + out = append(out, utf8BOM...) + return append(out, sanitized...) +} + +// outputRemovalMarkers lists every whole-file removal marker with the reason it +// states. +var outputRemovalMarkers = []struct { + document, reason string +}{ + {failClosedInvalidJSON, "redaction would invalidate JSON"}, + {failClosedCrossRecordJSON, "a secret spanned multiple records"}, + {failClosedSpansMembersJSON, "a private key block spans JSON framing"}, + {FailClosedUnwritableJSON, "it could not be redacted"}, +} + +// OutputRemoval reports whether sanitized is a whole-file removal marker and +// returns the reason it states. A replaced file loses the content the agent +// wrote into it, so callers alert operators rather than let that loss pass +// silently (#5705). +// +// A leading UTF-8 BOM is framing, not content. SanitizeJSONDocument restores the +// mark on its fail-closed returns and a replaced JSONL record keeps the mark its +// line carried, so the comparison strips it: otherwise a BOM-prefixed file or +// record that lost everything would read as ordinary content and raise no alert. +func OutputRemoval(sanitized []byte) (string, bool) { + trimmed := string(bytes.TrimSpace(bytes.TrimPrefix(bytes.TrimSpace(sanitized), utf8BOM))) + for _, marker := range outputRemovalMarkers { + if trimmed == marker.document { + return marker.reason, true + } + } + return "", false +} + +// OutputRecordRemovals returns the reason stated by each fail-closed marker +// record in a sanitized JSONL stream, in order and without repeats. A JSONL file +// keeps its framing when records are replaced, so it is never a whole-file +// marker, yet the records it lost still have to reach an operator (#5705). +func OutputRecordRemovals(sanitized []byte) []string { + var ( + reasons []string + seen = map[string]bool{} + ) + for _, line := range bytes.Split(sanitized, []byte("\n")) { + reason, removed := OutputRemoval(line) + if !removed || seen[reason] { + continue + } + seen[reason] = true + reasons = append(reasons, reason) + } + return reasons +} + +// sensitiveJSONKeyRe matches object keys whose values are masked even when the +// value itself does not match a secret pattern. +var sensitiveJSONKeyRe = regexp.MustCompile(`(?i)(?:key|token|secret|password|credential|auth)`) + +// redactedJSONKey replaces an object key that sanitization removed entirely +// (a key made only of bidi overrides or other invisible characters, for +// example). Such a key must never be restored as-is. +const redactedJSONKey = "redacted" + +// SanitizeJSONDocument structurally sanitizes a single JSON document so that +// redaction never changes its syntax. It returns the bytes to write and the +// findings that justified a rewrite; no findings means the document is clean +// and the caller must leave it untouched. A document that is not valid JSON is +// returned unchanged with no findings so the caller can fall back to a text +// scan. +// +// The document is rewritten by a token-preserving walk rather than decoded into +// a map and re-encoded: that keeps member order and duplicate keys, so a +// secret that spans JSON framing is still visible in the rewritten bytes. +func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { + if !IsJSONDocument(doc) { + return doc, nil, nil + } + // A BOM is framing rather than content: the token walk cannot parse it, and + // every return below puts it back, so it is stripped once here. + body := bytes.TrimPrefix(doc, utf8BOM) + trimmed := bytes.TrimSpace(body) + // A block that spans members is invisible to both the leaf scan and the + // written-bytes scan once a member is masked, and its markers may be + // \u-escaped in the raw bytes. The decoded view is the only place it is + // visible, so it is consulted before anything is rewritten. + spans := collectJSONLeaves(trimmed).spanningPrivateKeys() + if spans.unmappable > 0 { + // The view is built from the leaves themselves, so localization should + // never fail. If the walks ever disagree, fail closed rather than write + // bytes that may still carry the block. + return restoreBOM(doc, preserveTrailingNewline([]byte(failClosedSpansMembersJSON), doc)), + []Finding{privateKeySpanFinding(spans.unmappable, false)}, nil + } + rebuilt, findings, err := rewriteJSONTokens(trimmed, p, spans) + if err != nil { + // json.Valid accepted the text and the walk uses the same scanner, so + // this is a decoder limit rather than a syntax error. Return the error + // so the caller fails closed instead of writing unscanned bytes. + return nil, nil, fmt.Errorf("could not sanitize JSON document: %w", err) + } + out := body + if len(findings) > 0 || spans.localized > 0 { + out = rebuilt + } + if spans.localized > 0 { + findings = append(findings, privateKeySpanFinding(spans.localized, true)) + } + // Scan the bytes that will actually be written, for the whole-value secrets + // a leaf scan cannot see: a runtime value or a private-key block that spans + // JSON framing (for example a PEM block split across members) and so cannot + // be mapped back to a single leaf. + sanitizedOut, outputFindings := redactJSONOutput(out, p) + if bytes.Equal(sanitizedOut, body) { + // Nothing changed: hand the document back exactly as received. Running + // the trailing-newline adjustment on unchanged bytes would collapse a + // document that ends in more than one newline, rewriting a clean file + // and contradicting the byte-for-byte guarantee (#5705). + return restoreBOM(doc, body), append(findings, outputFindings...), nil + } + return restoreBOM(doc, preserveTrailingNewline(sanitizedOut, body)), append(findings, outputFindings...), nil +} + +// privateKeySpanFinding reports the private-key blocks that span JSON framing. +// localized says whether they were masked in the members that carried them or +// the whole document had to be dropped. +func privateKeySpanFinding(blocks int, localized bool) Finding { + detail := fmt.Sprintf("%d private key block(s) span JSON framing; masked the string values carrying them", blocks) + if !localized { + detail = "Private key block spans JSON framing and cannot be localized; output removed" + } + return Finding{ + Scanner: "secret_redactor", + Name: "private_key", + Severity: "critical", + Detail: detail, + } +} + +// privateKeyRe is the structural private-key pattern. A block that spans JSON +// framing has to be detected on the raw document: running the whole pipeline +// first lets a sensitive-named member mask the BEGIN marker and hide it. +var privateKeyRe = func() *regexp.Regexp { + for _, pattern := range defaultStructuralPatterns() { + if pattern.name == "private_key" { + return pattern.regex + } + } + panic("private_key structural pattern is missing") +}() + +// privateKeyMarkerRe matches a private-key marker line, including the fragments a +// marker is reduced to when it is split across members. It marks the text a +// multi-member block carries into a key name or string value, so nothing that is +// block content is written back as structure. The quoted markers are the ones +// privateKeyRe delimits a block with. +var privateKeyMarkerRe = regexp.MustCompile(`-----BEGIN|-----END|PRIVATE KEY-----`) + +// privateKeyMaterialRe matches a run of candidate PEM body material: the base64 +// alphabet (which covers hex) at a length no short identifier or enum value +// reaches. A string value covered by a framing-spanning block is masked only +// when it holds a marker or a run pemBodyRun accepts, because a lazy pattern that +// runs from one member's BEGIN to another member's END also covers the members +// between them. Masking those unconditionally replaced structural values — a +// finding's severity, category, action or repo, all of which the review schema +// constrains to enums and patterns — so the review failed validation and was not +// posted, which is the #5705 outcome. +// +// The length floor alone does not separate body material from free text: a long +// word ("misconfiguration") and a file path ("internal/security/jsonsanitize") +// both reach 16 characters using only base64 characters, and a path adds a slash +// that reads as base64 padding or division. pemBodyRun therefore also requires +// the case and digit mix a base64 body carries and a word or a path does not. +// A single member can hold only one line of the body, so a body split into short +// or digit-free chunks is decided by the joined text of consecutive members +// instead (maskSpanBody). +var privateKeyMaterialRe = regexp.MustCompile(`[A-Za-z0-9+/]{16,}=*`) + +// pemBodyRunRe matches a maximal run of base64 characters inside a leaf. A body +// fragment can be embedded in surrounding text or line framing — "part: MIIEowIB", +// or a chunk stored together with the newline that ended the line — so the runs, +// not the whole value, are what join a body. A run of two or more characters +// joins the candidate body directly. A run of exactly one character is +// ambiguous — it is as likely to be free text as a body fragment — so it joins +// only while the candidate run is still empty or entirely single-character: +// a body stored one character per member is reconstructed and decided on its +// joined text (pemBodyJoined), while an isolated single-character free-text +// value between a quoted marker pair keeps its content. A body split so that +// one-character and longer chunks alternate is not reconstructed (a known +// residual); uniform chunks and whole body lines are. +var pemBodyRunRe = regexp.MustCompile(`[A-Za-z0-9+/]+=*`) + +// pemBodyRuns returns the base64 runs of a leaf's text concatenated, or nil when +// the leaf carries no run at all. Surrounding prose, punctuation and whitespace +// stay out of the joined text, while an embedded body fragment (a "part:" prefix, +// a trailing newline) is still collected instead of breaking the run (#5705). +func pemBodyRuns(text []byte) []byte { + runs := pemBodyRunRe.FindAll(text, -1) + if len(runs) == 0 { + return nil + } + var material []byte + for _, run := range runs { + material = append(material, run...) + } + return material +} + +// schemaConstrainedFields is the set of review schema keys whose values are +// structural (enums, file paths, repository identifiers) rather than key material. +// When a quoted marker pair covers a review result, these fields are protected +// from joining candidate PEM body runs so schema validation is not broken (#5705). +var schemaConstrainedFields = map[string]bool{ + "action": true, + "category": true, + "severity": true, + "file": true, + "repo": true, + "head_sha": true, + "id": true, + "dimension": true, + "reason": true, + "pr_number": true, + "line": true, + "actionable": true, +} + +// isSchemaConstrainedField reports whether a value under memberKey is a +// schema-constrained review field rather than candidate key material. +func isSchemaConstrainedField(memberKey, value string) bool { + if !schemaConstrainedFields[memberKey] { + return false + } + if textCarriesKeyMaterial([]byte(value)) { + return false + } + return true +} + +// jsonProvenance accumulates an order-preserving view of the decoded strings +// in a document so a private-key block that spans members can be detected after +// JSON decoding. The raw bytes are not usable for this: a member may encode a +// marker with \u escapes, and masking a sensitive member removes the BEGIN +// marker before the rewritten document is scanned. +type jsonProvenance struct { + decoded bytes.Buffer + ranges []recordSpan + // keys marks the entries in ranges that are object keys rather than string + // values. Key names are the document's structure, so a block that spans + // them is neutralized differently from a block that spans values. + keys []bool + memberKeys []string +} + +// decodedViewNormalizer normalizes decoded JSON text before it is matched for +// framing-spanning secrets, so a marker obfuscated with zero-width or bidi +// characters is normalized exactly as the per-leaf scan normalizes it. +var decodedViewNormalizer = NewUnicodeNormalizer() + +// addString appends one decoded key or string value to the view and records its +// byte range so a match can be mapped back to the leaves that carry it. +func (v *jsonProvenance) addString(s string, isKey bool, memberKey string) { + s = decodedViewNormalizer.Scan(s).Sanitized + start := v.decoded.Len() + v.decoded.WriteString(s) + v.decoded.WriteByte('\n') + v.ranges = append(v.ranges, recordSpan{start: start, end: v.decoded.Len() - 1}) + v.keys = append(v.keys, isKey) + v.memberKeys = append(v.memberKeys, memberKey) +} + +// privateKeySpans is the result of looking for private-key blocks that span the +// keys and values of one document. +type privateKeySpans struct { + // covered holds the indexes of the string values that carry part of a block + // spanning more than one leaf. Every covered value is replaced whole. + covered map[int]bool + // maskedKeys holds the indexes of the object keys whose own name carries + // block content — a marker, or a run of base64 body material — so the name + // is key material rather than structure. + maskedKeys map[int]bool + // localized counts the blocks that were mapped onto leaves. + localized int + // unmappable counts the blocks that no leaf range covers. + unmappable int +} + +// spanningPrivateKeys finds the private-key blocks in the decoded view that are +// not contained in a single key or value, and maps each one onto the leaves it +// covers. Containment is checked per match: a lazy pattern can start at one +// leaf's BEGIN and end at another leaf's END, and counting differences would let +// that match cancel out a complete leaf block. +// +// A block whose markers sit in different members is not proof that key material +// spans them — a review that quotes the header in one finding and the footer in +// another matches too — so only the members the match carries block content into +// are touched. The strings the match starts and ends in carry marker text and are +// masked unconditionally; a string value in between is masked when it holds a +// block marker or base64 body material (valueCarriesKeyMaterial) or when the +// joined text of its neighbours looks like a PEM body line (maskSpanBody). Those +// are the two shapes key material takes in a member, while the free text and enum +// values between a quoted marker pair stay readable, so a review result keeps its +// shape instead of failing schema validation and being dropped (#5705). An object +// key keeps its name unless the match starts or ends in it, or the name itself +// carries block content — a marker or a run of base64 body material: key names are +// the document's structure, and masking them would drop a required field such as a +// finding's severity, category or file and make the document fail schema +// validation. A key name that is itself a body line is not structure, though; it is +// key material, and leaving it writes the body back after the markers are masked, +// where the written-bytes rescan can no longer see the block (#5705). +func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { + spans := privateKeySpans{covered: map[int]bool{}, maskedKeys: map[int]bool{}} + for _, match := range privateKeyRe.FindAllIndex(v.decoded.Bytes(), -1) { + if v.leafContaining(match[0], match[1]) >= 0 { + // A block inside one leaf is that leaf's own scan. + continue + } + var hit []int + for i, r := range v.ranges { + if r.start < match[1] && match[0] < r.end { + hit = append(hit, i) + } + } + if len(hit) == 0 { + spans.unmappable++ + continue + } + spans.localized++ + // The middle members are decided together: a body split into chunks + // that are each shorter than the material floor is only recognizable + // once they are joined. + v.maskSpanBody(hit, &spans) + for pos, i := range hit { + // The match begins with a BEGIN marker and ends with an END marker, so + // the leaves it starts and ends in always carry marker text. They are + // masked even when the marker itself is split across two members and + // neither fragment matches privateKeyMarkerRe on its own. + atBoundary := pos == 0 || pos == len(hit)-1 + if v.keys[i] { + if atBoundary || v.valueCarriesKeyMaterial(i) { + spans.maskedKeys[i] = true + } + continue + } + if atBoundary || v.valueCarriesKeyMaterial(i) { + spans.covered[i] = true + } + } + } + return spans +} + +// maskSpanBody covers the string values between a framing-spanning block's +// boundary members when their joined text looks like PEM body material. A member +// holds one line of the body, and an agent can split the body so that every line +// is short or digit-free; a per-member test then accepts none of them and writes +// the body back after the markers are masked, where the written-bytes rescan can +// no longer see the block (#5705). Consecutive candidate segments are therefore +// decided together, whatever their individual length: the base64 runs embedded in +// a member are collected (pemBodyRuns), so surrounding prose, a "part:" prefix or +// the newline an agent kept with a body line does not break the run, and the +// joined text is what has to look like a body line. An object key never joins the +// run — a key is structure, +// and letting one into the joined text renames required schema keys (severity, +// category, file) — but it does not break the run either: the values on either +// side of a key are still consecutive body chunks once the key names are ignored, +// so a body stored in separate object members is reconstructed and masked. A +// member that carries a single base64 character joins only while the run is +// empty or entirely single-character, so a body stored one character per member +// is reconstructed while an isolated single-character value keeps its content; a +// body whose one-character and longer chunks interleave is a known residual and +// is not reconstructed. A key +// whose own name is a body line is masked on its own instead +// (spanningPrivateKeys). +func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { + var group []int + var joined []byte + // bodySeeded says the current run was restarted at a recognized body line. + bodySeeded := false + // allSingle says every member of the current run carried a one-character + // base64 run. A one-character value cannot be told from free text, so it + // only joins a run that is still empty or all-single: a run of many + // single-character values is a body stored one character per member and is + // decided on its joined text (pemBodyJoined), while an isolated + // single-character value following a body line stays free text (#5705). + allSingle := true + flush := func() { + if len(group) == 0 { + bodySeeded = false + return + } + if bodySeeded || pemBodyJoined(joined) { + for _, i := range group { + spans.covered[i] = true + } + } + group = group[:0] + joined = joined[:0] + bodySeeded = false + allSingle = true + } + for pos, i := range hit { + if pos == 0 || pos == len(hit)-1 { + flush() + continue + } + if v.keys[i] { + // The key is structure, not a body chunk: skip it without breaking + // the run (see the doc comment). + continue + } + valBytes := v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end] + if isSchemaConstrainedField(v.memberKeys[i], string(valBytes)) { + // A schema-constrained field (severity, category, file, etc.) is + // review structure, not key material: it never joins a candidate + // run and breaks any pending run (#5705). + flush() + continue + } + if v.valueCarriesKeyMaterial(i) { + // A value that is a complete body line on its own is covered by the + // main loop. It ends the preceding run — the structural values before + // it ("severity", "category", "file") must not be joined into a mask + // with it — but the run restarts at this leaf, so a short fragment + // that follows it ("AQAB", or "part: MIIEowIB") is still + // reconstructed and masked instead of surviving once the markers are + // gone (#5705). + spans.covered[i] = true + flush() + bodySeeded = true + } + material := pemBodyRuns(valBytes) + if len(material) == 0 { + flush() + continue + } + if len(material) == 1 && !allSingle { + // A one-character value must not extend a run that already holds a + // longer member, or a lone free-text character after a body line + // would be masked. Flush and restart so a body stored one character + // per member is still decided on its own joined text. + flush() + } + allSingle = allSingle && len(material) == 1 + group = append(group, i) + joined = append(joined, material...) + } + flush() +} + +// valueCarriesKeyMaterial reports whether the decoded key or string value at +// index i has to be replaced whole: it carries a block marker, or one of its runs +// holds base64 body material. +func (v *jsonProvenance) valueCarriesKeyMaterial(i int) bool { + return textCarriesKeyMaterial(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) +} + +// textCarriesKeyMaterial reports whether a decoded key or value's text carries a +// block marker or a run of base64 body material. A leaf outside those two shapes +// is free text or a schema-constrained token that a framing-spanning match only +// covers because a lazy pattern ran from one member's marker to another's, so it +// keeps its content. +func textCarriesKeyMaterial(text []byte) bool { + if privateKeyMarkerRe.Match(text) { + return true + } + // Every run is checked, not only the first. A value can prefix the body with + // a hash or an id (a "sha " 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) { + if pemBodyRun(run) { + return true + } + } + return false +} + +// pemBodyRun reports whether run looks like a line of PEM body material rather +// than a hash, an id, a file path or a long word. A base64 body mixes upper case, +// lower case and digits and carries a character outside the hex range, while a +// hex run has no base64-only character, a word such as "misconfiguration" has +// neither an upper-case letter nor a digit, and a path such as +// "internal/security/jsonsanitize" adds a slash but no upper case or digit. +// 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 { + var upper, lower, digit, base64Only bool + for _, b := range run { + switch { + case b >= 'a' && b <= 'z': + lower = true + base64Only = base64Only || b > 'f' + case b >= 'A' && b <= 'Z': + upper = true + base64Only = base64Only || b > 'F' + case b >= '0' && b <= '9': + digit = true + case b == '+' || b == '/' || b == '=': + base64Only = true + } + } + return upper && lower && digit && base64Only +} + +// pemBodyJoined reports whether the concatenated text of consecutive member +// segments looks like PEM body material. It is the check maskSpanBody applies to +// a body split across members: a chunk on its own may be shorter than the +// material floor or carry no digit, but the joined body reconstructs both. It +// still requires upper case, lower case and a base64-only character, which a hex +// SHA, a lowercase word, a path and free text do not have. +// +// A joined run is not automatically a body, though: consecutive schema values +// read as concatenated words — a finding's "critical", "ssrf" and "Makefile" join +// to "criticalssrfMakefile", which carries the case and base64 mix on its own. A +// body line is base64 of binary key material, so it scatters separate runs of +// upper-case letters through the text, while an enum or a filename the schema +// constrains is a word with a single upper-case run at most ("Makefile", +// "README", "Makefile2"). A digit alone does not separate the two: the trailing +// "2" of "Makefile2" is also a digit, and treating it as proof of key material +// masked a finding's severity, category and file. A joined run therefore needs a +// multi-letter upper-case run that is followed by lower case (hasMixedUpperRun) +// to be body material. A body split so that every such run fell into one segment +// that broke the run is not recognized +// here; such a body is still caught member by member when a member is a whole +// body line (pemBodyRun), and the alternative — treating every value between +// quoted markers as body — masked required schema fields and lost the review +// (#5705). +func pemBodyJoined(joined []byte) bool { + if len(joined) < 16 { + return false + } + var upper, lower, base64Only bool + for _, b := range joined { + switch { + case b >= 'a' && b <= 'z': + lower = true + base64Only = base64Only || b > 'f' + case b >= 'A' && b <= 'Z': + upper = true + base64Only = base64Only || b > 'F' + case b == '+' || b == '/' || b == '=': + base64Only = true + } + } + if !upper || !lower || !base64Only { + return false + } + return hasMixedUpperRun(joined) +} + +// hasMixedUpperRun reports whether text carries a run of at least two upper-case +// letters that is immediately followed by a lower-case letter. That is the shape +// base64 of binary material scatters through a line ("MIIEow", "QWERTYuiop"): +// capitals recur inside a word and are followed by lower case. A schema word or +// filename produces a single leading capital ("Makefile"), a trailing digit that +// resets the run ("Makefile2"), or an all-capitals token at the end of the word +// ("README"), and none of those is followed by lower case after a multi-letter +// run. A digit alone therefore no longer settles the question, which is what let +// "Makefile2" mask required schema fields (#5705). +func hasMixedUpperRun(text []byte) bool { + run := 0 + for _, b := range text { + switch { + case b >= 'A' && b <= 'Z': + run++ + case b >= 'a' && b <= 'z': + if run >= 2 { + return true + } + run = 0 + default: + run = 0 + } + } + return false +} + +// leafContaining returns the index of the leaf that fully contains [start, end), +// or -1 when no single leaf does. +func (v *jsonProvenance) leafContaining(start, end int) int { + for i, r := range v.ranges { + if r.start <= start && end <= r.end { + return i + } + } + return -1 +} + +// preserveTrailingNewline drops the newline json.Encoder always appends and +// restores the document's own trailing newline, so a rewrite never changes the +// file's line framing. +func preserveTrailingNewline(encoded, doc []byte) []byte { + encoded = bytes.TrimRight(encoded, "\r\n") + switch { + case bytes.HasSuffix(doc, []byte("\r\n")): + return append(encoded, '\r', '\n') + case bytes.HasSuffix(doc, []byte("\n")): + return append(encoded, '\n') + default: + return encoded + } +} + +// redactJSONOutput scans the bytes about to be written for secrets that only +// appear in the serialized form. Such a match does not map to a single leaf, so +// it is applied only when the redacted text is still valid JSON; otherwise the +// document fails closed with a valid marker. clean is returned unchanged when +// the scan finds nothing. +// +// Only whole-value patterns run here. The leaf walk has already applied the +// value patterns to the decoded document, so a value match on the re-encoded +// bytes is a redaction placeholder followed by JSON escape characters rather +// than a secret, and masking it again would drop both the placeholder's prefix +// and a non-secret backslash (#5705). +func redactJSONOutput(clean []byte, p *Pipeline) ([]byte, []Finding) { + res := p.ScanWholeValueSecrets(string(clean)) + if len(res.Findings) == 0 { + return clean, nil + } + for _, finding := range res.Findings { + // A private-key block spanning values cannot be masked in place + // without breaking the surrounding JSON. + if finding.Name == "private_key" { + return []byte(failClosedSpansMembersJSON), res.Findings + } + } + if res.Sanitized == "" || !json.Valid([]byte(res.Sanitized)) { + return []byte(failClosedInvalidJSON), res.Findings + } + return []byte(res.Sanitized), res.Findings +} + +// SanitizeJSONLines sanitizes newline-delimited JSON one record at a time, +// preserving the record framing so every line stays independently parseable. +// A secret that spans a record boundary cannot be redacted without rewriting +// that framing, so the records it covers are replaced with valid fail-closed +// markers and every other record is left as sanitized. +func SanitizeJSONLines(content []byte, p *Pipeline) ([]byte, []Finding, error) { + // A private-key block that spans records has to be detected on the original + // framing: per-record masking of a sensitive member removes the BEGIN + // marker, after which neither the record scan nor the whole-stream scan can + // recognize the block. + content, crossRecordFindings := failClosedCrossRecordPrivateKeys(content) + var ( + out bytes.Buffer + findings []Finding + spans []recordSpan + ) + findings = append(findings, crossRecordFindings...) + for len(content) > 0 { + line := content + newline := bytes.IndexByte(content, '\n') + hasNewline := newline >= 0 + if hasNewline { + line = content[:newline] + content = content[newline+1:] + } else { + content = nil + } + // Keep CRLF framing byte-for-byte for records that are not rewritten. + carriageReturn := len(line) > 0 && line[len(line)-1] == '\r' + if carriageReturn { + line = line[:len(line)-1] + } + trimmed := bytes.TrimSpace(line) + start := out.Len() + switch { + case len(trimmed) == 0: + out.Write(line) + case IsJSONDocument(trimmed): + record, recordFindings, err := SanitizeJSONDocument(trimmed, p) + if err != nil { + return nil, findings, fmt.Errorf("could not sanitize JSONL record: %w", err) + } + findings = append(findings, recordFindings...) + if len(recordFindings) > 0 { + out.Write(record) + } else { + out.Write(line) + } + spans = append(spans, recordSpan{start: start, end: out.Len()}) + default: + res := p.Scan(string(line)) + if len(res.Findings) > 0 { + findings = append(findings, res.Findings...) + out.WriteString(res.Sanitized) + } else { + out.Write(line) + } + spans = append(spans, recordSpan{start: start, end: out.Len()}) + } + if carriageReturn { + out.WriteByte('\r') + } + if hasNewline { + out.WriteByte('\n') + } + } + + rebuilt := out.Bytes() + // Rescan the rebuilt stream only for the secrets no single record can show. + // The per-record pass has already applied every value pattern to the decoded + // record, so running them again on the encoded stream re-matches a redaction + // placeholder followed by JSON escape characters: in encoded JSON a \n escape + // is two non-space bytes, which lets env_assignment run past the end of the + // decoded value and swallow the next word. Each such match replaced an + // already-correct record — and a record whose only secret was an escaped + // newline — with a cross-record marker, which is exactly the failure + // redactJSONOutput rules out for single documents (#5705). Only whole-value + // secrets (registered runtime values and private-key blocks) can still cross + // a record boundary, so only those are scanned here. + stream := p.ScanWholeValueSecrets(string(rebuilt)) + if len(stream.Findings) == 0 { + return rebuilt, findings, nil + } + // Every finding a single record could account for was handled above: a + // within-record whole-value secret is caught by SanitizeJSONDocument, and a + // private-key block crossing records by failClosedCrossRecordPrivateKeys. What + // remains spans a record boundary. + findings = append(findings, stream.Findings...) + return failClosedRecordSpans(rebuilt, spans, stream), findings, nil +} + +// recordSpan is the byte range of one non-empty JSONL record in the rebuilt +// stream, excluding its trailing newline. +type recordSpan struct { + start, end int +} + +// failClosedCrossRecordPrivateKeys replaces the records that carry part of a +// private-key block crossing record boundaries with a valid marker. Match +// offsets come from a decoded view of the whole stream, so a marker written with +// \u escapes is still recognized, and every match maps back to the records that +// carry it. +func failClosedCrossRecordPrivateKeys(content []byte) ([]byte, []Finding) { + spans := jsonLineSpans(content) + if len(spans) == 0 { + return content, nil + } + covered, findings := newJSONLineView(content, spans).spanningRecordPrivateKeys() + if len(findings) == 0 { + return content, nil + } + var out bytes.Buffer + cursor := 0 + for i, span := range spans { + if !covered[i] { + continue + } + out.Write(content[cursor:span.start]) + out.WriteString(failClosedCrossRecordJSON) + cursor = span.end + } + out.Write(content[cursor:]) + return out.Bytes(), findings +} + +// jsonLineView is an order-preserving, decoded view of a JSONL stream: every +// object key and string value of every record, in document order, with a newline +// between records so nothing a record does not contain can join its neighbours. +// The raw bytes are not usable for cross-record matching: a record may encode a +// marker with \u escapes, and a BOM-prefixed record is not valid JSON until the +// mark is stripped. +type jsonLineView struct { + decoded bytes.Buffer + // records holds each record's range in the view, excluding the separator. + records []recordSpan + // leaves holds every decoded key and string value with the record it came + // from, so a match can be mapped back to whole records. + leaves []jsonLineLeaf +} + +// jsonLineLeaf is one decoded object key or string value in a jsonLineView. +type jsonLineLeaf struct { + record int + span recordSpan + key bool + memberKey string +} + +// newJSONLineView builds the decoded view of a stream whose non-empty records +// start at spans. A record that is one JSON document contributes its decoded +// leaves; anything else contributes its raw text as a single leaf, so a stream of +// PEM text lines is still matched line by line. +func newJSONLineView(content []byte, spans []recordSpan) *jsonLineView { + view := &jsonLineView{} + for i, span := range spans { + start := view.decoded.Len() + line := content[span.start:span.end] + if body := jsonRecordBody(line); json.Valid(body) { + prov := collectJSONLeaves(body) + view.decoded.Write(prov.decoded.Bytes()) + for j, r := range prov.ranges { + view.leaves = append(view.leaves, jsonLineLeaf{ + record: i, + span: recordSpan{start: start + r.start, end: start + r.end}, + key: prov.keys[j], + memberKey: prov.memberKeys[j], + }) + } + } else { + view.decoded.Write(line) + if end := view.decoded.Len(); end > start { + view.leaves = append(view.leaves, jsonLineLeaf{record: i, span: recordSpan{start: start, end: end}}) + } + } + view.records = append(view.records, recordSpan{start: start, end: view.decoded.Len()}) + view.decoded.WriteByte('\n') + } + return view +} + +// spanningRecordPrivateKeys finds the private-key blocks in the decoded view that +// cross a record boundary and reports which records must be replaced. +// +// A block whose markers sit in different records is not proof that key material +// spans them — a transcript that quotes the header in one record and the footer +// in another matches too — so only the records the block carries content into are +// replaced. The records the match starts and ends in always carry marker text and +// are replaced; a record in between is replaced only when its leaves hold a block +// marker or PEM body material (textCarriesKeyMaterial), or when the joined text +// of consecutive leaves looks like a PEM body line (maskMiddleRecordBody). Those +// are the two shapes key material takes, while free text and structural values +// between a quoted marker pair stay readable, so a transcript of work on this very +// code is not gutted. The single-document path localizes the same way (#5705). +func (v *jsonLineView) spanningRecordPrivateKeys() ([]bool, []Finding) { + covered := make([]bool, len(v.records)) + var findings []Finding + for _, match := range privateKeyRe.FindAllIndex(v.decoded.Bytes(), -1) { + var hit []int + for i, record := range v.records { + if record.start < match[1] && match[0] < record.end { + hit = append(hit, i) + } + } + // A block confined to one record is handled by that record's own + // sanitization. + if len(hit) < 2 { + continue + } + findings = append(findings, Finding{ + Scanner: "secret_redactor", + Name: "private_key", + Severity: "critical", + Detail: "Private key block spans records; removed the records carrying block content", + }) + covered[hit[0]] = true + covered[hit[len(hit)-1]] = true + v.maskMiddleRecordBody(hit, covered) + } + return covered, findings +} + +// maskMiddleRecordBody covers the records between a cross-record block's boundary +// records when their leaves carry key material. It is the record-level counterpart +// of maskSpanBody: consecutive candidate leaves are decided together, because a +// body split so that every line is short or digit-free is only recognizable once +// the lines are joined. A leaf joins a run at any length, since the joined text is +// what has to look like a body line, except that a single-character leaf joins +// only while the run is empty or entirely single-character (see maskSpanBody), so +// an isolated single-character value keeps its content and a body stored one +// character per record is still reconstructed. An object key never joins the run, since a key +// is structure rather than body, but it does not break the run either: a body +// stored in separate object members of one record is still reconstructed. Only the +// base64 runs embedded in a leaf join the run (pemBodyRuns), so line framing, a +// "part:" prefix and the punctuation around a fragment do not break it, while a +// leaf with no base64 run at all breaks it. A key whose own name is a body line +// carries key material, so its record is covered on its own. +func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { + first, last := hit[0], hit[len(hit)-1] + var group []int + var joined []byte + // bodySeeded says the current run was restarted at a recognized body line. + bodySeeded := false + // allSingle is the JSONL counterpart of the single-document tracker: a + // one-character value only joins a run that is empty or all-single, so a + // body stored one character per record is reconstructed while an isolated + // one-character value after a body line stays free text (#5705). + allSingle := true + flush := func() { + if len(group) == 0 { + bodySeeded = false + return + } + if bodySeeded || pemBodyJoined(joined) { + for _, i := range group { + covered[v.leaves[i].record] = true + } + } + group = group[:0] + joined = joined[:0] + bodySeeded = false + allSingle = true + } + for i, leaf := range v.leaves { + // The boundary records are already covered, and their leaves neither + // extend nor join a middle run. + if leaf.record <= first || leaf.record >= last { + flush() + continue + } + text := v.decoded.Bytes()[leaf.span.start:leaf.span.end] + if leaf.key { + // A key name is structure: it never joins the run, but it must not + // break one either, so a body split across object members of the + // same record is still reconstructed. A key name that is itself + // body material covers the record on its own. + if textCarriesKeyMaterial(text) { + covered[leaf.record] = true + flush() + } + continue + } + if isSchemaConstrainedField(leaf.memberKey, string(text)) { + // Schema-constrained review fields never join candidate runs and + // break any pending run (#5705). + flush() + continue + } + if textCarriesKeyMaterial(text) { + // A recognized body line covers its own record and ends the preceding + // run, so structural values before it are not joined into a mask with + // it. The run restarts at this leaf, so a short fragment that follows + // is reconstructed and its record masked with it (#5705). + covered[leaf.record] = true + flush() + bodySeeded = true + } + material := pemBodyRuns(text) + if len(material) == 0 { + flush() + continue + } + if len(material) == 1 && !allSingle { + // See maskSpanBody: a lone one-character value must not extend a run + // that already holds a longer member, or free text after a body line + // would be masked. + flush() + } + allSingle = allSingle && len(material) == 1 + group = append(group, i) + joined = append(joined, material...) + } + flush() +} + +// jsonRecordBody returns a JSONL record's JSON body: surrounding whitespace and a +// leading UTF-8 BOM removed. encoding/json rejects a BOM, so a record carrying one +// would otherwise be read as plain text and its \u-escaped markers never decoded, +// which hid a cross-record block and left the key body behind (#5705). +func jsonRecordBody(line []byte) []byte { + return bytes.TrimSpace(bytes.TrimPrefix(bytes.TrimSpace(line), utf8BOM)) +} + +// collectJSONLeaves walks doc and records every decoded object key and string +// value, in document order, in a view where a value split across members reads as +// one contiguous run of text. Each leaf's range in that view is kept so a match +// can be mapped back to the members that carry it. +func collectJSONLeaves(doc []byte) *jsonProvenance { + prov := &jsonProvenance{} + dec := json.NewDecoder(bytes.NewReader(doc)) + dec.UseNumber() + var walkValue func(memberKey string) + walkValue = func(memberKey string) { + tok, err := dec.Token() + if err != nil { + return + } + switch t := tok.(type) { + case json.Delim: + switch t { + case '{': + for dec.More() { + keyTok, err := dec.Token() + if err != nil { + return + } + key, ok := keyTok.(string) + if !ok { + return + } + prov.addString(key, true, "") + walkValue(key) + } + _, _ = dec.Token() // consume the closing delimiter + case '[': + for dec.More() { + walkValue("") + } + _, _ = dec.Token() // consume the closing delimiter + } + case string: + prov.addString(t, false, memberKey) + } + } + walkValue("") + return prov +} + +// jsonLineSpans returns the byte range of every non-empty line in content, +// excluding its trailing CR/LF framing. +func jsonLineSpans(content []byte) []recordSpan { + var spans []recordSpan + for start := 0; start < len(content); { + end := bytes.IndexByte(content[start:], '\n') + if end < 0 { + end = len(content) + } else { + end += start + } + lineEnd := end + if lineEnd > start && content[lineEnd-1] == '\r' { + lineEnd-- + } + if len(bytes.TrimSpace(content[start:lineEnd])) > 0 { + spans = append(spans, recordSpan{start: start, end: lineEnd}) + } + start = end + 1 + } + return spans +} + +// failClosedRecordSpans replaces the records a whole-stream redaction changed +// with a valid fail-closed marker. Records the redaction did not touch are +// copied through unchanged, so two disjoint cross-record matches never discard +// the clean records between them. +// +// The per-record pass has already handled every match a single record could +// account for, so a remaining match spans a record boundary. Localization is +// conservative but per record, not all-or-nothing: inside the changed region a +// record is kept only when its bytes are unique in the stream and reappear as a +// whole newline-delimited record in the redacted stream. Locating a covered +// record means finding its bytes again in the redacted stream, which is only +// trustworthy when the record is distinct: with a repeated record, a later +// untouched copy can stand in for the copy a match covered, and the original +// bytes — carrying part of the secret — would be written back. Such a record is +// replaced. Records outside the changed region are copied through, duplicates +// included. +func failClosedRecordSpans(stream []byte, spans []recordSpan, scan ScanResult) []byte { + sanitized := []byte(scan.Sanitized) + + // Changes are confined to the region that differs between the stream and + // the redacted stream, so records outside it were not touched. + start, end := changedRegion(stream, sanitized) + counts := make(map[string]int, len(spans)) + for _, span := range spans { + counts[string(stream[span.start:span.end])]++ + } + + var out bytes.Buffer + cursor := 0 + searchFrom := 0 + for _, span := range spans { + record := stream[span.start:span.end] + if span.end <= start || span.start >= end { + // Outside the changed region: the bytes are untouched. + out.Write(stream[cursor:span.end]) + cursor = span.end + continue + } + idx := bytes.Index(sanitized[searchFrom:], record) + // A surviving copy must be a whole record, and it must be the only copy: + // otherwise a later untouched duplicate can stand in for a covered one. + if counts[string(record)] == 1 && idx >= 0 && lineBounded(sanitized, searchFrom+idx, searchFrom+idx+len(record)) { + searchFrom += idx + len(record) + out.Write(stream[cursor:span.end]) + cursor = span.end + continue + } + // The record is not present verbatim, so a match covered part of it (or + // the scan reported a finding without changing bytes, which cannot be + // localized at all). Either way it must not be written as-is. + out.Write(stream[cursor:span.start]) + out.WriteString(failClosedCrossRecordJSON) + cursor = span.end + } + out.Write(stream[cursor:]) + return out.Bytes() +} + +// changedRegion returns the half-open byte range that differs between a and b. +// It is approximate for length-changing edits, which is enough: it is used as an +// upper bound on the bytes a redaction touched. +func changedRegion(a, b []byte) (int, int) { + limit := min(len(a), len(b)) + start := 0 + for start < limit && a[start] == b[start] { + start++ + } + end := 0 + for end < limit-start && a[len(a)-1-end] == b[len(b)-1-end] { + end++ + } + return start, len(a) - end +} + +// lineBounded reports whether data[start:end] is a whole newline-delimited +// line. +func lineBounded(data []byte, start, end int) bool { + if start > 0 && data[start-1] != '\n' { + return false + } + switch { + case end == len(data), data[end] == '\n': + return true + case data[end] == '\r': + return end+1 < len(data) && data[end+1] == '\n' + default: + return false + } +} + +// rewriteJSONTokens walks every token in doc, sanitizes each object key and +// scalar value, and renders a valid JSON document. Unlike map decoding it +// keeps member order and duplicate keys, so a secret in an earlier, overwritten +// value is still found, and a secret spanning JSON framing stays visible in the +// rewritten bytes. String values that a framing-spanning private key carries key +// material into, and key names whose own text carries a block marker, are +// replaced whole, which is how such a block is neutralized member by member. +func rewriteJSONTokens(doc []byte, p *Pipeline, spans privateKeySpans) ([]byte, []Finding, error) { + dec := json.NewDecoder(bytes.NewReader(doc)) + dec.UseNumber() + var ( + buf bytes.Buffer + w = &jsonRewrite{pipeline: p, spans: spans} + ) + if err := w.writeValue(dec, &buf, ""); err != nil { + return nil, nil, fmt.Errorf("could not tokenize JSON: %w", err) + } + if _, err := dec.Token(); !errors.Is(err, io.EOF) { + return nil, nil, fmt.Errorf("unexpected trailing JSON content") + } + return buf.Bytes(), w.findings, nil +} + +// jsonRewrite is the state one token walk carries: the pipeline, the findings it +// has collected, and the keys and string values a framing-spanning private key +// covers. +type jsonRewrite struct { + pipeline *Pipeline + findings []Finding + spans privateKeySpans + // index counts the keys and string values already walked, in document + // order, so it lines up with the ranges in jsonProvenance. + index int +} + +// nextIndex advances the leaf cursor past the next key or string value and +// returns that leaf's index in the provenance view. +func (w *jsonRewrite) nextIndex() int { + i := w.index + w.index++ + return i +} + +// valueMasked reports whether the string value at index i carries part of a +// framing-spanning private key and must be replaced whole. +func (w *jsonRewrite) valueMasked(i int) bool { return w.spans.covered[i] } + +// keyMasked reports whether the object key at index i carries a block marker and +// must be replaced whole. +func (w *jsonRewrite) keyMasked(i int) bool { return w.spans.maskedKeys[i] } + +// writeValue writes one JSON value to buf, sanitizing object keys and scalar +// leaves as it goes. memberKey is the enclosing object key when the value is an +// object member, so sensitive-key masking still applies; it is empty for array +// elements and the top-level value. +func (w *jsonRewrite) writeValue(dec *json.Decoder, buf *bytes.Buffer, memberKey string) error { + tok, err := dec.Token() + if err != nil { + return err + } + switch t := tok.(type) { + case json.Delim: + return w.writeContainer(dec, buf, t) + case string: + if w.valueMasked(w.nextIndex()) { + return writeJSONString(buf, privateKeyMask) + } + sanitized, stringFindings := sanitizeJSONString(t, memberKey, w.pipeline) + w.findings = append(w.findings, stringFindings...) + return writeJSONString(buf, sanitized) + case json.Number: + literal := t.String() + res := w.pipeline.Scan(literal) + if len(res.Findings) == 0 { + buf.WriteString(literal) + return nil + } + w.findings = append(w.findings, res.Findings...) + // A redacted number is no longer a number literal, so write the + // replacement as a JSON string to keep the document valid. + return writeJSONString(buf, res.Sanitized) + case bool: + buf.WriteString(strconv.FormatBool(t)) + return nil + case nil: + buf.WriteString("null") + return nil + default: + return fmt.Errorf("unexpected JSON token %T", tok) + } +} + +// jsonMember is one object member whose value has been rendered but whose name +// is not final yet. Names are resolved once the whole object has been read so a +// sanitized name can never collide with a clean key that appears later. +type jsonMember struct { + originalKey string + sanitizedKey string + rendered []byte +} + +// writeContainer writes the members of an object or array, preserving member +// order and duplicate keys. +func (w *jsonRewrite) writeContainer(dec *json.Decoder, buf *bytes.Buffer, delim json.Delim) error { + switch delim { + case '{': + var members []jsonMember + for dec.More() { + keyTok, err := dec.Token() + if err != nil { + return err + } + key, ok := keyTok.(string) + if !ok { + return fmt.Errorf("JSON object key is %T, want string", keyTok) + } + masked := w.keyMasked(w.nextIndex()) + sanitizedKey, keyFindings := sanitizeJSONKey(key, w.pipeline) + if masked { + // The key name carried a private-key block marker, so it is + // block content rather than structure and cannot be kept. + sanitizedKey, keyFindings = privateKeyMask, nil + } + w.findings = append(w.findings, keyFindings...) + var rendered bytes.Buffer + // The original key decides whether the value is sensitive: the mask + // that replaced a key must not drag its value into json_field + // masking. + if err := w.writeValue(dec, &rendered, key); err != nil { + return err + } + members = append(members, jsonMember{ + originalKey: key, + sanitizedKey: sanitizedKey, + rendered: rendered.Bytes(), + }) + } + if _, err := dec.Token(); err != nil { // consume '}' + return err + } + assignJSONMemberNames(members) + buf.WriteByte('{') + for i, m := range members { + if i > 0 { + buf.WriteByte(',') + } + if err := writeJSONString(buf, m.sanitizedKey); err != nil { + return err + } + buf.WriteByte(':') + buf.Write(m.rendered) + } + buf.WriteByte('}') + return nil + case '[': + buf.WriteByte('[') + first := true + for dec.More() { + if !first { + buf.WriteByte(',') + } + if err := w.writeValue(dec, buf, ""); err != nil { + return err + } + first = false + } + if _, err := dec.Token(); err != nil { // consume ']' + return err + } + buf.WriteByte(']') + return nil + default: + return fmt.Errorf("unexpected JSON delimiter %q", delim.String()) + } +} + +// assignJSONMemberNames resolves the member names of one object. Clean keys keep +// their names, and a sanitized name that would collide with a different key is +// disambiguated. Repeats of the same original duplicate key keep sharing one +// name, so intentional duplicate keys survive sanitization. +func assignJSONMemberNames(members []jsonMember) { + claimed := make(map[string]string, len(members)) + for _, m := range members { + if m.sanitizedKey == m.originalKey { + claimed[m.sanitizedKey] = m.originalKey + } + } + renamed := make(map[string]string, len(members)) + for i := range members { + m := &members[i] + if m.sanitizedKey == m.originalKey { + continue + } + if target, ok := renamed[m.originalKey]; ok { + m.sanitizedKey = target + continue + } + target := m.sanitizedKey + if owner, taken := claimed[target]; taken && owner != m.originalKey { + for n := 1; ; n++ { + cand := fmt.Sprintf("%s_%d", m.sanitizedKey, n) + if _, exists := claimed[cand]; !exists { + target = cand + break + } + } + } + renamed[m.originalKey] = target + claimed[target] = m.originalKey + m.sanitizedKey = target + } +} + +// writeJSONString appends s to buf as a JSON string literal without escaping +// HTML characters, so legitimate markup survives sanitization. +func writeJSONString(buf *bytes.Buffer, s string) error { + var encoded bytes.Buffer + enc := json.NewEncoder(&encoded) + enc.SetEscapeHTML(false) + if err := enc.Encode(s); err != nil { + return err + } + buf.Write(bytes.TrimSuffix(encoded.Bytes(), []byte("\n"))) + return nil +} + +// sanitizeJSONKey sanitizes one object key. A key whose sanitized value is +// empty was removed entirely, so it is replaced with a placeholder rather than +// kept as-is. +func sanitizeJSONKey(key string, p *Pipeline) (string, []Finding) { + res := p.Scan(key) + if len(res.Findings) == 0 { + return key, nil + } + sanitized := res.Sanitized + if sanitized == "" { + sanitized = redactedJSONKey + } + return sanitized, res.Findings +} + +// sanitizeJSONString sanitizes one string leaf. memberKey is the enclosing +// object key, used to mask values whose key name marks them as sensitive even +// when the value itself matches no secret pattern. +func sanitizeJSONString(value, memberKey string, p *Pipeline) (string, []Finding) { + res := p.Scan(value) + out := value + var findings []Finding + rewritten := len(res.Findings) > 0 + if rewritten { + findings = append(findings, res.Findings...) + out = res.Sanitized + } + // Sensitivity is decided on the key as the leaf scan sees it: invisible + // characters stripped and compatibility forms folded, the same normalization + // sanitizeJSONKey applies when it writes the name back. Testing the original + // spelling let a key such as "pass\u200bword" be written as "password" with an + // untouched value (#5705). + key := normalizedJSONKey(memberKey) + // #9944: an "author" member holding a codex agent path is not a credential, + // although "author" contains the "auth" trigger word. The text pipeline + // honours this exemption; the structural path must too, because a codex + // transcript is a JSON document and takes that path. + exempt := strings.EqualFold(key, "author") && authorPathValue.MatchString(out) + // isAlreadyMasked is only trusted for a value this scan actually rewrote: + // the placeholder shape is also a real short-secret shape, so an original + // value must still be masked even when it looks like one (#5705). + if key != "" && !exempt && sensitiveJSONKeyRe.MatchString(key) && + !(rewritten && isAlreadyMasked(out)) && + utf8.RuneCountInString(out) >= minJSONFieldLen { + masked := Mask(out) + findings = append(findings, Finding{ + Scanner: "secret_redactor", + Name: "json_field", + Severity: "high", + Detail: fmt.Sprintf("Redacted json_field (%d chars) -> %s", utf8.RuneCountInString(out), masked), + }) + out = masked + } + return out, findings +} + +// normalizedJSONKey returns key as the leaf scan sees it: invisible characters +// stripped and compatibility forms folded, exactly as sanitizeJSONKey normalizes +// the name it writes back. Sensitivity has to be checked on this spelling, or a +// zero-width or fullwidth obfuscated sensitive key becomes an explicitly +// sensitive field with an untouched value (#5705). +func normalizedJSONKey(key string) string { + if key == "" { + return "" + } + return decodedViewNormalizer.Scan(key).Sanitized +} diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go new file mode 100644 index 0000000000..3fab65188d --- /dev/null +++ b/internal/security/jsonsanitize_test.go @@ -0,0 +1,2131 @@ +package security + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// pemBegin and pemEnd are the marker strings under test. They are split at +// definition so a source scan of the test files does not treat this as key +// material, and defined once so a marker-shape change cannot leave one fixture +// testing a different shape than the others. +var ( + pemBegin = "-----BEGIN RSA" + " PRIVATE KEY-----" + pemEnd = "-----END RSA" + " PRIVATE KEY-----" +) + +// TestSanitizeJSONDocument_DuplicateKeyEarlierOccurrenceRedacted pins that a +// secret in an earlier, overwritten duplicate-key occurrence is still found. +// Map decoding drops that occurrence, so only a token-preserving walk sees it. +func TestSanitizeJSONDocument_DuplicateKeyEarlierOccurrenceRedacted(t *testing.T) { + p := OutputPipeline() + // \u0067 decodes to "g"; the raw text never contains "ghp_". + escapedSecret := `\u0067hp_FAKEtesttoken000000000000000000000000` + doc := []byte(`{"note":"` + escapedSecret + `","note":"clean"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized duplicate-key JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + assert.NotContains(t, string(out), `\u0067hp_`) + assert.Contains(t, string(out), `"note":"clean"`, "the surviving duplicate value must be preserved") +} + +// TestSanitizeJSONDocument_DuplicateKeysSurviveRewrite pins that the +// token-preserving walk keeps duplicate keys and their order when another +// member forces a rewrite. +func TestSanitizeJSONDocument_DuplicateKeysSurviveRewrite(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"a":1,"a":2,"token":"ghp_FAKEtesttoken000000000000000000000000"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.Contains(t, string(out), `"a":1,"a":2`, "duplicate members must keep their order") + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersMasksCoveredMembers pins +// that a private key spread over several members is neutralized member by member +// instead of dropping the whole document. Scanning only the re-encoded form +// missed the block: encoding a map sorts keys, and with the END marker sorted +// before the BEGIN marker the pattern no longer matched the original key +// material. Dropping the document was the other extreme — a review result lost +// its verdict with it (#5705). +func TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersMasksCoveredMembers(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + // Reverse the members' sort order so a map re-encode would emit END before + // BEGIN and hide the block from a serialized scan. + doc := []byte(`{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `","verdict":"approve"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "a framing-spanning private key must produce a finding") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "BEGIN RSA") + assert.NotContains(t, string(out), "MIIEpAIBAAKCAQEA") + assert.NotContains(t, string(out), "output removed", "the document must be kept, not dropped") + assert.Contains(t, string(out), `"verdict":"approve"`, "a member outside the block must survive") + assert.Contains(t, string(out), `"z_begin":`, "key names are structure and must survive") + assert.Contains(t, string(out), `"m_body":`) + assert.Contains(t, string(out), `"a_end":`) +} + +// TestSanitizeJSONDocument_HexPrefixBeforeBodyMaterialMasked pins the regression +// a reviewer found: only the first material run in a value was examined, so a +// value that put a hash before the body ("sha ") returned false at +// the hex run. The markers were masked, the body was written back, and the +// written-bytes rescan could not catch it because the markers were gone (#5705). +func TestSanitizeJSONDocument_HexPrefixBeforeBodyMaterialMasked(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + body := "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcw" + doc := []byte(`{"a":"` + begin + `","b":"sha 0123456789abcdef0123 ` + body + `","c":"` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), body, "a body after a hex prefix must not survive") + assert.NotContains(t, string(out), "0123456789abcdef0123", "the member carrying the block is replaced whole") + + var result struct { + B string `json:"b"` + } + require.NoError(t, json.Unmarshal(out, &result)) + assert.Equal(t, privateKeyMask, result.B, "the member carrying the block is masked") +} + +// TestSanitizeJSONDocument_PathsAndProseBetweenMarkersStayReadable pins the other +// regression a reviewer found: a file path and a long word both reach the +// material floor, so a path such as "internal/security/jsonsanitize" or a word +// such as "misconfiguration" was masked as key material. A quoted marker pair +// carries no secret, and the review has to keep the values its schema requires +// (#5705). +func TestSanitizeJSONDocument_PathsAndProseBetweenMarkersStayReadable(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + path := "internal/security/jsonsanitize" + prose := "a misconfiguration here" + doc := []byte(`{"action":"comment","pr_number":12,"repo":"acme/widgets",` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","findings":[` + + `{"severity":"high","category":"logic-error","file":"a.go","description":"quotes the ` + begin + ` header"},` + + `{"severity":"medium","category":"missing-test","file":"` + path + `","description":"` + prose + `"},` + + `{"severity":"low","category":"stale-doc","file":"c.go","description":"quotes the ` + end + ` footer"}],"body":"summary"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "the cross-member marker pair is still reported") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----") + assertReviewResultSchemaValid(t, out) + + var result struct { + Findings []struct { + Severity string `json:"severity"` + File string `json:"file"` + Description string `json:"description"` + } `json:"findings"` + } + require.NoError(t, json.Unmarshal(out, &result), "the sanitized review must still decode: %s", out) + require.Len(t, result.Findings, 3) + assert.Equal(t, path, result.Findings[1].File, "a path is not PEM body material") + assert.Equal(t, prose, result.Findings[1].Description, "a long word is not PEM body material") + assert.Equal(t, "medium", result.Findings[1].Severity, "the structural enum keeps its value") + assert.Equal(t, privateKeyMask, result.Findings[0].Description, "the value carrying the header is masked") + assert.Equal(t, privateKeyMask, result.Findings[2].Description, "the value carrying the footer is masked") +} + +// TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview pins the +// regression a reviewer found: a review result that quotes the PEM header in one +// finding and the footer in another matches the lazy private-key pattern across +// members, but nothing is hidden and the review still has to be posted. Only the +// values that carry a marker or key material are masked, so the structural values +// the review schema constrains keep theirs — action, repo, severity and category +// included — and the sanitized document still validates against +// schemas/review-result.schema.json. Masking every covered value instead replaced +// those enums with the block marker, so validation failed and the review was not +// posted, which is the #5705 outcome (#5705). +func TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN" + " PRIVATE KEY-----" + end := "-----END" + " PRIVATE KEY-----" + doc := []byte(`{"action":"comment","pr_number":12,"repo":"acme/widgets",` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01",` + + `"findings":[` + + `{"severity":"high","category":"logic-error","file":"a.go","description":"quotes the ` + begin + ` header"},` + + `{"severity":"medium","category":"missing-test","file":"b.go","description":"a finding between the markers"},` + + `{"severity":"low","category":"stale-doc","file":"c.go","description":"quotes the ` + end + ` footer"},` + + `{"severity":"info","category":"doc-style","file":"d.go","description":"a finding after the block"}],"body":"summary"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "the cross-member marker pair is still reported") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "output removed", "the review must not be dropped whole") + assert.NotContains(t, string(out), "PRIVATE KEY-----") + + // The blocking requirement: the sanitized review still satisfies the schema + // the harness validates before post-review runs. + assertReviewResultSchemaValid(t, out) + + var result struct { + Action string `json:"action"` + PRNumber int `json:"pr_number"` + Repo string `json:"repo"` + Body string `json:"body"` + Findings []struct { + Severity string `json:"severity"` + Category string `json:"category"` + File string `json:"file"` + Description string `json:"description"` + } `json:"findings"` + } + require.NoError(t, json.Unmarshal(out, &result), "the sanitized review must still decode: %s", out) + assert.Equal(t, "comment", result.Action, "the action must survive") + assert.Equal(t, 12, result.PRNumber) + assert.Equal(t, "acme/widgets", result.Repo) + assert.Equal(t, "summary", result.Body, "a field outside the matched span keeps its content") + require.Len(t, result.Findings, 4, "every finding must survive") + + // Only the values that carry a marker are masked; the free text between the + // quoted markers is not key material and keeps its content. + assert.Equal(t, "high", result.Findings[0].Severity, "a structural enum before the match keeps its value") + assert.Equal(t, "a.go", result.Findings[0].File, "a value before the match keeps its content") + assert.Equal(t, privateKeyMask, result.Findings[0].Description, "the value carrying the marker is masked") + assert.Equal(t, "a finding between the markers", result.Findings[1].Description, + "free text between a quoted marker pair is not key material") + assert.Equal(t, privateKeyMask, result.Findings[2].Description, "the value carrying the footer is masked") + assert.Equal(t, "d.go", result.Findings[3].File, "a finding after the footer is outside the span") + assert.Equal(t, "a finding after the block", result.Findings[3].Description) +} + +// TestSanitizeJSONDocument_KeyMaterialInSpanKeepsStructuralEnums pins the other +// half of the rule: when the block really is split across members, the values +// carrying key material are masked, while the structural values the review schema +// constrains keep theirs so the review can still be posted (#5705). +func TestSanitizeJSONDocument_KeyMaterialInSpanKeepsStructuralEnums(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"action":"request-changes","pr_number":12,"repo":"acme/widgets",` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","findings":[` + + `{"severity":"high","category":"secret-exposure","file":"a.go","description":"leaked ` + begin + `"},` + + `{"severity":"high","category":"secret-exposure","file":"b.go","description":"MIIEpAIBAAKCAQEA0123456789abcdef"},` + + `{"severity":"high","category":"secret-exposure","file":"c.go","description":"and ` + end + `"}],"body":"remove it"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "output removed", "the review must not be dropped whole") + assert.NotContains(t, string(out), "PRIVATE KEY-----") + assert.NotContains(t, string(out), "MIIEpAIBAAKCAQEA", "the key material must not survive") + assertReviewResultSchemaValid(t, out) + + var result struct { + Findings []struct { + Severity string `json:"severity"` + Category string `json:"category"` + File string `json:"file"` + Description string `json:"description"` + } `json:"findings"` + } + require.NoError(t, json.Unmarshal(out, &result)) + require.Len(t, result.Findings, 3) + for i, finding := range result.Findings { + assert.Equal(t, "high", finding.Severity, "finding %d must keep its severity enum", i) + assert.Equal(t, "secret-exposure", finding.Category, "finding %d must keep its category enum", i) + assert.NotEmpty(t, finding.File, "finding %d must keep its file", i) + assert.NotEmpty(t, finding.Description, "finding %d must keep its description", i) + } +} + +// TestSanitizeJSONDocument_MarkerSplitAcrossMembersMasked pins that a marker +// written in pieces does not survive: the leaves the match starts and ends in are +// always masked, and a value carrying only a marker fragment is masked too, so no +// piece of the block header or footer is written back (#5705). +func TestSanitizeJSONDocument_MarkerSplitAcrossMembersMasked(t *testing.T) { + p := OutputPipeline() + doc := []byte(`["-----BEGIN"," RSA PRIVATE KEY-----","MIIEb2R5","-----END"," RSA PRIVATE KEY-----"]`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "-----BEGIN") + assert.NotContains(t, string(out), "-----END") + assert.NotContains(t, string(out), "PRIVATE KEY-----") +} + +// TestSanitizeJSONDocument_SchemaFieldsBetweenQuotedMarkersKept pins the other +// side of the joined-run rule: the values between a quoted header and footer are +// not body material just because they are consecutive. A finding's severity, +// category and file join into "criticalssrfMakefile", which carries the case and +// base64 mix a body line has, and masking them failed the review schema and lost +// the review — the outcome this change exists to prevent (#5705). +func TestSanitizeJSONDocument_SchemaFieldsBetweenQuotedMarkersKept(t *testing.T) { + p := OutputPipeline() + // A filename is a word, not key material: a trailing digit ("Makefile2") or + // an all-capitals name ("README") must not tip the joined run into a mask + // that drops severity, category and file and fails schema validation + // (#5705). + for _, file := range []string{"Makefile", "Makefile2", "README", "LICENSE"} { + t.Run(file, func(t *testing.T) { + doc := []byte(`{"action":"comment","repo":"acme/widgets","pr_number":12,` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","body":"quotes a key",` + + `"findings":[` + + `{"severity":"high","category":"logic-error","file":"a.go","description":"quotes the ` + pemBegin + ` header"},` + + `{"severity":"critical","category":"ssrf","file":"` + file + `","description":"quotes the ` + pemEnd + ` footer"}]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----", "the markers themselves are masked") + assert.Contains(t, string(out), `"severity":"critical"`, "a schema value is not body material") + assert.Contains(t, string(out), `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, string(out), `"file":"`+file+`"`, "a schema value is not body material") + assertReviewResultSchemaValid(t, out) + }) + } +} + +// TestSanitizeJSONDocument_SchemaFieldsInReversedOrderKept pins that schema +// fields appearing in any key order (for example, "file" before "category" and +// "severity") are recognized as structure rather than candidate key material, +// so an all-caps filename like README before an enum like ssrf does not join into +// an apparent mixed-upper run (#5705). +func TestSanitizeJSONDocument_SchemaFieldsInReversedOrderKept(t *testing.T) { + p := OutputPipeline() + for _, file := range []string{"README", "LICENSE", "Makefile", "Makefile2"} { + t.Run(file, func(t *testing.T) { + doc := []byte(`{"action":"comment","repo":"acme/widgets","pr_number":12,` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","body":"quotes a key",` + + `"findings":[` + + `{"description":"quotes the ` + pemBegin + ` header","file":"a.go","category":"logic-error","severity":"high"},` + + `{"file":"` + file + `","category":"ssrf","severity":"critical","description":"quotes the ` + pemEnd + ` footer"}]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----", "the markers themselves are masked") + assert.Contains(t, string(out), `"severity":"critical"`, "a schema value is not body material") + assert.Contains(t, string(out), `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, string(out), `"file":"`+file+`"`, "a schema value is not body material") + assertReviewResultSchemaValid(t, out) + }) + } +} + +// TestSanitizeJSONDocument_ShortBodyChunksMasked pins that a body split into +// chunks shorter than the material floor is still masked. Each chunk is too short +// for the per-value test, so the run is decided on its joined text and every +// contributing chunk is covered; a length floor per chunk let the body survive +// once the boundary markers were masked (#5705). +func TestSanitizeJSONDocument_ShortBodyChunksMasked(t *testing.T) { + p := OutputPipeline() + chunks := []string{"MII", "Eow", "IB", "AAK", "CAQ", "EA"} + quoted := []string{`"` + pemBegin + `"`} + for _, chunk := range chunks { + quoted = append(quoted, `"`+chunk+`"`) + } + quoted = append(quoted, `"`+pemEnd+`"`) + doc := []byte(`{"lines":[` + strings.Join(quoted, ",") + `]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + for _, chunk := range chunks { + assert.NotContains(t, string(out), chunk, "a short body chunk must not survive") + } + assert.NotContains(t, string(out), "PRIVATE KEY-----") +} + +// TestSanitizeJSONDocument_ChunkedBodyBetweenMarkersMasked pins the regression a +// reviewer found: a body split across members into chunks that are each short, +// digit-free, or hex-looking was written back after the boundary markers were +// masked, where the written-bytes rescan can no longer see the block. The joined +// text of consecutive values reconstructs the body, so every chunk is masked +// (#5705). +func TestSanitizeJSONDocument_ChunkedBodyBetweenMarkersMasked(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + cases := map[string][]string{ + "short chunks": {"MIIEowIB", "AAKCAQEA", "x9Kq2Lm"}, + "digit-free chunk": {"MIIEowIBAAKCAQEA"}, + "hex chunk in the run": {"MIIEowIBAAKCAQEA", "abcdef0123456789", "short+chunk"}, + } + for name, chunks := range cases { + t.Run(name, func(t *testing.T) { + quoted := make([]string, 0, len(chunks)+2) + quoted = append(quoted, `"`+begin+`"`) + for _, chunk := range chunks { + quoted = append(quoted, `"`+chunk+`"`) + } + quoted = append(quoted, `"`+end+`"`) + doc := []byte(`{"lines":[` + strings.Join(quoted, ",") + `]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----") + for _, chunk := range chunks { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } + }) + } +} + +// TestSanitizeJSONDocument_HexValuesInSpanKeepTheirContent pins that a hex run +// inside a quoted marker span is not treated as key material. A commit SHA or a +// finding id is schema-constrained (head_sha, id), and a PEM body is base64, so a +// hex-only run is far more likely a hash than a PEM line (#5705). +func TestSanitizeJSONDocument_HexValuesInSpanKeepTheirContent(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"action":"comment","pr_number":12,"repo":"acme/widgets","findings":[` + + `{"severity":"high","category":"logic-error","file":"a.go","id":"f_0123456789abcdef0123456789abcdef","description":"quotes the ` + begin + ` header"},` + + `{"severity":"low","category":"doc-style","file":"b.go","id":"f_0123456789abcdef0123456789abcdef","description":"and the ` + end + ` footer"}],` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","body":"summary"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.Contains(t, string(out), `"head_sha":"abcdef0123456789abcdef0123456789abcdef01"`, + "a commit SHA is not PEM body material") + assert.Contains(t, string(out), `"id":"f_0123456789abcdef0123456789abcdef"`, + "a finding id is not PEM body material") + assert.NotContains(t, string(out), "PRIVATE KEY-----") +} + +// TestSanitizeJSONDocument_KeyNameCarryingMarkerIsMasked pins the other half of +// the key rule: a key name is structure and keeps its name, unless the name itself +// carries a block marker. Then the name is block content and cannot be written +// back, while a sibling key between the markers still keeps its name (#5705). +func TestSanitizeJSONDocument_KeyNameCarryingMarkerIsMasked(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"` + begin + `":"x","severity":"high","` + end + `":"y"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "BEGIN RSA") + assert.NotContains(t, string(out), "END RSA") + assert.Contains(t, string(out), `"severity":`, "a key name between the markers keeps its name") +} + +// TestJSONProvenance_KeysAreStructure pins that the decoded view records which +// leaves are object keys, that a spanning block only covers string values, and +// that a value between the markers is covered only when it carries key material, +// so the rewrite never renames a key unless its own text carries a marker. +func TestJSONProvenance_KeysAreStructure(t *testing.T) { + begin := pemBegin + end := pemEnd + doc := []byte(`{"severity":"` + begin + `","category":"MIIEpAIBAAKCAQEA0123456789abcdef","body":"x","file":"` + end + `"}`) + + prov := collectJSONLeaves(doc) + require.Equal(t, len(prov.ranges), len(prov.keys), "every recorded leaf must carry a kind") + spans := prov.spanningPrivateKeys() + require.Equal(t, 1, spans.localized) + assert.Empty(t, spans.maskedKeys, "no key name carries a marker") + require.Len(t, spans.covered, 3, "the marker and the key-material values are covered") + for i := range spans.covered { + assert.False(t, prov.keys[i], "only string values are covered") + } + assert.False(t, spans.covered[5], "free text between the markers is not key material") +} + +// TestSanitizeJSONDocument_BodyLineAsKeyBetweenMarkersMasked pins that a key name +// which is itself a body line is key material, not structure. Once the boundary +// markers are masked the written-bytes rescan can no longer see the block, so a +// body kept in a key name would be written back unmasked (#5705). +func TestSanitizeJSONDocument_BodyLineAsKeyBetweenMarkersMasked(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + const body = "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + doc := []byte(`{"` + begin + `":1,"` + body + `":2,"` + end + `":3}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), body, "a body line in a key name is key material") + assert.NotContains(t, string(out), "BEGIN RSA") + assert.NotContains(t, string(out), "END RSA") +} + +// TestSanitizeJSONDocument_StructuralKeysKeepNamesNextToMaterial pins the other +// side of the same rule: a structural key between the markers keeps its name even +// when the values around it carry body material. Letting a key join the +// joined-run test would rename required schema keys and drop the review (#5705). +func TestSanitizeJSONDocument_StructuralKeysKeepNamesNextToMaterial(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"` + begin + `":"x","severity":"high","category":"logic-error",` + + `"body":"MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez","` + end + `":"y"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + for _, key := range []string{`"severity":`, `"category":`, `"body":`} { + assert.Contains(t, string(out), key, "a structural key keeps its name") + } + assert.NotContains(t, string(out), "x7Qz9restOfTheBodyWq1Ez", "the body material is masked") +} + +// TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed pins that a +// document with no leaf findings is still scanned in its written form. A +// runtime secret spanning two member boundaries is visible only in the raw +// bytes, and the previous no-findings path returned those bytes untouched. +func TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const secret = `","field2":"` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + doc := []byte(`{"field1":"foo","field2":"bar"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "a framing-spanning secret must produce a finding") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), secret) +} + +// TestSanitizeJSONDocument_CrossMemberPrivateKeyWithLeafSecret pins that a leaf +// secret and a framing-spanning private key in the same document are both +// handled: the rewrite keeps member order, and the members carrying the block +// are masked while the rest of the document survives. +func TestSanitizeJSONDocument_CrossMemberPrivateKeyWithLeafSecret(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `",` + + `"token":"ghp_FAKEtesttoken000000000000000000000000","verdict":"approve"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + assert.NotContains(t, string(out), "PRIVATE KEY-----") + assert.Contains(t, string(out), `"verdict":"approve"`, "a member outside the block must survive") +} + +// TestSanitizeJSONDocument_DuplicateKeySanitizedKeyCollision pins that a +// sanitized key never steals the name of an existing clean member, and that +// intentional duplicate keys still survive. +func TestSanitizeJSONDocument_DuplicateKeySanitizedKeyCollision(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const secret = "abcdefghijk" + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + doc := []byte(`{"` + secret + `":1,"***":2,"d":0,"d":1}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), secret) + + var decoded map[string]any + require.NoError(t, json.Unmarshal(out, &decoded)) + assert.Equal(t, float64(2), decoded["***"], "the clean key must keep its own value") + assert.Equal(t, float64(1), decoded["***_1"], "the sanitized key must be disambiguated") + assert.Equal(t, 2, strings.Count(string(out), `"d":`), "intentional duplicate keys must survive") +} + +// TestSanitizeJSONLines_CrossRecordRuntimeSecretFailsClosed pins that a +// runtime secret spanning two individually valid records is not discarded. +func TestSanitizeJSONLines_CrossRecordRuntimeSecretFailsClosed(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const secret = `one"}` + "\n" + `{"key` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + content := []byte("{\"key_one\":\"one\"}\n{\"key_two\":\"two\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), secret, "the cross-record secret must not survive") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 2, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONLines_RedactedAssignmentBeforeEscapedNewlineKeepsRecord pins +// that the whole-stream rescan cannot re-match a value the per-record pass +// already redacted. In encoded JSON a \n escape is two non-space bytes, so +// running env_assignment over the rebuilt stream matched the placeholder plus +// the next word, and the correctly redacted record was replaced with a +// cross-record marker — a false alarm that dropped real content from +// transcripts/*.jsonl and output.jsonl (#5705). +func TestSanitizeJSONLines_RedactedAssignmentBeforeEscapedNewlineKeepsRecord(t *testing.T) { + p := OutputPipeline() + content := []byte(`{"type":"assistant","text":"run: API_KEY=supersecretvalue123\nnext line"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.Len(t, findings, 1, "one secret must be reported once, not recounted by the stream rescan: %+v", findings) + assert.Equal(t, "env_assignment", findings[0].Name) + + line := strings.TrimSpace(string(out)) + assert.True(t, json.Valid([]byte(line)), "the record must stay valid JSON: %s", line) + assert.NotContains(t, line, "output removed", "a redacted record must not be replaced") + assert.NotContains(t, line, "supersecretvalue123") + assert.Contains(t, line, "next line", "the text after the escaped newline must survive") +} + +// TestSanitizeJSONLines_BenignEscapedAssignmentKeepsRecord pins the benign half +// of the same regression: a shell command with an escaped newline contains no +// secret at all, and the per-record pass leaves it alone (#5705). +func TestSanitizeJSONLines_BenignEscapedAssignmentKeepsRecord(t *testing.T) { + p := OutputPipeline() + content := []byte(`{"text":"export GITHUB_TOKEN=$TOKEN\nnext line"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.Empty(t, findings, "no secret is present, so nothing may be reported") + assert.Equal(t, string(content), string(out), "a benign record must be written back unchanged") +} + +// only the records a cross-record match touches are replaced. A single +// first-to-last changed region used to swallow every record between two +// disjoint matches. +func TestSanitizeJSONLines_DisjointCrossRecordMatchesKeepCleanRecord(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const first = `one"}` + "\n" + `{"b` + const second = `three"}` + "\n" + `{"d` + require.True(t, RegisterRuntimeSecret(first)) + require.True(t, RegisterRuntimeSecret(second)) + + p := OutputPipeline() + content := []byte( + "{\"a\":\"one\"}\n" + + "{\"b\":\"two\"}\n" + + "{\"clean\":\"middle\"}\n" + + "{\"c\":\"three\"}\n" + + "{\"d\":\"four\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), first) + assert.NotContains(t, string(out), second) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 5, "record count must not change") + assert.Equal(t, `{"clean":"middle"}`, lines[2], "the clean record between two matches must survive") + for _, i := range []int{0, 1, 3, 4} { + assert.True(t, json.Valid([]byte(lines[i])), "each replaced record must stay valid JSON: %s", lines[i]) + assert.Contains(t, lines[i], "output removed") + } +} + +// TestSanitizeJSONDocument_BackstopKeepsEarlierMask pins that the +// serialized-bytes backstop never masks a redaction placeholder a second time. +// The leaf pass masked part of an escaped sequence, so re-encoding left the +// placeholder followed by doubled backslashes. A value pattern captured that +// tail, found no complete mask, and masked again — dropping the informative +// prefix and a non-secret backslash, and logging a duplicate finding (#5705). +func TestSanitizeJSONDocument_BackstopKeepsEarlierMask(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"body":"x token_usage = metrics.get(\\\"token_usage\\\") or {}"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.Len(t, findings, 1, "only the leaf match may be reported: %+v", findings) + assert.Equal(t, "env_assignment", findings[0].Name) + + var decoded struct { + Body string `json:"body"` + } + require.NoError(t, json.Unmarshal(out, &decoded)) + assert.Equal(t, `x token_usage = metr...\"token_usage\") or {}`, decoded.Body, + "the earlier mask and the non-secret backslashes must survive") +} + +// TestSanitizeJSONDocument_BackstopRedactsSecondRuntimeSecret pins that a +// runtime secret exposed only by serializing the parsed document is still +// handled when another runtime secret was already found in a leaf. +func TestSanitizeJSONDocument_BackstopRedactsSecondRuntimeSecret(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const leafSecret = "leafonlysecretvalue" + const serializedSecret = `","field2":"` + require.True(t, RegisterRuntimeSecret(leafSecret)) + require.True(t, RegisterRuntimeSecret(serializedSecret)) + + p := OutputPipeline() + doc := []byte(`{"field1":"leafonlysecretvalue","field2":"bar"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), leafSecret) + assert.NotContains(t, string(out), serializedSecret) +} + +// TestSanitizeJSONDocument_KeyRemovedEntirelyIsReplaced pins that a JSON key +// made only of removable characters never survives sanitization. +func TestSanitizeJSONDocument_KeyRemovedEntirelyIsReplaced(t *testing.T) { + p := OutputPipeline() + for name, key := range map[string]string{ + "null byte": "\x00", + "bidi override": "\u202e", + } { + t.Run(name, func(t *testing.T) { + doc, err := json.Marshal(map[string]string{key: "value"}) + require.NoError(t, err) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), `\u0000`) + assert.NotContains(t, string(out), `\u202e`) + + var decoded map[string]string + require.NoError(t, json.Unmarshal(out, &decoded)) + assert.Equal(t, "value", decoded[redactedJSONKey]) + }) + } +} + +// TestSanitizeJSONLines_SingleRecordPEMKeepsCleanRecords pins that a private +// key confined to one record is redacted in place instead of replacing every +// record in the file. +func TestSanitizeJSONLines_SingleRecordPEMKeepsCleanRecords(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte( + "{\"event\":\"clean-before\"}\n" + + "{\"tool\":\"read\",\"text\":\"" + begin + "\\nMIIEpAIBAAKCAQEA0123456789abcdef\\n" + end + "\"}\n" + + "{\"event\":\"clean-after\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + assert.Equal(t, `{"event":"clean-before"}`, lines[0], "clean records must be untouched") + assert.Equal(t, `{"event":"clean-after"}`, lines[2], "clean records must be untouched") + assert.True(t, json.Valid([]byte(lines[1]))) + assert.NotContains(t, lines[1], "BEGIN RSA") + assert.NotContains(t, lines[1], "MIIEpAIBAAKCAQEA") +} + +// TestOutputRemoval pins the markers recognized as a whole-file replacement and +// the reason reported for the operator alert. +func TestOutputRemoval(t *testing.T) { + for name, tc := range map[string]struct { + input string + reason string + removed bool + }{ + "invalid json": {failClosedInvalidJSON + "\n", "redaction would invalidate JSON", true}, + "cross-record": {failClosedCrossRecordJSON, "a secret spanned multiple records", true}, + "spans members": {failClosedSpansMembersJSON, "a private key block spans JSON framing", true}, + "unwritable": {FailClosedUnwritableJSON, "it could not be redacted", true}, + "bom prefixed": {"\ufeff" + failClosedSpansMembersJSON, "a private key block spans JSON framing", true}, + "bom and space": {"\ufeff " + failClosedInvalidJSON + "\r\n", "redaction would invalidate JSON", true}, + "ordinary doc": {`{"error":"not a removal marker"}`, "", false}, + "not json": {"plain prose", "", false}, + "empty": {"", "", false}, + } { + t.Run(name, func(t *testing.T) { + reason, removed := OutputRemoval([]byte(tc.input)) + assert.Equal(t, tc.removed, removed) + assert.Equal(t, tc.reason, reason) + }) + } +} + +// TestOutputRecordRemovals pins that a JSONL stream whose records were replaced +// reports each distinct reason once. A replaced record keeps the file's framing, +// so the file never equals a whole-file marker, and this is how its loss reaches +// an operator (#5705). +func TestOutputRecordRemovals(t *testing.T) { + stream := []byte( + `{"event":"clean"}` + "\n" + + failClosedCrossRecordJSON + "\r\n" + + failClosedCrossRecordJSON + "\n" + + failClosedSpansMembersJSON + "\n") + assert.Equal(t, + []string{"a secret spanned multiple records", "a private key block spans JSON framing"}, + OutputRecordRemovals(stream)) + assert.Empty(t, OutputRecordRemovals([]byte(`{"event":"clean"}`+"\n"))) +} + +// TestOutputRecordRemovals_BOMFirstRecord pins that a replaced first record keeps +// the BOM its line carried, and that the mark does not hide the loss: the record +// is still reported, so the operator alert is not skipped (#5705). +func TestOutputRecordRemovals_BOMFirstRecord(t *testing.T) { + stream := []byte("\ufeff" + failClosedCrossRecordJSON + "\n" + `{"event":"clean"}` + "\n") + assert.Equal(t, + []string{"a secret spanned multiple records"}, + OutputRecordRemovals(stream)) +} + +// TestJSONProvenance_UnmappableBlock pins the defensive fallback: a block that no +// recorded leaf range covers is reported as unmappable so the caller fails +// closed instead of writing bytes that may still carry it. +func TestJSONProvenance_UnmappableBlock(t *testing.T) { + begin := pemBegin + end := pemEnd + v := &jsonProvenance{} + v.decoded.WriteString(begin + "\n" + "MIIEkeymaterial" + "\n" + end + "\n") + // One empty string value, which can never overlap a match. + v.ranges = []recordSpan{{start: 0, end: 0}} + v.keys = []bool{false} + + spans := v.spanningPrivateKeys() + assert.Equal(t, 1, spans.unmappable) + assert.Zero(t, spans.localized) + assert.Empty(t, spans.covered) + assert.Empty(t, spans.maskedKeys) +} + +// TestSanitizeJSONDocument_AlreadyMaskedValueNotRemasked pins that rescanning a +// document leaves an existing mask placeholder intact. +func TestSanitizeJSONDocument_AlreadyMaskedValueNotRemasked(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"body":"Guard against null values with token_usage = metrics.get(\"token_usage\") or {}"}`) + + first, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.Len(t, findings, 1, "one secret must produce one finding") + assert.Contains(t, string(first), "metr...", "the informative prefix must be retained") + + second, findings, err := SanitizeJSONDocument(first, p) + require.NoError(t, err) + assert.Empty(t, findings, "rescanning a sanitized document must be idempotent") + assert.Equal(t, first, second) +} + +// TestSanitizeJSONDocument_DuplicateKeyNestedContainers covers the +// token-preserving walk across nested objects, arrays, every scalar type, and +// an escaped duplicate key whose value is a container. +func TestSanitizeJSONDocument_DuplicateKeyNestedContainers(t *testing.T) { + p := OutputPipeline() + escapedSecret := `\u0067hp_FAKEtesttoken000000000000000000000000` + doc := []byte(`{"outer":[{"id":1,"id":2,"opts":{"flag":true,"none":null,"ratio":1.5}},` + + `{"token":"` + escapedSecret + `","token":["clean"]}],"tail":false}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + + var decoded any + require.NoError(t, json.Unmarshal(out, &decoded)) + outer := decoded.(map[string]any)["outer"].([]any) + second := outer[1].(map[string]any) + // The duplicate-key walk keeps the later occurrence, which is the array. + assert.Equal(t, []any{"clean"}, second["token"]) + assert.Equal(t, false, decoded.(map[string]any)["tail"]) +} + +// TestSanitizeJSONDocument_ScalarAndContainerCoverage exercises every scalar +// branch and nested collection of the walker. +func TestSanitizeJSONDocument_ScalarAndContainerCoverage(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const numericSecret = "123456789012" + require.True(t, RegisterRuntimeSecret(numericSecret)) + + p := OutputPipeline() + doc := []byte(`{"list":["plain",42,` + numericSecret + `,true,null],` + + `"nested":{"deep":[{"value":"plain"}]},"counter":7}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), numericSecret) + assert.Contains(t, string(out), "42", "clean numbers must keep their precision") + assert.Contains(t, string(out), `"counter":7`) +} + +// TestSanitizeJSONDocument_CleanKeyWinsSanitizedCollision pins that a secret key +// whose mask collides with an existing clean member never steals that member's +// name or value. +func TestSanitizeJSONDocument_CleanKeyWinsSanitizedCollision(t *testing.T) { + const secret = "ghp_FAKEtesttoken000000000000000000000000" + const masked = "ghp_..." + p := OutputPipeline() + doc := []byte(`{"` + secret + `":"secretkeyval","` + masked + `":"plainval"}`) + + // Repeat so a map-iteration-order-dependent bug in name resolution cannot + // hide behind a single lucky ordering. + for range 20 { + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + + var decoded map[string]string + require.NoError(t, json.Unmarshal(out, &decoded)) + assert.Equal(t, "plainval", decoded[masked], "clean key must retain its name and value") + assert.Len(t, decoded, 2) + assert.NotContains(t, string(out), secret) + } +} + +// TestSanitizeJSONLines_RepeatedRecordsFailsClosed pins that a cross-record +// match is not localized by a substring search a repeated record can fool. A +// later untouched copy must never stand in for a covered record: keeping the +// original bytes would write the spanning secret back out. Duplicates outside +// the changed region are still preserved. +func TestSanitizeJSONLines_RepeatedRecordsFailsClosed(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const secret = `aaa"}` + "\n" + `{"v":"bbb` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + content := []byte( + "{\"v\":\"aaa\"}\n" + // first half of the match + "{\"v\":\"bbb\"}\n" + // second half of the match + "{\"v\":\"aaa\"}\n" + // untouched duplicate of record 1 + "{\"v\":\"ccc\"}\n" + + "{\"v\":\"bbb\"}\n") // untouched duplicate of record 2 + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), secret, "the spanning secret must not be reassembled") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 5, "record count must not change") + for _, line := range lines[:2] { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } + assert.Equal(t, `{"v":"aaa"}`, lines[2], "an untouched duplicate outside the change must survive") + assert.Equal(t, `{"v":"ccc"}`, lines[3]) + assert.Equal(t, `{"v":"bbb"}`, lines[4], "an untouched duplicate outside the change must survive") +} + +// TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch pins that a +// clean record between a quoted header and footer survives, whether or not it +// repeats later. The cross-record check replaces only the records that carry +// block content, so a record that also appears after the block must not be +// dropped from the match and its copy outside the match must not be attributed to +// it. +func TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte( + "[\"" + begin + "\"]\n" + + "{\"value\":\"middle\"}\n" + + "[\"" + end + "\"]\n" + + "{\"value\":\"middle\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), begin) + assert.NotContains(t, string(out), end) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, i := range []int{0, 2} { + assert.True(t, json.Valid([]byte(lines[i])), "each replaced record must stay valid JSON: %s", lines[i]) + assert.Contains(t, lines[i], "output removed") + } + assert.Equal(t, `{"value":"middle"}`, lines[1], "a clean record inside the match must survive") + assert.Equal(t, `{"value":"middle"}`, lines[3], "its copy outside the match must survive too") +} + +// TestSanitizeJSONLines_QuotedMarkersKeepCleanRecords pins that a transcript that +// quotes a PEM header in one record and the footer in a later one loses only the +// records that carry block content. Replacing every record the lazy match touches +// gutted a transcript of work on this code — grep output and tool results quoting +// the markers — which is the #5705 outcome the single-document path avoids +// (6dca72790, 078ffa2, b0ab1e2). +func TestSanitizeJSONLines_QuotedMarkersKeepCleanRecords(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte( + "{\"event\":\"quote\",\"text\":\"" + begin + "\"}\n" + + "{\"event\":\"normal record one\"}\n" + + "{\"event\":\"normal record two\"}\n" + + "{\"event\":\"quote\",\"text\":\"" + end + "\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), begin) + assert.NotContains(t, string(out), end) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, i := range []int{0, 3} { + assert.True(t, json.Valid([]byte(lines[i])), "each replaced record must stay valid JSON: %s", lines[i]) + assert.Contains(t, lines[i], "output removed") + } + assert.Equal(t, `{"event":"normal record one"}`, lines[1], "a record carrying no block content must survive") + assert.Equal(t, `{"event":"normal record two"}`, lines[2], "a record carrying no block content must survive") +} + +// TestSanitizeJSONLines_BodyLineAsKeyBetweenMarkersCovered pins the record-level +// half of the body-in-key rule: a middle record whose key name is itself a body +// line carries key material and must be replaced, while a clean record between the +// markers still survives (#5705). +func TestSanitizeJSONLines_BodyLineAsKeyBetweenMarkersCovered(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + const body = "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + content := []byte( + "{\"" + begin + "\":1}\n" + + "{\"event\":\"normal record\"}\n" + + "{\"" + body + "\":2}\n" + + "{\"" + end + "\":3}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), body, "a body line in a key name is key material") + assert.NotContains(t, string(out), begin) + assert.NotContains(t, string(out), end) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, i := range []int{0, 2, 3} { + assert.True(t, json.Valid([]byte(lines[i])), "each replaced record must stay valid JSON: %s", lines[i]) + assert.Contains(t, lines[i], "output removed") + } + assert.Equal(t, `{"event":"normal record"}`, lines[1], "a record carrying no block content must survive") +} + +// TestSanitizeJSONLines_BodySplitAcrossRecordsCovered pins the other half: a +// middle record is kept only when it really is clean. A body split so that every +// record holds one short, digit-free chunk is still body material once the chunks +// are joined, and every record carrying it must be replaced. +func TestSanitizeJSONLines_BodySplitAcrossRecordsCovered(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte( + "[\"" + begin + "\"]\n" + + "[\"dfghjk\"]\n" + + "[\"QWERTYuiop\"]\n" + + "[\"" + end + "\"]\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "dfghjkQWERTYuiop") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONDocument_SensitiveBeginMemberMasksBlock pins that masking a +// sensitive member value cannot hide a private-key block that spans members. A +// sensitive-named member holding only the BEGIN marker is masked as a +// json_field, which would leave the body and END marker behind; the block is +// detected in the original framing and its members are masked. +func TestSanitizeJSONDocument_SensitiveBeginMemberMasksBlock(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"key_start":"` + begin + `","payload":"MIIEpAIBAAKCAQEA0123456789abcdef","tail":"` + end + `","verdict":"approve"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEpAIBAAKCAQEA", "the key body must not survive") + assert.NotContains(t, string(out), "END RSA") + assert.Contains(t, string(out), `"verdict":"approve"`, "a member outside the block must survive") +} + +// TestSanitizeJSONLines_CleanDuplicateKeyRecordPreserved pins that a clean +// duplicate-key record survives while another record is rewritten. +func TestSanitizeJSONLines_CleanDuplicateKeyRecordPreserved(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"a\":1,\"a\":2}\n{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.NotEmpty(t, findings) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 2) + assert.Equal(t, `{"a":1,"a":2}`, lines[0], "clean duplicate-key record must remain unchanged") + assert.True(t, json.Valid([]byte(lines[1]))) + assert.NotContains(t, lines[1], "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONLines_PrivateKeyAcrossRecordsFailsClosed pins that a PEM +// block split over three records replaces all three. +func TestSanitizeJSONLines_PrivateKeyAcrossRecordsFailsClosed(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte(fmt.Sprintf("[%q]\n[%q]\n[%q]\n", begin, "MIIEpAIBAAKCAQEA0123456789abcdefghijklmnop", end)) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.Equal(t, "private_key", findings[0].Name) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3) + for _, line := range lines { + assert.True(t, json.Valid([]byte(line))) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONLines_RawMultilinePEMFailsClosed pins the same for a PEM +// block written as raw lines rather than JSON values. +func TestSanitizeJSONLines_RawMultilinePEMFailsClosed(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte(fmt.Sprintf("%s\nMIIEpAIBAAKCAQEA0123456789abcdefghijklmnop\n%s\n", begin, end)) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.Equal(t, "private_key", findings[0].Name) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3) + for _, line := range lines { + assert.True(t, json.Valid([]byte(line))) + assert.Contains(t, line, "output removed") + assert.NotContains(t, line, "MIIEpAIBAAKCAQEA") + } +} + +// TestSanitizeJSONLines_DuplicateKeyEscapedSecretRedacted pins that an escaped +// secret in a record with duplicate keys is found by the token walk. +func TestSanitizeJSONLines_DuplicateKeyEscapedSecretRedacted(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"a\":\"first\",\"a\":\"second\",\"password\":\"\\u0073\\u0065\\u0063\\u0072\\u0065\\u0074_password_1234\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.NotEmpty(t, findings) + line := strings.TrimSpace(string(out)) + assert.True(t, json.Valid([]byte(line))) + assert.NotContains(t, line, "password_1234") + assert.Contains(t, line, `"a":"first"`, "an earlier duplicate value must survive redaction") + assert.Contains(t, line, `"a":"second"`, "the second duplicate value must survive redaction") +} + +// TestSanitizeJSONLines_FramingSecretPreservesLineCount pins that a secret +// spanning one record's own framing is redacted without adding or removing +// lines. +func TestSanitizeJSONLines_FramingSecretPreservesLineCount(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + const secret = `","field2":"` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + content := []byte("{\"field1\":\"foo\",\"field2\":\"bar\"}\n{\"field3\":\"second record\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.Equal(t, 2, strings.Count(string(out), "\n"), "line count must remain exactly 2") + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 2) + assert.True(t, json.Valid([]byte(lines[0]))) + assert.True(t, json.Valid([]byte(lines[1]))) + assert.NotContains(t, lines[0], secret) +} + +// TestSanitizeJSONLines_SingleRecordPrivateKeyRedactedInPlace pins that a key +// confined to one record is redacted rather than failed closed. +func TestSanitizeJSONLines_SingleRecordPrivateKeyRedactedInPlace(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte(fmt.Sprintf("{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\",\"pem\":\"%s\\n%s\"}\n", begin, end)) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.NotEmpty(t, findings) + line := strings.TrimSpace(string(out)) + assert.True(t, json.Valid([]byte(line))) + assert.Equal(t, 1, strings.Count(string(out), "\n"), "one record must stay one record") + assert.NotContains(t, line, "ghp_FAKEtesttoken") + assert.NotContains(t, line, "PRIVATE KEY-----") + assert.Contains(t, line, "[REDACTED PRIVATE KEY]", "a key confined to one record is redacted in place") +} + +// TestLineBounded pins the record-boundary check used to decide whether a +// surviving record copy is a whole record. +func TestLineBounded(t *testing.T) { + data := []byte("a\nbb\r\nccc\nlast") + tests := []struct { + name string + start, end int + want bool + }{ + {"whole first line", 0, 1, true}, + {"whole crlf line", 2, 4, true}, + {"whole middle line", 6, 9, true}, + {"last line without newline", 10, 14, true}, + {"starts mid-line", 1, 4, false}, + {"ends mid-line", 6, 8, false}, + {"lone carriage return", 9, 10, false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, lineBounded(data, tc.start, tc.end)) + }) + } +} + +// TestSanitizeJSONDocument_LeafAndSplitPrivateKeysMasked pins that a handled +// leaf block does not exempt a second, framing-spanning block in the same +// document, and that neither leaves key material behind. +func TestSanitizeJSONDocument_LeafAndSplitPrivateKeysMasked(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"note":"` + begin + `\nMIIEleafkeymaterial\n` + end + `",` + + `"key_start":"` + begin + `","payload":"MIIEspanningkeymaterial0","tail":"` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") + assert.NotContains(t, string(out), "MIIEleafkeymaterial") +} + +// TestSanitizeJSONLines_SensitiveBeginRecordFailsClosed pins that a +// cross-record private key is detected on the original stream, before masking +// a sensitive-named member removes its BEGIN marker. +func TestSanitizeJSONLines_SensitiveBeginRecordFailsClosed(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + records := []string{ + "{\"key_start\":\"" + begin + "\"}", + "{\"payload\":\"MIIEspanningkeymaterial0\"}", + "{\"tail\":\"" + end + "\"}", + } + for name, tc := range map[string]struct { + sep string + trailer string + }{ + "lf": {sep: "\n", trailer: "\n"}, + "crlf": {sep: "\r\n", trailer: "\r\n"}, + "no trailing newline": {sep: "\n", trailer: ""}, + } { + t.Run(name, func(t *testing.T) { + content := []byte(strings.Join(records, tc.sep) + tc.trailer) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") + assert.NotContains(t, string(out), "END RSA") + + lines := strings.Split(strings.TrimSuffix(strings.TrimSuffix(string(out), "\n"), "\r"), tc.sep) + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } + }) + } +} + +// TestSanitizeJSONDocument_EscapedLeafBlockDoesNotExemptSplitBlock pins that an +// escaped-marker leaf block cannot stand in for a separate block that spans +// members: the escaped block is visible only after JSON decoding, so raw-byte +// and decoded finding counts are not comparable. +func TestSanitizeJSONDocument_EscapedLeafBlockDoesNotExemptSplitBlock(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + escapedBegin := `\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + doc := []byte(`{"note":"` + escapedBegin + `\nMIIEleafkeymaterial\n` + end + `",` + + `"key_start":"` + begin + `","payload":"MIIEspanningkeymaterial0","tail":"` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0", "the spanning block must not survive") + assert.NotContains(t, string(out), "MIIEleafkeymaterial", "the escaped leaf block must be redacted") +} + +// TestSanitizeJSONLines_EscapedBeginRecordFailsClosed pins that a cross-record +// block is recognized even when its BEGIN marker is written with \u escapes in +// the original record bytes. +func TestSanitizeJSONLines_EscapedBeginRecordFailsClosed(t *testing.T) { + p := OutputPipeline() + end := pemEnd + content := []byte(`{"key_start":"\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + `"}` + "\n" + + `{"payload":"MIIEspanningkeymaterial0"}` + "\n" + + `{"tail":"` + end + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") + assert.NotContains(t, string(out), "END RSA") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONLines_BOMRecordEscapedBeginFailsClosed pins that a BOM on the +// first record does not hide a cross-record block. encoding/json rejects the mark, +// so the record was read as plain text, its \u-escaped BEGIN marker was never +// decoded, and the key body survived — bypassing the escaped-marker fix from +// bb35a97f6 (#5705). +func TestSanitizeJSONLines_BOMRecordEscapedBeginFailsClosed(t *testing.T) { + p := OutputPipeline() + bom := "\ufeff" + end := pemEnd + content := []byte(bom + `{"a":"\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + `"}` + "\n" + + `{"b":"MIIEspanningkeymaterial0"}` + "\n" + + `{"c":"` + end + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") + assert.NotContains(t, string(out), "END RSA") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONLines_CleanBOMRecordPreserved pins that a BOM-prefixed record is +// routed through the structural path and keeps its encoding mark, exactly as a +// BOM-prefixed single document does. +func TestSanitizeJSONLines_CleanBOMRecordPreserved(t *testing.T) { + p := OutputPipeline() + bom := []byte("\ufeff") + content := append(append([]byte{}, bom...), []byte(`{"event":"clean"}`+"\n")...) + content = append(content, []byte("{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\n")...) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, bytes.HasPrefix(out, bom), "the BOM must survive: %q", out) + assert.Contains(t, string(out), `{"event":"clean"}`, "a clean BOM-prefixed record must be unchanged") + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONDocument_CRLFNoStrayCarriageReturn pins that trailing CRLF +// framing is reproduced exactly, without a duplicated carriage return, on the +// unchanged and rewritten paths. +func TestSanitizeJSONDocument_CRLFNoStrayCarriageReturn(t *testing.T) { + p := OutputPipeline() + for name, doc := range map[string]string{ + "clean": "{\"a\":\"x\"}\r\n", + "secret": "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\r\n", + } { + t.Run(name, func(t *testing.T) { + out, _, err := SanitizeJSONDocument([]byte(doc), p) + require.NoError(t, err) + assert.NotContains(t, string(out), "\r\r", "no stray carriage return") + assert.True(t, strings.HasSuffix(string(out), "}\r\n"), "CRLF framing must be preserved: %q", out) + }) + } +} + +// TestSanitizeJSONDocument_EscapedMarkersAcrossMembersMasked pins that a block +// spanning members is detected even when no leaf produces a finding and the +// markers are \u-escaped in the raw bytes. +func TestSanitizeJSONDocument_EscapedMarkersAcrossMembersMasked(t *testing.T) { + p := OutputPipeline() + end := pemEnd + doc := []byte(`["\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + + `","MIIEspanningkeymaterial0","` + end + `"]`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") +} + +// TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersMasked pins that the +// decoded view applies the same Unicode normalization as the leaf scan, so a +// marker obfuscated with a zero-width character cannot hide a spanning block. +func TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersMasked(t *testing.T) { + p := OutputPipeline() + end := pemEnd + // U+200B inside the BEGIN marker: not a PEM block in any single form. + doc := []byte(`{"begin":"-----\u200bBEGIN RSA` + " PRIVATE KEY-----\"" + + `,"payload":"MIIEspanningkeymaterial0","end":"` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") +} + +// TestSanitizeJSONDocument_UnterminatedBeginBeforeCompleteBlockMasksBoth pins +// that a lazy match starting at one leaf's BEGIN and ending at another leaf's +// END cannot cancel out a complete leaf block: containment is judged per match, +// so both blocks are neutralized. +func TestSanitizeJSONDocument_UnterminatedBeginBeforeCompleteBlockMasksBoth(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"a":"` + begin + `\nMIIEfirstkeymaterial","b":"` + begin + `\nZZZZZZZZ\n` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEfirstkeymaterial", "the unterminated block must not survive") + assert.NotContains(t, string(out), "ZZZZZZZZ", "the complete block must not survive") +} + +// TestSanitizeJSONDocument_LeavesUnsupportedInputAlone pins the fallback +// contract for documents the structural path cannot handle. +func TestSanitizeJSONDocument_LeavesUnsupportedInputAlone(t *testing.T) { + p := OutputPipeline() + for name, doc := range map[string]string{ + "not json": `{"unterminated": `, + "plain text": "just prose", + "empty": "", + "trailing value": `{"a":1}{"b":2}`, + } { + t.Run(name, func(t *testing.T) { + out, findings, err := SanitizeJSONDocument([]byte(doc), p) + require.NoError(t, err) + assert.Empty(t, findings) + assert.Equal(t, doc, string(out), "an unsupported document must be returned unchanged") + }) + } +} + +// TestIsJSONLines pins multi-document detection. +func TestIsJSONLines(t *testing.T) { + assert.True(t, IsJSONLines([]byte("{\"a\":1}\n{\"b\":2}\n"))) + assert.True(t, IsJSONLines([]byte("\ufeff{\"a\":1}\r\n{\"b\":2}\r\n"))) + assert.False(t, IsJSONLines([]byte("{\"a\":1}\n")), "single record is not a multi-document stream") + assert.False(t, IsJSONLines([]byte("{\"a\":1}")), "single record without newline is not a stream") + assert.False(t, IsJSONLines([]byte("{\"a\":1}\nnot json\n")), "stream with non-JSON line is rejected") + assert.False(t, IsJSONLines([]byte("")), "empty content is not a stream") +} + +// TestSanitizeJSONLines_NonJSONRecordsRedacted pins the text fallback for +// records that are not valid JSON. +func TestSanitizeJSONLines_NonJSONRecordsRedacted(t *testing.T) { + p := OutputPipeline() + content := []byte("plain Token: ghp_FAKEtesttoken000000000000000000000000\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + assert.Equal(t, 1, strings.Count(string(out), "\n"), "line framing must be preserved") +} + +// TestSanitizeJSONLines_PreservesBlankAndCleanRecords pins that blank lines and +// clean non-JSON records survive a stream that also contains a secret. +func TestSanitizeJSONLines_PreservesBlankAndCleanRecords(t *testing.T) { + p := OutputPipeline() + content := []byte("plain prose without secrets\n" + + "\n" + + "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "blank lines and record count must be preserved") + assert.Equal(t, "plain prose without secrets", lines[0]) + assert.Empty(t, lines[1]) + assert.NotContains(t, lines[2], "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONDocument_TextRedactionThatBreaksJSONFailsClosed pins that a +// framing-spanning secret whose in-place redaction would leave invalid JSON is +// replaced with a valid marker instead of corrupted syntax. +func TestSanitizeJSONDocument_TextRedactionThatBreaksJSONFailsClosed(t *testing.T) { + resetRuntimeSecrets() + t.Cleanup(resetRuntimeSecrets) + // Spans the closing quote, comma and next key, so masking it breaks the + // document. + const secret = `"v1","k2"` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + doc := []byte(`{"k1":"v1","k2":"v2"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), secret) + assert.Contains(t, string(out), "output removed") +} + +// TestSanitizeJSONDocument_TopLevelScalars pins that scalar documents are +// handled without inventing structure. +func TestSanitizeJSONDocument_TopLevelScalars(t *testing.T) { + p := OutputPipeline() + for name, doc := range map[string]string{ + "number": "42", + "true": "true", + "null": "null", + } { + t.Run(name, func(t *testing.T) { + out, findings, err := SanitizeJSONDocument([]byte(doc), p) + require.NoError(t, err) + assert.Empty(t, findings) + assert.Equal(t, doc, string(out)) + }) + } +} + +// TestSanitizeJSONLines_LastRecordWithoutNewline pins that a final record +// without a trailing newline is still sanitized and keeps its framing. +func TestSanitizeJSONLines_LastRecordWithoutNewline(t *testing.T) { + p := OutputPipeline() + content := []byte(`{"token":"ghp_FAKEtesttoken000000000000000000000000"}`) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + assert.False(t, strings.HasSuffix(string(out), "\n"), "no newline must be invented") + assert.True(t, json.Valid(out), "the record must stay valid JSON: %s", out) +} + +// TestSanitizeJSONLines_PreservesCRLFFraming pins that CRLF records keep their +// carriage returns across a rewrite. +func TestSanitizeJSONLines_PreservesCRLFFraming(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"event\":\"clean\"}\r\n{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\r\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.Equal(t, 2, strings.Count(string(out), "\r\n"), "CRLF framing must be preserved") + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONDocument_TrailingNewlinePreserved pins that a rewritten +// document keeps the file's own line framing. +func TestSanitizeJSONDocument_TrailingNewlinePreserved(t *testing.T) { + p := OutputPipeline() + for name, doc := range map[string]string{ + "lf": "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\n", + "crlf": "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\r\n", + "none": "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}", + } { + t.Run(name, func(t *testing.T) { + out, findings, err := SanitizeJSONDocument([]byte(doc), p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + + want := map[string]string{"lf": "\n", "crlf": "\r\n", "none": ""}[name] + assert.True(t, strings.HasSuffix(string(out), "}"+want), "trailing framing must be preserved: %q", out) + assert.Equal(t, strings.Count(doc, "\n"), strings.Count(string(out), "\n")) + }) + } +} + +// TestSanitizeJSONDocument_CleanDuplicateKeyDocumentUnchanged pins that a +// duplicate-key document with nothing to redact is left byte-for-byte intact. +func TestSanitizeJSONDocument_CleanDuplicateKeyDocumentUnchanged(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"a": 1, "a": 2}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + assert.Empty(t, findings) + assert.Equal(t, string(doc), string(out), "a clean duplicate-key document must not be reformatted") +} + +// TestSanitizeJSONDocument_DuplicateKeyRawTextFinding covers a document whose +// match exists in the serialized form: the leaves are individually clean, so +// the raw-text scan finds and redacts it. +func TestSanitizeJSONDocument_DuplicateKeyRawTextFinding(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"password": "secretvalue123", "dup": 1, "dup": 2}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "secretvalue123") +} + +// TestSanitizeJSONDocument_DuplicateKeyWithSecretKey covers a duplicate-key +// document whose keys themselves carry a secret. +func TestSanitizeJSONDocument_DuplicateKeyWithSecretKey(t *testing.T) { + p := OutputPipeline() + const secret = "ghp_FAKEtesttoken000000000000000000000000" + doc := []byte(`{"` + secret + `": 1, "` + secret + `": 2}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), secret) +} + +// reviewResultSchemaPath is a pinned copy of the schema authored in +// fullsend-ai/agents (schemas/review-result.schema.json). Vendoring it ties these +// tests to the real constraints sanitization can break — the enums and patterns +// of the structural fields, additionalProperties false, and the required members +// — instead of a hand-maintained mirror that silently drifts when the upstream +// enum changes. The upstream repo, commit and path are recorded in +// testdata/review-result.schema.pin; re-vendor the schema together with that pin, +// and scripts/check-review-schema-pin.sh reports when this copy drifts from +// upstream at the pinned commit. +const reviewResultSchemaPath = "testdata/review-result.schema.json" + +// reviewResultSchema is the subset of the vendored schema the checks below use. +type reviewResultSchema struct { + topLevel map[string]bool + findingMembers map[string]bool + actions []string + severities []string + categories []string +} + +// loadReviewResultSchema reads the pinned schema and extracts the constraints +// from it, so the test cannot accept a category or member the real harness would +// reject. +func loadReviewResultSchema(t *testing.T) reviewResultSchema { + t.Helper() + raw, err := os.ReadFile(reviewResultSchemaPath) + require.NoError(t, err, "the pinned review-result schema must be readable") + + var doc struct { + Properties map[string]json.RawMessage `json:"properties"` + Defs struct { + Finding struct { + Properties map[string]struct { + Enum []string `json:"enum"` + } `json:"properties"` + } `json:"finding"` + } `json:"$defs"` + } + require.NoError(t, json.Unmarshal(raw, &doc), "the pinned review-result schema must decode") + + schema := reviewResultSchema{topLevel: map[string]bool{}, findingMembers: map[string]bool{}} + for key := range doc.Properties { + schema.topLevel[key] = true + } + for key := range doc.Defs.Finding.Properties { + schema.findingMembers[key] = true + } + + var action struct { + Enum []string `json:"enum"` + } + require.NoError(t, json.Unmarshal(doc.Properties["action"], &action)) + schema.actions = action.Enum + + findingProps := doc.Defs.Finding.Properties + schema.severities = findingProps["severity"].Enum + schema.categories = findingProps["category"].Enum + require.NotEmpty(t, schema.actions, "action enum must be present in the schema") + require.NotEmpty(t, schema.severities, "severity enum must be present in the schema") + require.NotEmpty(t, schema.categories, "category enum must be present in the schema") + return schema +} + +// assertReviewResultSchemaValid checks doc against the review-result schema +// constraints sanitization can break. A review the harness rejects is not posted, +// which is the #5705 outcome, so a fixture that survives sanitization has to still +// satisfy these. +func assertReviewResultSchemaValid(t *testing.T, doc []byte) { + t.Helper() + schema := loadReviewResultSchema(t) + + var result map[string]json.RawMessage + require.NoError(t, json.Unmarshal(doc, &result), "sanitized review must decode: %s", doc) + + for key := range result { + assert.True(t, schema.topLevel[key], "unexpected top-level member %q", key) + } + + var action string + require.NoError(t, json.Unmarshal(result["action"], &action), "action is required") + assert.Contains(t, schema.actions, action, "action must be one of the schema enums") + + var repo string + require.NoError(t, json.Unmarshal(result["repo"], &repo), "repo is required") + assert.Regexp(t, `^[a-zA-Z0-9._-]+(/[a-zA-Z0-9._-]+)+$`, repo, "repo must match the schema pattern") + + var prNumber int + require.NoError(t, json.Unmarshal(result["pr_number"], &prNumber), "pr_number is required") + assert.Positive(t, prNumber, "pr_number must be at least 1") + + if action == "comment" || action == "approve" || action == "request-changes" || action == "reject" { + var headSHA, body string + require.NoError(t, json.Unmarshal(result["head_sha"], &headSHA), "%s requires head_sha", action) + require.NoError(t, json.Unmarshal(result["body"], &body), "%s requires body", action) + assert.Regexp(t, `^[0-9a-fA-F]{40}$|^[0-9a-fA-F]{64}$`, headSHA, "head_sha must match the schema pattern") + assert.NotEmpty(t, body, "body must be at least one character") + } + + rawFindings, hasFindings := result["findings"] + if !hasFindings { + assert.NotContains(t, []string{"request-changes", "reject"}, action, "%s requires findings", action) + return + } + var findings []map[string]json.RawMessage + require.NoError(t, json.Unmarshal(rawFindings, &findings), "findings must be an array of objects") + require.NotEmpty(t, findings, "findings must not be empty") + + for i, finding := range findings { + for key := range finding { + assert.True(t, schema.findingMembers[key], "finding %d has unexpected member %q", i, key) + } + var severity, category, file, description string + require.NoError(t, json.Unmarshal(finding["severity"], &severity), "finding %d requires severity", i) + require.NoError(t, json.Unmarshal(finding["category"], &category), "finding %d requires category", i) + require.NoError(t, json.Unmarshal(finding["file"], &file), "finding %d requires file", i) + require.NoError(t, json.Unmarshal(finding["description"], &description), "finding %d requires description", i) + assert.Contains(t, schema.severities, severity, "finding %d severity must be one of the schema enums", i) + assert.Contains(t, schema.categories, category, "finding %d category must be one of the schema enums", i) + assert.NotEmpty(t, file, "finding %d file must be at least one character", i) + assert.NotEmpty(t, description, "finding %d description must be at least one character", i) + } +} + +// TestSanitizeJSONDocument_KeepsBOM pins that a document carrying a UTF-8 BOM is +// sanitized structurally and keeps its encoding mark. The BOM is not JSON +// whitespace, so without this the document falls through to the plain-text scan, +// which is the scan that cannot guarantee JSON syntax stays intact (#5705). +func TestSanitizeJSONDocument_KeepsBOM(t *testing.T) { + p := OutputPipeline() + bom := []byte("\ufeff") + + clean := append(append([]byte{}, bom...), []byte(`{"verdict":"approve"}`)...) + out, findings, err := SanitizeJSONDocument(clean, p) + require.NoError(t, err) + assert.Empty(t, findings) + assert.Equal(t, clean, out, "a clean BOM-prefixed document must be returned unchanged") + + dirty := append(append([]byte{}, bom...), []byte(`{"token":"ghp_FAKEtesttoken000000000000000000000000"}`)...) + out, findings, err = SanitizeJSONDocument(dirty, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, bytes.HasPrefix(out, bom), "the BOM must survive the rewrite: %q", out) + assert.True(t, json.Valid(bytes.TrimPrefix(out, bom)), "sanitized document must stay valid JSON: %s", out) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") +} + +// TestOutputRemoval_NoPlainTextReason pins that the plain-text marker the CLI no +// longer writes is not a recognized reason. A document that parses as JSON takes +// the structural path, so every remaining fail-closed reason is structural. +func TestOutputRemoval_NoPlainTextReason(t *testing.T) { + reason, removed := OutputRemoval([]byte(`{"error":"output removed because text redaction would invalidate JSON"}`)) + assert.False(t, removed, "the removed plain-text marker must not be recognized") + assert.Empty(t, reason) +} + +// TestSanitizeJSONDocument_NormalizedSensitiveKeyMasksValue pins that a +// sensitive key obfuscated with a zero-width or fullwidth character is still +// recognized after sanitizeJSONKey writes its normalized spelling. Deciding +// sensitivity on the original key produced an explicit "password" field with an +// untouched opaque value, and the whole-value rescan does not apply json_field +// (#5705). +func TestSanitizeJSONDocument_NormalizedSensitiveKeyMasksValue(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"pass\u200bword":"opaque-value-12345","password":"another-opaque-1"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "opaque-value-12345", "a normalized sensitive key must mask its value") + assert.NotContains(t, string(out), "another-opaque-1", "a compatibility-obfuscated sensitive key must mask its value") + assert.Contains(t, string(out), `"password":`, "the normalized key is written") +} + +// TestSanitizeJSONLines_NormalizedSensitiveKeyMasksValue is the JSONL half: a +// record whose sensitive key is obfuscated must still mask its value. +func TestSanitizeJSONLines_NormalizedSensitiveKeyMasksValue(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"pass\\u200bword\":\"opaque-value-12345\"}\n" + + "{\"event\":\"clean\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "opaque-value-12345") + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 2, "record count must not change") + assert.Equal(t, `{"event":"clean"}`, lines[1], "a clean record must survive") +} + +// TestSanitizeJSONDocument_AuthorPathExemption pins that the structural path +// honours the #9944 exemption the text scan applies: an "author" member holding a +// codex agent path is not a credential, even though "author" contains "auth". +func TestSanitizeJSONDocument_AuthorPathExemption(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"author":"/root/agent_one/child","messages":[{"author":"/root/agent_one/child"}]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + assert.Empty(t, findings, "a codex agent path under author is exempt") + assert.Equal(t, string(doc), string(out), "an exempt document must be returned unchanged") +} + +// TestSanitizeJSONLines_AuthorPathExemption is the JSONL half of the #9944 +// exemption: a codex transcript record is a JSON document and takes the +// structural path. +func TestSanitizeJSONLines_AuthorPathExemption(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"author\":\"/root/agent_one/child\"}\n" + + "{\"author\":\"/root/agent_two/child\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.Empty(t, findings, "codex agent paths under author are exempt") + assert.Equal(t, string(content), string(out), "an exempt stream must be returned unchanged") +} + +// TestSanitizeJSONDocument_MaskShapedRealSecretStillMasked pins that a real short +// credential that happens to look like a mask placeholder is still masked when it +// is the original value. isAlreadyMasked is only trusted for a value this scan +// rewrote; otherwise an eight-character password ending in "..." and a backslash +// was written back unchanged (#5705). +func TestSanitizeJSONDocument_MaskShapedRealSecretStillMasked(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"password":"abcd...\\"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "abcd...", "a real secret shaped like a placeholder must still be masked") +} + +// TestSanitizeJSONDocument_BodyChunksSplitAcrossObjectKeysMasked pins the +// regression a reviewer found: a PEM body split into short chunks stored in +// separate object members lost its markers but kept every chunk, because each +// intervening key flushed the joined-run test. Object keys are structure and never +// join the run, but they must not break it either (#5705). +func TestSanitizeJSONDocument_BodyChunksSplitAcrossObjectKeysMasked(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"` + begin + `":"MIIEowIB","k1":"AAKCAQEA","k2":"x9Kq2Lm","` + end + `":"tail"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + for _, chunk := range []string{"MIIEowIB", "AAKCAQEA", "x9Kq2Lm"} { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } + assert.NotContains(t, string(out), "BEGIN RSA") + assert.NotContains(t, string(out), "END RSA") +} + +// TestSanitizeJSONDocument_ShortFragmentAfterBodyLineMasked pins that a recognized +// body line does not end the run: a short final fragment beside it must be masked +// too, or it survives once the markers are gone (#5705). +func TestSanitizeJSONDocument_ShortFragmentAfterBodyLineMasked(t *testing.T) { + p := OutputPipeline() + longLine := "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + doc := []byte(`{"a":"` + pemBegin + `","b":"` + longLine + `","c":"AQAB","d":"` + pemEnd + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), longLine) + assert.NotContains(t, string(out), "AQAB", "a short fragment beside a body line must not survive") +} + +// TestSanitizeJSONDocument_PrefixedBodyFragmentsMasked pins that body fragments +// embedded in surrounding text are masked. The "part:" prefix and the whitespace +// used to break the run, so each 8-character fragment stayed below the material +// floor and survived after the markers were masked (#5705). +func TestSanitizeJSONDocument_PrefixedBodyFragmentsMasked(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"a":"` + pemBegin + `","b":"part: MIIEowIB","c":"part: AAKCAQEA","d":"` + pemEnd + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEowIB", "a prefixed body fragment must not survive") + assert.NotContains(t, string(out), "AAKCAQEA", "a prefixed body fragment must not survive") +} + +// TestSanitizeJSONDocument_BodyChunksWithLineFramingMasked pins that a body split +// into short chunks that each carry the newline that ended the line is still +// masked. The whitespace is line framing, not body: it must not break the joined +// run, where each chunk on its own is below the material floor (#5705). +func TestSanitizeJSONDocument_BodyChunksWithLineFramingMasked(t *testing.T) { + p := OutputPipeline() + chunks := []string{`MIIEowIB\n`, `AAKCAQEA\n`, `x9Kq2Lm0\n`} + quoted := []string{`"` + pemBegin + `"`} + for _, chunk := range chunks { + quoted = append(quoted, `"`+chunk+`"`) + } + quoted = append(quoted, `"`+pemEnd+`"`) + doc := []byte(`{"lines":[` + strings.Join(quoted, ",") + `]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----") + for _, chunk := range []string{"MIIEowIB", "AAKCAQEA", "x9Kq2Lm0"} { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } +} + +// TestSanitizeJSONLines_SchemaFieldsBetweenQuotedMarkersKept is the record-level +// half of the joined-run rule: a middle record whose values are schema fields +// joins into "criticalssrfMakefile" and must keep its content, so the review the +// transcript describes is not discarded (#5705). +func TestSanitizeJSONLines_SchemaFieldsBetweenQuotedMarkersKept(t *testing.T) { + p := OutputPipeline() + for _, file := range []string{"Makefile", "Makefile2", "README", "LICENSE"} { + t.Run(file, func(t *testing.T) { + content := []byte( + `{"note":"quotes the ` + pemBegin + ` header"}` + "\n" + + `{"severity":"critical","category":"ssrf","file":"` + file + `"}` + "\n" + + `{"note":"quotes the ` + pemEnd + ` footer"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + assert.Contains(t, lines[1], `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, lines[1], `"file":"`+file+`"`, "a schema value is not body material") + assert.NotContains(t, lines[0], "PRIVATE KEY-----") + assert.NotContains(t, lines[2], "PRIVATE KEY-----") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "every record must stay valid JSON: %s", line) + } + }) + } +} + +// TestSanitizeJSONLines_SchemaFieldsInReversedOrderKept is the JSONL record +// counterpart of TestSanitizeJSONDocument_SchemaFieldsInReversedOrderKept. +func TestSanitizeJSONLines_SchemaFieldsInReversedOrderKept(t *testing.T) { + p := OutputPipeline() + for _, file := range []string{"README", "LICENSE", "Makefile", "Makefile2"} { + t.Run(file, func(t *testing.T) { + content := []byte( + `{"note":"quotes the ` + pemBegin + ` header"}` + "\n" + + `{"file":"` + file + `","category":"ssrf","severity":"critical"}` + "\n" + + `{"note":"quotes the ` + pemEnd + ` footer"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + assert.Contains(t, lines[1], `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, lines[1], `"file":"`+file+`"`, "a schema value is not body material") + assert.Contains(t, lines[1], `"severity":"critical"`, "a schema value is not body material") + assert.NotContains(t, lines[0], "PRIVATE KEY-----") + assert.NotContains(t, lines[2], "PRIVATE KEY-----") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "every record must stay valid JSON: %s", line) + } + }) + } +} + +// TestSanitizeJSONLines_ShortBodyChunksCovered pins that a middle record holding +// a body in chunks shorter than the material floor is replaced, not written back +// with its body intact (#5705). +func TestSanitizeJSONLines_ShortBodyChunksCovered(t *testing.T) { + p := OutputPipeline() + content := []byte( + `{"note":"` + pemBegin + `"}` + "\n" + + `["MII","Eow","IB","AAK","CAQ","EA"]` + "\n" + + `{"note":"` + pemEnd + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + for _, chunk := range []string{"MII", "Eow", "IB", "AAK", "CAQ", "EA"} { + assert.NotContains(t, string(out), `"`+chunk+`"`, "a short body chunk must not survive") + } + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + } +} + +// TestSanitizeJSONLines_ShortFragmentAfterBodyLineCovered is the record-level half +// of TestSanitizeJSONDocument_ShortFragmentAfterBodyLineMasked: a short fragment +// beside a recognized body line must be covered with it (#5705). +func TestSanitizeJSONLines_ShortFragmentAfterBodyLineCovered(t *testing.T) { + p := OutputPipeline() + longLine := "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + content := []byte( + `{"note":"` + pemBegin + `"}` + "\n" + + `{"line":"` + longLine + `"}` + "\n" + + `{"tail":"AQAB"}` + "\n" + + `{"note":"` + pemEnd + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), longLine) + assert.NotContains(t, string(out), "AQAB", "a short fragment beside a body line must not survive") + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + } +} + +// TestSanitizeJSONLines_PrefixedBodyFragmentsCovered is the record-level half of +// TestSanitizeJSONDocument_PrefixedBodyFragmentsMasked (#5705). +func TestSanitizeJSONLines_PrefixedBodyFragmentsCovered(t *testing.T) { + p := OutputPipeline() + content := []byte( + `{"note":"` + pemBegin + `"}` + "\n" + + `{"part":"part: MIIEowIB"}` + "\n" + + `{"part":"part: AAKCAQEA"}` + "\n" + + `{"note":"` + pemEnd + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "MIIEowIB", "a prefixed body fragment must not survive") + assert.NotContains(t, string(out), "AAKCAQEA", "a prefixed body fragment must not survive") + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + } +} + +// TestSanitizeJSONLines_BodyChunksWithLineFramingCovered is the record-level half +// of TestSanitizeJSONDocument_BodyChunksWithLineFramingMasked: each middle record +// holds a short body chunk together with the newline that ended the line, and the +// framing must not stop the chunks from being joined and masked (#5705). +func TestSanitizeJSONLines_BodyChunksWithLineFramingCovered(t *testing.T) { + p := OutputPipeline() + content := []byte( + `{"note":"` + pemBegin + `"}` + "\n" + + `["MIIEowIB\n","AAKCAQEA\n","x9Kq2Lm0\n"]` + "\n" + + `{"note":"` + pemEnd + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + for _, chunk := range []string{"MIIEowIB", "AAKCAQEA", "x9Kq2Lm0"} { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + } +} + +// TestSanitizeJSONLines_BodyChunksSplitAcrossObjectKeysCovered is the JSONL half: +// a middle record whose body chunks are stored in separate object members must be +// replaced once the chunks are joined across the intervening keys. +func TestSanitizeJSONLines_BodyChunksSplitAcrossObjectKeysCovered(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte( + "{\"" + begin + "\":1}\n" + + "{\"a\":\"MIIEowIB\",\"b\":\"AAKCAQEA\",\"c\":\"x9Kq2Lm\"}\n" + + "{\"" + end + "\":2}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + for _, chunk := range []string{"MIIEowIB", "AAKCAQEA", "x9Kq2Lm"} { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// The error return of SanitizeJSONDocument and SanitizeJSONLines is only +// reachable on a decoder limit after IsJSONDocument has accepted the bytes, and +// no input produces one: json.Valid and the token decoder share the same limits, +// so a document the decoder rejects is rejected before the structural path and +// falls back to the text scan. The wrap text ("could not sanitize JSON document" +// / "could not sanitize JSONL record") is therefore pinned at the CLI layer by +// TestScanOutputFiles_SanitizerErrorContainsFileAndContinues, which injects the +// error through the sanitizer parameter rather than depending on a natural +// trigger. diff --git a/internal/security/redactor.go b/internal/security/redactor.go index 9941deee98..d3ad4e157e 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -7,6 +7,7 @@ import ( "slices" "strings" "sync" + "unicode/utf8" ) // Runtime secrets are exact credential values the runner learned during @@ -17,6 +18,12 @@ import ( // trivial string can never blank out ordinary output. const minRuntimeSecretLen = 8 +// minJSONFieldLen is the shortest value masked as a json_field. It is counted in +// runes, matching the {8,} quantifier the json_field value used before the +// pattern was widened to span escaped quotes inside a JSON string. The other +// structural patterns enforce their own minimum in the pattern itself. +const minJSONFieldLen = 8 + var ( runtimeSecretsMu sync.RWMutex runtimeSecrets []string @@ -63,6 +70,13 @@ func resetRuntimeSecrets() { runtimeSecrets = nil } +// ResetRuntimeSecretsForTest clears the registry. It is exported because tests +// outside this package (internal/cli drives the output scan end to end) need a +// clean registry; the tests in this package call resetRuntimeSecrets directly. +func ResetRuntimeSecretsForTest() { + resetRuntimeSecrets() +} + // SecretRedactor scans text for API keys, tokens, credentials, and // sensitive patterns, replacing them with masked versions. Adapted from // Hermes Agent's agent/redact.py. @@ -87,6 +101,21 @@ func NewSecretRedactor() *SecretRedactor { func (s *SecretRedactor) Name() string { return "secret_redactor" } func (s *SecretRedactor) Scan(text string) ScanResult { + return s.scan(text, false) +} + +// ScanWholeValueSecrets masks only the secrets whose match is the entire value: +// registered runtime values and private-key blocks. It is meant for bytes a leaf +// scan has already redacted, where a pattern match can be a redaction +// placeholder plus JSON escape characters rather than a new secret (#5705). +func (s *SecretRedactor) ScanWholeValueSecrets(text string) ScanResult { + return s.scan(text, true) +} + +// scan runs the pattern set. wholeValueOnly restricts it to the patterns whose +// match is the whole secret, which are the only ones that can still be present +// in bytes an earlier pass already redacted. +func (s *SecretRedactor) scan(text string, wholeValueOnly bool) ScanResult { result := ScanResult{Safe: true, Sanitized: text} current := text @@ -110,29 +139,37 @@ func (s *SecretRedactor) Scan(text string) ScanResult { // Prefix-based patterns (full match is the secret). // Use ReplaceAll to catch duplicate occurrences of the same secret. - for _, p := range s.prefixPatterns { - // Deduplicate matches so we report each unique secret once. - seen := map[string]bool{} - matches := p.regex.FindAllString(current, -1) - for _, match := range matches { - if seen[match] { - continue + if !wholeValueOnly { + for _, p := range s.prefixPatterns { + // Deduplicate matches so we report each unique secret once. + seen := map[string]bool{} + matches := p.regex.FindAllString(current, -1) + for _, match := range matches { + if seen[match] { + continue + } + seen[match] = true + masked := Mask(match) + result.Findings = append(result.Findings, Finding{ + Scanner: "secret_redactor", + Name: p.name, + Severity: "critical", + Detail: fmt.Sprintf("Redacted %s (%d chars) -> %s", p.name, len(match), masked), + }) + current = strings.ReplaceAll(current, match, masked) + result.Safe = false } - seen[match] = true - masked := mask(match) - result.Findings = append(result.Findings, Finding{ - Scanner: "secret_redactor", - Name: p.name, - Severity: "critical", - Detail: fmt.Sprintf("Redacted %s (%d chars) -> %s", p.name, len(match), masked), - }) - current = strings.ReplaceAll(current, match, masked) - result.Safe = false } } - // Structural patterns (capture group is the secret) + // Structural patterns (capture group is the secret). Only the private-key + // block is safe to match in whole-value mode: every other pattern captures a + // value out of surrounding text, so a match on bytes that already carry a + // redaction placeholder can be that placeholder rather than a secret. for _, p := range s.structuralPatterns { + if wholeValueOnly && p.name != "private_key" { + continue + } // Private key: replace full match (no capture group needed). if p.name == "private_key" { matches := p.regex.FindAllString(current, -1) @@ -176,7 +213,46 @@ func (s *SecretRedactor) Scan(text string) ScanResult { if p.name == "json_field" && isExemptJSONField(current, loc[0], loc[1], secret) { continue } - masked := mask(secret) + // If the matched secret ends with a backslash and is immediately + // followed by a quote delimiter, the trailing backslash was escaping + // that delimiter (e.g. \" in JSON or code strings). Preserve the + // escape by excluding the backslash from the redacted secret span. + // json_field spans escaped quotes in its own value pattern, so its + // capture already ends at the delimiter it belongs to. + if p.name != "json_field" && end < len(current) && (current[end] == '"' || current[end] == '\'') { + numBackslashes := 0 + for k := len(secret) - 1; k >= 0 && secret[k] == '\\'; k-- { + numBackslashes++ + } + if numBackslashes%2 == 1 { + secret = secret[:len(secret)-1] + end-- + } + } + if len(secret) == 0 { + continue + } + // A captured value is always masked, even when it already looks + // like a mask. The shape of a placeholder (4 characters and "...", + // or "***") is also the shape of a real short secret: + // db_connection_password accepts a value of 4 characters or more, + // so skipping every 7-byte capture that ends in "..." left a real + // password such as postgres://u:abcd...@host in the output. Callers + // that rescan bytes an earlier pass already redacted use + // ScanWholeValueSecrets, which runs no value pattern, so they never + // reach this loop; a full Scan over redacted text can therefore + // only be re-masking a placeholder into "***", never a secret into + // itself. + // + // Only json_field needs the length gate here: its value pattern + // matches any length, while env_assignment, auth_header and + // db_connection_password enforce their own minimum in the pattern. + // The gate counts runes and runs on the trimmed span, so the bytes + // actually masked are never shorter than the documented minimum. + if p.name == "json_field" && utf8.RuneCountInString(secret) < minJSONFieldLen { + continue + } + masked := Mask(secret) result.Findings = append(result.Findings, Finding{ Scanner: "secret_redactor", Name: p.name, @@ -200,7 +276,7 @@ func (s *SecretRedactor) Scan(text string) ScanResult { // authorPathValue matches the author values the json_field rule leaves // unmasked: an absolute path of at least 10 bytes made only of letters, // digits, '_', '.', '/' and '-'. Such a value has no quote, colon, -// whitespace, backslash or '@', and mask would keep its first four bytes, +// whitespace, backslash or '@', and Mask would keep its first four bytes, // so the patterns that run after json_field match the same text whether // the value is kept or masked. Codex agent paths (/root, /morpheus, or // /root/ plus /-separated names of [a-z0-9_]) of 10 or more bytes qualify; @@ -237,11 +313,41 @@ func isExemptJSONField(text string, matchStart, matchEnd int, secret string) boo return authorPathValue.MatchString(secret) && isExemptJSONKey(text[matchStart:matchEnd]) } -func mask(value string) string { +// Mask returns a redacted representation of a secret value. +// +// The returned text is safe to splice into a JSON or YAML string value, but not +// into arbitrary byte ranges: it keeps the first four bytes unless they contain +// an escape or a quote delimiter, in which case it returns "***". Callers that +// write it back must place it inside a string literal (writeJSONString does this +// for the structural path); a caller that rebuilds raw framing must re-escape +// the surrounding text itself. +func Mask(value string) string { if len(value) < 10 { return "***" } - return value[:4] + "..." + prefix := value[:4] + // A prefix that carries an escape or a quote delimiter cannot be written + // back: in a JSON or YAML string it would escape or close the surrounding + // quoting and break the document (#5705). The quote case covers a YAML + // single-quoted value whose doubled quote ('') falls inside the prefix: + // keeping half of the pair leaves a lone quote that ends the string early. + if strings.ContainsAny(prefix, "\\'\"") { + return "***" + } + return prefix + "..." +} + +// isAlreadyMasked reports whether value is already a redaction placeholder +// produced by Mask. Trailing backslashes are ignored: a placeholder that sits in +// a JSON string can be followed by escape characters once the string is +// re-encoded, and that tail must not turn the placeholder into a new secret +// (#5705). +// +// Only callers that know the value came from Mask may use this. The shape alone +// cannot tell a placeholder from a real short secret, so Scan does not apply it. +func isAlreadyMasked(value string) bool { + value = strings.TrimRight(value, `\`) + return value == "***" || len(value) == 7 && strings.HasSuffix(value, "...") } func defaultPrefixPatterns() []secretPattern { @@ -297,7 +403,28 @@ func defaultStructuralPatterns() []secretPattern { // the mask keeps it visible. A bare value still ends at the first // space, as in the PostToolUse hook. {"env_assignment", `(?i)(?:^|\s)(?:export\s+)?((?:[A-Za-z0-9]+_)*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|PASSWD|AUTH|API_KEY)(?:_[A-Za-z0-9]+)*)\s*=\s*(?:['"](?:(?:basic|bearer|token)[ \t]+)?)?([^\s"'}\]),;]{8,})['"]?`}, - {"json_field", `(?:"[^"]*(?i:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?i:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"([^"]{8,})"|'([^']{8,})')`}, + // json_field captures a value out of a quoted field. The double-quoted + // branch and the second single-quoted branch consume escaped delimiters, so + // a JSON or YAML string with an embedded quote is matched whole. The first + // single-quoted branch covers a value that ends in a literal backslash, + // where that backslash must not escape the closing quote; it comes first + // because Go's regexp alternation is leftmost-first, so the escape-reading + // branch would otherwise match first and read the closing quote of + // 'api_key': 'secret\' in a YAML flow mapping as an escape, running on to + // the next quote on the same line and swallowing the field that follows. + // That branch therefore matches only when the quote after the backslash is + // followed by a field or line boundary. The strict double-quoted branch + // stops at a raw newline, so a JSON value ending in \" cannot run on to the + // next line's quote and swallow the field there (#9944). A double-quoted + // value that ends in a literal backslash right before its closing quote + // needs the same bounded fallback the single-quoted branch has, and a + // value folded across physical lines (a YAML or log string, not JSON) still + // needs to be matchable when its closing quote ends the field or the line: + // that last branch allows raw newlines but only at that boundary, so it + // 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]*(?:,|\}|\]|$))`}, // The optional quote covers YAML: authorization: "Bearer ". {"auth_header", `(?i)(?:Authorization|X-Api-Key|X-Auth-Token)\s*:\s*['"]?(?:(?:Basic|Bearer|Token)\s+)?([^\s"'}\]),;]{12,})`}, {"private_key", `-----BEGIN\s+(?:RSA\s+|EC\s+|OPENSSH\s+)?PRIVATE KEY-----[\s\S]*?-----END\s+(?:RSA\s+|EC\s+|OPENSSH\s+)?PRIVATE KEY-----`}, diff --git a/internal/security/scanner.go b/internal/security/scanner.go index a793cdee5c..e1df3743fd 100644 --- a/internal/security/scanner.go +++ b/internal/security/scanner.go @@ -79,6 +79,42 @@ func (p *Pipeline) Scan(text string) ScanResult { return aggregate } +// wholeValueScanner masks only the secrets whose match is the entire value. +// Pipeline.ScanWholeValueSecrets uses it to rescan bytes an earlier pass has +// already redacted without mistaking a redaction placeholder for a secret. +type wholeValueScanner interface { + ScanWholeValueSecrets(text string) ScanResult +} + +// ScanWholeValueSecrets runs only the whole-value masking of the pipeline's +// scanners: registered runtime values and private-key blocks. Normalizers and +// value patterns are skipped, because the leaf scan has already applied them to +// the decoded document, and re-running them over serialized bytes can only +// damage the redactions they produced (#5705). +func (p *Pipeline) ScanWholeValueSecrets(text string) ScanResult { + aggregate := ScanResult{Safe: true, Sanitized: text} + current := text + for _, s := range p.scanners { + w, ok := s.(wholeValueScanner) + if !ok { + continue + } + result := w.ScanWholeValueSecrets(current) + aggregate.Findings = append(aggregate.Findings, result.Findings...) + if !result.Safe { + aggregate.Safe = false + } + if result.Sanitized != "" { + current = result.Sanitized + aggregate.Sanitized = current + } + } + if aggregate.Sanitized == text { + aggregate.Sanitized = "" // no changes + } + return aggregate +} + // InputPipeline returns the standard input scanning pipeline for // untrusted text entering the agent. Order matters: // 1. UnicodeNormalizer — strip invisible chars, normalize fullwidth diff --git a/internal/security/scanner_test.go b/internal/security/scanner_test.go index 0399ad60fd..8564b6ef33 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -2,6 +2,7 @@ package security import ( "encoding/json" + "fmt" "strings" "testing" @@ -261,6 +262,40 @@ func TestSecretRedactor(t *testing.T) { assert.True(t, result.Safe || !hasFinding(result, "db_connection_password")) }) + // A real password can look like a mask placeholder: the placeholder shape + // (4 characters and "...") is 7 bytes, and db_connection_password accepts a + // value of 4 or more, so a shape test in the redactor skipped it and left + // the password in the output (#5705). + t.Run("db password shaped like a mask placeholder redacted", func(t *testing.T) { + result := r.Scan("postgres://user:abcd...@host:5432/db") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "db_connection_password")) + assert.Equal(t, "postgres://user:***@host:5432/db", result.Sanitized) + }) + + // Rescanning redacted text with a full Scan re-masks the placeholder: a + // seven-byte placeholder is shorter than ten, so Mask returns "***". The + // text stays redacted; only the informative prefix is lost. Callers that + // rescan bytes an earlier pass redacted use ScanWholeValueSecrets, which + // runs no value pattern and leaves the placeholder alone. + t.Run("db password placeholder remasked on a full rescan", func(t *testing.T) { + first := r.Scan("postgres://user:hunter2secret@host:5432/db") + require.False(t, first.Safe) + require.Equal(t, "postgres://user:hunt...@host:5432/db", first.Sanitized) + + second := r.Scan(first.Sanitized) + assert.Equal(t, "postgres://user:***@host:5432/db", second.Sanitized, + "a placeholder is still redacted, never left as itself") + assert.False(t, second.Safe) + }) + + t.Run("whole-value rescan leaves a placeholder intact", func(t *testing.T) { + const redacted = "postgres://user:hunt...@host:5432/db" + result := r.ScanWholeValueSecrets(redacted) + assert.True(t, result.Safe) + assert.Empty(t, result.Sanitized, "the earlier redaction must survive a whole-value rescan") + }) + t.Run("db password with multiple @ redacted", func(t *testing.T) { result := r.Scan("postgres://user:P@ss@w0rd@host:5432/db") assert.False(t, result.Safe) @@ -382,6 +417,269 @@ func TestSecretRedactor(t *testing.T) { assert.True(t, json.Valid([]byte(result.Sanitized)), "output is not valid JSON: %s", result.Sanitized) }) + + t.Run("env assignment does not eat escaping backslash in JSON string", func(t *testing.T) { + // Regression test (#5705): [^\s"'}\]),;]{8,} previously consumed \ + // inside JSON string values before an escaped quote, leaving unescaped + // quote syntax like token_usage = metr..."token_usage"). + tokenVar := "token" + "_usage" + input := fmt.Sprintf(`{"remediation": "Guard against null values with %s = metrics.get(\"token_usage\") or {}"}`, tokenVar) + result := r.Scan(input) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "env_assignment")) + assert.True(t, json.Valid([]byte(result.Sanitized)), + "output must remain valid JSON: %s", result.Sanitized) + assert.Contains(t, result.Sanitized, `\"token_usage\"`) + }) + + t.Run("env assignment redacts credentials containing backslashes", func(t *testing.T) { + result := r.Scan(`TOKEN=ab\cdEFGHijkl`) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "env_assignment")) + assert.NotContains(t, result.Sanitized, `ab\cdEFGHijkl`) + + // Boundary test: exactly 8 characters containing multiple backslashes + resultBoundary := r.Scan(`TOKEN=a\b\c\def`) + assert.False(t, resultBoundary.Safe) + assert.True(t, hasFinding(resultBoundary, "env_assignment")) + assert.NotContains(t, resultBoundary.Sanitized, `a\b\c\def`) + + // Trailing backslash before boundary + resultTrailing := r.Scan(`TOKEN=abcdefg\`) + assert.False(t, resultTrailing.Safe) + assert.True(t, hasFinding(resultTrailing, "env_assignment")) + assert.NotContains(t, resultTrailing.Sanitized, `abcdefg\`) + + // Exact-minimum-length boundary tests (8 chars) ending in backslash before quote delimiters + resultSingleQuote := r.Scan("TOKEN='abcdefg\\'") + assert.False(t, resultSingleQuote.Safe) + assert.True(t, hasFinding(resultSingleQuote, "env_assignment")) + assert.NotContains(t, resultSingleQuote.Sanitized, "abcdefg") + assert.Contains(t, resultSingleQuote.Sanitized, `\'`) + + resultDoubleQuote := r.Scan(`TOKEN="abcdefg\""`) + assert.False(t, resultDoubleQuote.Safe) + assert.True(t, hasFinding(resultDoubleQuote, "env_assignment")) + assert.NotContains(t, resultDoubleQuote.Sanitized, "abcdefg") + assert.Contains(t, resultDoubleQuote.Sanitized, `\"`) + }) + + t.Run("db connection redacts password containing backslashes", func(t *testing.T) { + result := r.Scan(`postgres://user:pa\ss@host:5432/db`) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "db_connection_password")) + assert.NotContains(t, result.Sanitized, `pa\ss`) + + // Boundary test: exactly 4 characters containing interior backslash + resultInterior := r.Scan(`postgres://user:p\ss@host:5432/db`) + assert.False(t, resultInterior.Safe) + assert.True(t, hasFinding(resultInterior, "db_connection_password")) + assert.NotContains(t, resultInterior.Sanitized, `p\ss`) + + // Boundary test: trailing backslash before delimiter @ + resultTrailing := r.Scan(`postgres://user:p\s\@host:5432/db`) + assert.False(t, resultTrailing.Safe) + assert.True(t, hasFinding(resultTrailing, "db_connection_password")) + assert.NotContains(t, resultTrailing.Sanitized, `p\s\`) + }) + + t.Run("auth header redacts credentials containing backslashes", func(t *testing.T) { + result := r.Scan(`Authorization: Bearer ab\cdEFGHijkl1234`) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "auth_header")) + assert.NotContains(t, result.Sanitized, `ab\cdEFGHijkl1234`) + + // Boundary test: exactly 12 characters containing multiple backslashes + resultBoundary := r.Scan(`Authorization: Bearer a\b\c\d\e\f\g`) + assert.False(t, resultBoundary.Safe) + assert.True(t, hasFinding(resultBoundary, "auth_header")) + assert.NotContains(t, resultBoundary.Sanitized, `a\b\c\d\e\f\g`) + + // Exact-minimum-length boundary tests (12 chars) ending in backslash before quote delimiters + resAuthSingle := r.Scan("authorization: 'Bearer abcdefghijk\\'") + assert.False(t, resAuthSingle.Safe) + assert.True(t, hasFinding(resAuthSingle, "auth_header")) + assert.NotContains(t, resAuthSingle.Sanitized, "abcdefghijk") + assert.Contains(t, resAuthSingle.Sanitized, `\'`) + + resAuthDouble := r.Scan(`authorization: "Bearer abcdefghijk\""`) + assert.False(t, resAuthDouble.Safe) + assert.True(t, hasFinding(resAuthDouble, "auth_header")) + assert.NotContains(t, resAuthDouble.Sanitized, "abcdefghijk") + assert.Contains(t, resAuthDouble.Sanitized, `\"`) + + resAuthUnprefixedSingle := r.Scan("authorization: 'abcdefghijk\\'") + assert.False(t, resAuthUnprefixedSingle.Safe) + assert.True(t, hasFinding(resAuthUnprefixedSingle, "auth_header")) + assert.NotContains(t, resAuthUnprefixedSingle.Sanitized, "abcdefghijk") + assert.Contains(t, resAuthUnprefixedSingle.Sanitized, `\'`) + + resAuthUnprefixedDouble := r.Scan(`authorization: "abcdefghijk\""`) + assert.False(t, resAuthUnprefixedDouble.Safe) + assert.True(t, hasFinding(resAuthUnprefixedDouble, "auth_header")) + assert.NotContains(t, resAuthUnprefixedDouble.Sanitized, "abcdefghijk") + assert.Contains(t, resAuthUnprefixedDouble.Sanitized, `\"`) + }) + + t.Run("json_field with embedded escaped quote preserves valid JSON", func(t *testing.T) { + input := `{"password": "abcdefghijkl\"rest"}` + result := r.Scan(input) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.True(t, json.Valid([]byte(result.Sanitized)), + "output must remain valid JSON: %s", result.Sanitized) + assert.NotContains(t, result.Sanitized, "abcdefghijkl") + }) + + t.Run("json_field masks backslashes in literal quoted values", func(t *testing.T) { + result := r.Scan(`'password': 'ab\\cdef'`) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, `ab\\cdef`) + }) + + t.Run("json_field handles escaped apostrophe through the full value", func(t *testing.T) { + result := r.Scan(`'password': 'abcdefgh\'remaining_secret'`) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "remaining_secret") + }) + + t.Run("json_field counts literal trailing backslash toward minimum", func(t *testing.T) { + result := r.Scan("'password': 'abcdefg\\'") + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "abcdefg") + }) + + t.Run("json_field redacts a double-quoted value ending in a literal backslash", func(t *testing.T) { + // The strict double-quoted branch reads \" as an escaped quote and then + // needs another quote to close, so a value that ends in one literal + // backslash right before its closing quote matched no branch at all. + // Main's `"([^"]{8,})"` masked it, and a log line can carry a password + // with a trailing backslash (#5705). + result := r.Scan("\"password\": \"Abc123xyzQ\\\"\nnext line\n") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "Abc123xyzQ") + }) + + t.Run("json_field redacts a double-quoted value ending in a literal backslash before a field", func(t *testing.T) { + result := r.Scan(`{"password": "Abc123xyzQ\"}`) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "Abc123xyzQ") + }) + + t.Run("json_field redacts a double-quoted value folded across lines", func(t *testing.T) { + // A YAML or log string can fold a double-quoted value across physical + // lines. The strict branch excludes raw CR/LF, so the value must still be + // matchable when its closing quote ends the field or the line (#5705). + result := r.Scan("\"password\": \"line1\nline2line3\"\nnext line\n") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "line2line3") + }) + + t.Run("json_field handles doubled apostrophe in YAML scalar", func(t *testing.T) { + result := r.Scan("'password': 'abcdefgh''remaining_secret'") + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "remaining_secret") + }) + + t.Run("json_field keeps YAML single-quoted value valid when doubled quote falls in the mask prefix", func(t *testing.T) { + // The mask prefix would end on half of the doubled '' pair, leaving a + // lone quote that closes the YAML string early. The value must fall back + // to the fixed placeholder instead (#5705). + result := r.Scan("'api_token': 'abc''defghijk'") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "defghijk") + assert.Equal(t, "'api_token': '***'", result.Sanitized, + "a prefix carrying a quote must not be written back") + }) + + t.Run("json_field handles backslash followed by physical newline", func(t *testing.T) { + result := r.Scan("'password': 'abcdefgh\\\nijklmnop'") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "ijklmnop") + }) + + t.Run("json_field handles adjacent sensitive YAML fields with trailing backslash", func(t *testing.T) { + input := "'password': 'abcdefgh\\'\n'secret': 'ijklmnop'" + result := r.Scan(input) + assert.False(t, result.Safe) + findings := 0 + for _, f := range result.Findings { + if f.Name == "json_field" { + findings++ + } + } + assert.Equal(t, 2, findings, "both adjacent fields must be detected and redacted") + assert.NotContains(t, result.Sanitized, "abcdefgh") + assert.NotContains(t, result.Sanitized, "ijklmnop") + }) + + t.Run("json_field trailing backslash in a flow mapping keeps the next field", func(t *testing.T) { + // Go's regexp alternation is leftmost-first, so the escape-reading branch + // used to match first and read the closing quote as an escaped quote, + // running on to the next quote on the same line and swallowing the field + // that follows in a YAML flow mapping (#5705). + input := `{'api_key': 'abcdefghi\', 'x': 'yyyyyyyyyyyy'}` + result := r.Scan(input) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "abcdefghi") + assert.Contains(t, result.Sanitized, "'x': 'yyyyyyyyyyyy'", "the field that follows must survive intact") + }) + + t.Run("json_field redacts a single-quoted value spanning a raw newline", func(t *testing.T) { + // Base matched `'([^']{8,})'`, which crosses newlines. Handling escaped + // delimiters must not narrow the pattern: a raw newline inside the + // value is still part of the secret. + result := r.Scan("'password': 'line1\nline2line3'") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "line2line3") + }) + + t.Run("json_field multi-line value does not swallow the next field", func(t *testing.T) { + input := "'password': 'line1\nline2line3'\n'secret': 'ijklmnop'" + result := r.Scan(input) + assert.False(t, result.Safe) + findings := 0 + for _, f := range result.Findings { + if f.Name == "json_field" { + findings++ + } + } + assert.Equal(t, 2, findings, "both fields must be detected and redacted") + assert.NotContains(t, result.Sanitized, "line2line3") + assert.NotContains(t, result.Sanitized, "ijklmnop") + }) + + t.Run("json_field minimum counts runes, not bytes", func(t *testing.T) { + // Three CJK characters are nine bytes. The {8,} quantifier the value + // pattern used before it spanned escaped quotes counted characters, so + // a byte count would start masking values it never masked. + short := r.Scan(`{"password": "秘密の鍵"}`) + assert.True(t, short.Safe, "a value below the minimum must not be masked: %s", short.Sanitized) + + exact := r.Scan(`{"password": "秘密の鍵ですよね"}`) // 8 runes + assert.False(t, exact.Safe) + assert.True(t, hasFinding(exact, "json_field")) + }) + + t.Run("mask does not leave dangling escape sequence", func(t *testing.T) { + input1 := `Authorization: Bearer abc\ndefghijkl` + result1 := r.Scan(input1) + assert.False(t, result1.Safe) + assert.Equal(t, "Authorization: Bearer ***", result1.Sanitized) + + input2 := `Authorization: Bearer \u1234efghijkl` + result2 := r.Scan(input2) + assert.False(t, result2.Safe) + assert.Equal(t, "Authorization: Bearer ***", result2.Sanitized) + }) } func TestSSRFValidator(t *testing.T) { diff --git a/internal/security/testdata/review-result.schema.json b/internal/security/testdata/review-result.schema.json new file mode 100644 index 0000000000..2a41318da4 --- /dev/null +++ b/internal/security/testdata/review-result.schema.json @@ -0,0 +1,208 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "review-result.schema.json", + "title": "Review Agent Result", + "description": "Structured output from the review agent, validated by the harness before the post-script runs (ADR 0022).", + "type": "object", + "additionalProperties": false, + "required": ["action", "pr_number", "repo"], + "properties": { + "action": { + "type": "string", + "enum": ["approve", "request-changes", "comment", "reject", "failure"] + }, + "pr_number": { "type": "integer", "minimum": 1 }, + "repo": { "type": "string", "pattern": "^[a-zA-Z0-9._-]+(/[a-zA-Z0-9._-]+)+$" }, + "head_sha": { "type": "string", "pattern": "^[0-9a-fA-F]{40}$|^[0-9a-fA-F]{64}$" }, + "body": { "type": "string", "minLength": 1 }, + "findings": { + "type": "array", + "items": { "$ref": "#/$defs/finding" }, + "minItems": 1 + }, + "reason": { + "type": "string", + "enum": ["tool-failure", "missing-context", "ambiguous-findings", "token-limit", "time-budget"] + }, + "dispositions": { + "type": "array", + "description": "One entry for every open finding id from the prior projection (status absent, open, or reclassified). Ids already resolved or dismissed by a human are closed and must not be answered. A reclassified entry needs a finding with the same id in findings; a dismissed_by_human entry is accepted only when the post-script verifies a resolved review thread from an eligible reviewer, and never for a high or critical finding. Omit on a first review.", + "items": { "$ref": "#/$defs/disposition" } + }, + "label_actions": { + "$ref": "#/$defs/label_actions" + }, + "risk_assessment": { + "description": "Score and level must be consistent: 1=low, 2=moderate, 3=elevated, 4=high, 5=critical.", + "type": "object", + "required": ["score", "level", "rationale"], + "properties": { + "score": { "type": "integer", "minimum": 1, "maximum": 5 }, + "level": { + "type": "string", + "enum": ["low", "moderate", "elevated", "high", "critical"] + }, + "tier1_signals": { + "type": "array", + "items": { "$ref": "#/$defs/risk_signal" } + }, + "tier2_signals": { + "type": "array", + "items": { "$ref": "#/$defs/risk_signal" } + }, + "tier3_signals": { + "type": "array", + "items": { "$ref": "#/$defs/risk_signal" } + }, + "rationale": { "type": "string", "minLength": 1 }, + "degraded": { "type": "string", "minLength": 1 } + }, + "additionalProperties": false, + "allOf": [ + { "if": { "properties": { "score": { "const": 1 } } }, "then": { "properties": { "level": { "const": "low" } } } }, + { "if": { "properties": { "score": { "const": 2 } } }, "then": { "properties": { "level": { "const": "moderate" } } } }, + { "if": { "properties": { "score": { "const": 3 } } }, "then": { "properties": { "level": { "const": "elevated" } } } }, + { "if": { "properties": { "score": { "const": 4 } } }, "then": { "properties": { "level": { "const": "high" } } } }, + { "if": { "properties": { "score": { "const": 5 } } }, "then": { "properties": { "level": { "const": "critical" } } } } + ] + }, + "risk_gated": { + "type": "boolean", + "description": "Set by post-processing when a risk assessment downgrades the verdict. Not present in agent output — added by the harness post-script." + } + }, + "allOf": [ + { + "if": { "properties": { "action": { "const": "approve" } }, "required": ["action"] }, + "then": { "required": ["body", "head_sha"] } + }, + { + "if": { "properties": { "action": { "const": "request-changes" } }, "required": ["action"] }, + "then": { "required": ["body", "head_sha", "findings"] } + }, + { + "if": { "properties": { "action": { "const": "comment" } }, "required": ["action"] }, + "then": { "required": ["body", "head_sha"] } + }, + { + "if": { "properties": { "action": { "const": "reject" } }, "required": ["action"] }, + "then": { "required": ["body", "head_sha", "findings"] } + }, + { + "if": { "properties": { "action": { "const": "failure" } }, "required": ["action"] }, + "then": { "required": ["reason"] } + }, + { + "if": { + "properties": { "action": { "const": "approve" } }, + "required": ["action"] + }, + "then": { + "not": { + "properties": { + "findings": { + "contains": { + "properties": { "category": { "const": "protected-path" } }, + "required": ["category"] + } + } + }, + "required": ["findings"] + } + } + } + ], + "$defs": { + "finding": { + "type": "object", + "required": ["severity", "category", "file", "description"], + "properties": { + "severity": { "type": "string", "enum": ["critical", "high", "medium", "low", "info"] }, + "category": { + "type": "string", + "description": "Canonical dimension categories (the dimension table in skills/pr-review/references/re-review.md, mirrored by allowed_category in pre-review and post-review) plus the non-dimensional categories. Keep all copies in sync.", + "enum": [ + "logic-error", "nil-deref", "off-by-one", "edge-case", "api-contract", "missing-test", "test-inadequate", "pattern-violation", "test-weakened", "test-removed", "mock-loosened", "assertion-weakened", "coverage-reduced", "test-poisoning", "split-payload", "stale-reference", + "auth-bypass", "rbac-violation", "data-exposure", "privilege-escalation", "injection-vuln", "sandbox-escape", "xss", "ssrf", "insecure-deserialization", "prompt-injection", "unicode-steganography", "bidi-override", "homoglyph-attack", "instruction-smuggling", "fail-open", "permission-expansion", "permission-reduction", "role-escalation", "workflow-permission", "secret-exposure", + "scope-exceeded", "tier-mismatch", "unauthorized-change", "scope-creep", "missing-authorization", "misleading-label", "design-direction", "complexity-ratio", "misplaced-abstraction", "architectural-conflict", "design-smell", "over-engineering", "under-engineering", "scope-bundling", + "naming-convention", "error-handling-idiom", "api-shape", "code-organization", "doc-style", "pattern-inconsistency", + "stale-doc", "missing-doc", "incorrect-doc", "incomplete-doc", + "breaking-api", "breaking-schema", "breaking-config", "breaking-cli", "missing-deprecation", "missing-version-bump", "backward-incompatible", + "uxd-evaluate-code-heuristics", + "protected-path", "provenance-warning", "scope-authorization-implicit", "sub-agent-failure" + ] + }, + "file": { "type": "string", "minLength": 1 }, + "line": { "type": "integer", "minimum": 1 }, + "description": { "type": "string", "minLength": 1 }, + "remediation": { "type": "string" }, + "actionable": { + "type": "boolean", + "description": "When true with a non-empty remediation, routes the verdict to request-changes so the fix agent can address the finding automatically." + }, + "id": { + "type": "string", + "pattern": "^f_[a-zA-Z0-9]+$", + "description": "Stable id copied from the prior projection. Omit on a new finding; the post-script assigns f_ plus random hex. Do not derive it from the file, line, or text." + }, + "dimension": { + "type": "string", + "description": "Name of the pr-review persona that produced the finding. Orchestrator-only findings omit it." + } + }, + "additionalProperties": false + }, + "disposition": { + "type": "object", + "required": ["id", "status", "rationale", "evidence"], + "properties": { + "id": { "type": "string", "pattern": "^f_[a-zA-Z0-9]+$" }, + "status": { + "type": "string", + "enum": ["open", "resolved_by_change", "reclassified", "dismissed_by_human"] + }, + "rationale": { "type": "string", "minLength": 1 }, + "evidence": { + "type": "string", + "description": "Code change or human resolution that supports the status. Empty only for open." + } + }, + "additionalProperties": false + }, + "label_actions": { + "type": "object", + "required": ["reason", "actions"], + "properties": { + "reason": { + "type": "string", + "minLength": 1, + "description": "Single sentence explaining why these labels are being applied or removed" + }, + "actions": { + "type": "array", + "minItems": 1, + "maxItems": 20, + "items": { + "type": "object", + "required": ["action", "label"], + "properties": { + "action": { "type": "string", "enum": ["add", "remove"] }, + "label": { "type": "string", "minLength": 1, "pattern": "^[a-zA-Z0-9._/: +-]+$" } + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "risk_signal": { + "type": "object", + "required": ["dimension", "value"], + "properties": { + "dimension": { "type": "string", "minLength": 1 }, + "value": { "type": "string", "minLength": 1 } + }, + "additionalProperties": false + } + } +} diff --git a/internal/security/testdata/review-result.schema.pin b/internal/security/testdata/review-result.schema.pin new file mode 100644 index 0000000000..c256b91513 --- /dev/null +++ b/internal/security/testdata/review-result.schema.pin @@ -0,0 +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