diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 3bf3084f8e..a543bd51cb 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -694,7 +694,29 @@ remaining file is still scanned and redacted, and the run fails closed afterward 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. +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 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/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") +}