diff --git a/internal/cli/run.go b/internal/cli/run.go
index ea2f08329d..e78b590b94 100644
--- a/internal/cli/run.go
+++ b/internal/cli/run.go
@@ -3436,7 +3436,8 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep
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))
+ printer.StepFail(failureLine("Output scan failed", err, progressVerbosity))
+ return fmt.Errorf("post-agent output scan failed: %w", err)
}
// Extract sandbox-side security findings for audit trail.
@@ -7012,6 +7013,10 @@ 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)
+}
+
+func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, printer *ui.Printer, writeFile func(string, []byte, os.FileMode) error) error {
quiet := config.ProgressIsQuiet(progressVerbosity)
if _, err := os.Stat(outputDir); os.IsNotExist(err) {
printer.StepInfo("No output files to scan")
@@ -7061,12 +7066,180 @@ func scanOutputFiles(outputDir, traceID, progressVerbosity string, printer *ui.P
printer.StepWarn(fmt.Sprintf("Could not read %s: %v", relPath, readErr))
return nil
}
+ isJSONL := strings.EqualFold(filepath.Ext(path), ".jsonl") || strings.EqualFold(filepath.Ext(path), ".ndjson")
+ if isJSONL {
+ out, jsonLineFindings, jsonLineDetails, scanErr := sanitizeJSONLines(content, pipeline)
+ if scanErr != nil {
+ return fmt.Errorf("could not sanitize JSONL output: %w", scanErr)
+ }
+ if jsonLineFindings > 0 {
+ findingCount += jsonLineFindings
+ for _, f := range jsonLineDetails {
+ if !quiet {
+ printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s: %s", f.Name, filepath.Base(path), f.Detail))
+ }
+ security.AppendFinding(findingsPath, security.TracedFinding{
+ TraceID: traceID, Timestamp: time.Now().UTC().Format(time.RFC3339),
+ Phase: "host_output", Finding: f,
+ })
+ }
+ // JSONL record handling is complete above; preserve the writer
+ // error contract and quiet-mode path redaction.
+ if writeErr := writeFile(path, out, 0o644); writeErr != nil {
+ if quiet {
+ return fmt.Errorf("could not write sanitized output file")
+ }
+ return fmt.Errorf("could not write sanitized %s: %w", filepath.Base(path), writeErr)
+ }
+ }
+ return nil
+ }
+ relPath, _ := filepath.Rel(outputDir, path)
+
+ ext := strings.ToLower(filepath.Ext(path))
+ isJSONL = ext == ".jsonl" || ext == ".ndjson"
+
+ // If the file is valid JSON (and not JSONL or containing duplicate keys), structurally
+ // sanitize keys and string leaves to guarantee that redaction never breaks JSON syntax
+ // and fails closed (#5705).
+ if !isJSONL && !hasDuplicateJSONKeys(content) {
+ dec := json.NewDecoder(bytes.NewReader(content))
+ dec.UseNumber()
+ var jsonVal any
+ if dec.Decode(&jsonVal) == nil {
+ var trailing any
+ if dec.Decode(&trailing) == io.EOF {
+ sanitizedVal, findings := sanitizeJSONStructure(jsonVal, pipeline)
+ if len(findings) > 0 {
+ findingCount += len(findings)
+ structuralFindings := findings
+ for _, f := range findings {
+ 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,
+ })
+ }
+ var buf bytes.Buffer
+ enc := json.NewEncoder(&buf)
+ enc.SetEscapeHTML(false)
+ if bytes.Contains(bytes.TrimRight(content, "\r\n"), []byte("\n")) {
+ enc.SetIndent("", " ")
+ }
+ if err := enc.Encode(sanitizedVal); err != nil {
+ if !quiet {
+ printer.StepWarn(fmt.Sprintf("Could not marshal sanitized JSON %s: %v; falling back to text scan", relPath, err))
+ }
+ // Fall through to plain text scan below instead of failing open.
+ } else {
+ marshaled := buf.Bytes()
+ // Backstop the serialized output. If text redaction finds
+ // another secret, only accept it when the result remains valid
+ // JSON; otherwise discard the potentially malformed payload.
+ backstop := pipeline.Scan(string(marshaled))
+ if len(backstop.Findings) > 0 {
+ changed := false
+ privateKey := false
+ for _, finding := range backstop.Findings {
+ if finding.Name == "private_key" {
+ privateKey = true
+ }
+ }
+ changed = privateKey || len(structuralFindings) == 0 || backstopHasNewFinding(backstop.Findings, structuralFindings)
+ if changed {
+ findingCount += len(backstop.Findings)
+ for _, f := range backstop.Findings {
+ if !quiet {
+ printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s (backstop): %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 backstop.Sanitized != "" && (privateKey || len(structuralFindings) == 0 || backstopHasNewFinding(backstop.Findings, structuralFindings)) {
+ if privateKey || !json.Valid([]byte(backstop.Sanitized)) {
+ marshaled = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`)
+ } else {
+ marshaled = []byte(backstop.Sanitized)
+ }
+ }
+ }
+ }
+ if writeErr := writeFile(path, marshaled, 0o644); writeErr != nil {
+ if quiet {
+ return fmt.Errorf("could not write sanitized output file")
+ }
+ if !isJSONL {
+ return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr)
+ }
+ return fmt.Errorf("could not write sanitized output file: %w", writeErr)
+ }
+ return nil
+ }
+ } else {
+ // Scan encoded JSON for patterns spanning separate leaves. Such a
+ // match cannot be safely applied as raw text, so replace the
+ // whole document with a valid fail-closed marker.
+ var buf bytes.Buffer
+ enc := json.NewEncoder(&buf)
+ enc.SetEscapeHTML(false)
+ if err := enc.Encode(jsonVal); err != nil {
+ return fmt.Errorf("could not encode JSON output for security scan")
+ }
+ backstop := pipeline.Scan(buf.String())
+ hasNewFinding := false
+ privateKey := false
+ for _, f := range backstop.Findings {
+ if f.Name == "private_key" {
+ privateKey = true
+ hasNewFinding = true
+ } else if f.Name == "runtime_secret" {
+ hasNewFinding = true
+ }
+ }
+ if !hasNewFinding {
+ return nil
+ }
+ findingCount += len(backstop.Findings)
+ for _, f := range backstop.Findings {
+ if !quiet {
+ printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s (backstop): %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,
+ })
+ }
+ var finalBytes []byte
+ if privateKey || backstop.Sanitized == "" || !json.Valid([]byte(backstop.Sanitized)) {
+ finalBytes = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`)
+ } else {
+ finalBytes = []byte(backstop.Sanitized)
+ }
+ if writeErr := writeFile(path, finalBytes, 0o644); writeErr != nil {
+ if quiet {
+ return fmt.Errorf("could not write sanitized output file")
+ }
+ return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr)
+ }
+ return nil
+ }
+ }
+ }
+ }
+
+ // Non-JSON files or fallback: 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))
@@ -7081,12 +7254,21 @@ func scanOutputFiles(outputDir, traceID, progressVerbosity string, printer *ui.P
}
// Sanitized may be empty when all content was invisible characters.
out := result.Sanitized
- if writeErr := os.WriteFile(path, []byte(out), 0o644); writeErr != nil {
+ // Duplicate-key JSON and malformed/non-JSON inputs use the raw-text
+ // fallback. If a valid JSON document reaches this path (for example,
+ // because it has duplicate keys), preserve the valid structure rather
+ // than writing a cross-value redaction that creates invalid JSON.
+ if json.Valid(content) && !json.Valid([]byte(out)) {
+ if !quiet {
+ printer.StepWarn(fmt.Sprintf("Text redaction would invalidate JSON in %s; replacing output with a redacted JSON marker", relPath))
+ }
+ out = `{"error":"output removed because text redaction would invalidate JSON"}`
+ }
+ if writeErr := writeFile(path, []byte(out), 0o644); writeErr != nil {
if quiet {
- unwritable++
- } else {
- printer.StepWarn(fmt.Sprintf("Could not write sanitized %s: %v", relPath, writeErr))
+ return fmt.Errorf("could not write sanitized output file")
}
+ return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr)
}
}
return nil
@@ -7109,6 +7291,316 @@ func scanOutputFiles(outputDir, traceID, progressVerbosity string, printer *ui.P
return nil
}
+type jsonContainerFrame struct {
+ isObject bool
+ expectingKey bool
+ keys map[string]bool
+}
+
+func sanitizeJSONLines(content []byte, pipeline *security.Pipeline) ([]byte, int, []security.Finding, error) {
+ var out bytes.Buffer
+ findings := 0
+ var allFindings []security.Finding
+ // Keep a whole-stream pass for multiline patterns such as PEM private keys
+ // that can span otherwise-valid JSONL records. We only use it as a detector:
+ // raw replacement would consume JSON framing, so matching streams are
+ // replaced record-by-record with valid fail-closed JSON markers.
+ streamScan := pipeline.Scan(string(content))
+ streamHasPrivateKey := false
+ for _, finding := range streamScan.Findings {
+ streamHasPrivateKey = streamHasPrivateKey || finding.Name == "private_key"
+ }
+ for len(content) > 0 {
+ line := content
+ newline := bytes.IndexByte(content, '\n')
+ hasNewline := newline >= 0
+ if hasNewline {
+ line = content[:newline]
+ content = content[newline+1:]
+ } else {
+ content = nil
+ }
+ trimmed := bytes.TrimSpace(line)
+ if len(trimmed) > 0 {
+ if streamHasPrivateKey {
+ line = []byte(`{"error":"output removed because output contained a cross-record private key"}`)
+ if len(allFindings) == 0 {
+ findings += len(streamScan.Findings)
+ allFindings = append(allFindings, streamScan.Findings...)
+ }
+ } else if !json.Valid(trimmed) {
+ result := pipeline.Scan(string(line))
+ if len(result.Findings) > 0 {
+ findings += len(result.Findings)
+ allFindings = append(allFindings, result.Findings...)
+ line = []byte(result.Sanitized)
+ }
+ } else {
+ var value any
+ dec := json.NewDecoder(bytes.NewReader(trimmed))
+ dec.UseNumber()
+ if err := dec.Decode(&value); err != nil {
+ return nil, findings, allFindings, err
+ }
+ sanitized, fs := sanitizeJSONStructure(value, pipeline)
+ findings += len(fs)
+ allFindings = append(allFindings, fs...)
+ if hasDuplicateJSONKeys(trimmed) {
+ result := pipeline.Scan(string(line))
+ if len(fs) > 0 {
+ line = []byte(`{"error":"output removed because structural findings cannot be safely applied to duplicate-key JSON"}`)
+ } else if len(result.Findings) > 0 {
+ findings += len(result.Findings)
+ allFindings = append(allFindings, result.Findings...)
+ if result.Sanitized != "" {
+ line = []byte(result.Sanitized)
+ if !json.Valid(line) {
+ line = []byte(`{"error":"output removed because text redaction would invalidate JSON"}`)
+ }
+ }
+ }
+ } else {
+ needsRewrite := len(fs) > 0
+ if !needsRewrite {
+ var encodedOriginal bytes.Buffer
+ enc := json.NewEncoder(&encodedOriginal)
+ enc.SetEscapeHTML(false)
+ if err := enc.Encode(value); err != nil {
+ return nil, findings, allFindings, err
+ }
+ encodedBytes := bytes.TrimSuffix(encodedOriginal.Bytes(), []byte("\n"))
+ originalBackstop := pipeline.Scan(string(encodedBytes))
+ hasNewFinding := false
+ privateKey := false
+ for _, f := range originalBackstop.Findings {
+ if f.Name == "private_key" {
+ privateKey = true
+ hasNewFinding = true
+ } else if f.Name == "runtime_secret" {
+ hasNewFinding = true
+ }
+ }
+ if hasNewFinding {
+ findings += len(originalBackstop.Findings)
+ allFindings = append(allFindings, originalBackstop.Findings...)
+ if privateKey || originalBackstop.Sanitized == "" || !json.Valid([]byte(originalBackstop.Sanitized)) {
+ line = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`)
+ } else {
+ line = bytes.TrimSuffix([]byte(originalBackstop.Sanitized), []byte("\n"))
+ }
+ }
+ }
+ if needsRewrite {
+ var encoded bytes.Buffer
+ enc := json.NewEncoder(&encoded)
+ enc.SetEscapeHTML(false)
+ if err := enc.Encode(sanitized); err != nil {
+ return nil, findings, allFindings, err
+ }
+ line = bytes.TrimSuffix(encoded.Bytes(), []byte("\n"))
+ backstop := pipeline.Scan(string(line))
+ if len(backstop.Findings) > 0 {
+ findings += len(backstop.Findings)
+ allFindings = append(allFindings, backstop.Findings...)
+ privateKey := false
+ for _, finding := range backstop.Findings {
+ privateKey = privateKey || finding.Name == "private_key"
+ }
+ if privateKey || !json.Valid([]byte(backstop.Sanitized)) {
+ line = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`)
+ } else {
+ line = []byte(backstop.Sanitized)
+ }
+ }
+ }
+ }
+ }
+ }
+ out.Write(line)
+ if hasNewline {
+ out.WriteByte('\n')
+ }
+ }
+ return out.Bytes(), findings, allFindings, nil
+}
+
+func backstopHasNewFinding(backstop, structural []security.Finding) bool {
+ counts := make(map[string]int, len(structural))
+ for _, finding := range structural {
+ counts[finding.Name]++
+ }
+ for _, finding := range backstop {
+ if counts[finding.Name] == 0 {
+ return true
+ }
+ counts[finding.Name]--
+ }
+ return false
+}
+
+// hasDuplicateJSONKeys parses content token by token and returns true if any
+// JSON object within the payload contains duplicate keys.
+func hasDuplicateJSONKeys(content []byte) bool {
+ dec := json.NewDecoder(bytes.NewReader(content))
+ dec.UseNumber()
+ var stack []*jsonContainerFrame
+ for {
+ tok, err := dec.Token()
+ if err != nil {
+ return false
+ }
+ switch t := tok.(type) {
+ case json.Delim:
+ switch t {
+ case '{':
+ stack = append(stack, &jsonContainerFrame{
+ isObject: true,
+ expectingKey: true,
+ keys: make(map[string]bool),
+ })
+ case '[':
+ stack = append(stack, &jsonContainerFrame{
+ isObject: false,
+ })
+ case '}', ']':
+ if len(stack) > 0 {
+ stack = stack[:len(stack)-1]
+ }
+ if len(stack) > 0 && stack[len(stack)-1].isObject {
+ stack[len(stack)-1].expectingKey = true
+ }
+ }
+ case string:
+ if len(stack) > 0 && stack[len(stack)-1].isObject {
+ top := stack[len(stack)-1]
+ if top.expectingKey {
+ if top.keys[t] {
+ return true
+ }
+ top.keys[t] = true
+ top.expectingKey = false
+ } else {
+ top.expectingKey = true
+ }
+ }
+ default:
+ if len(stack) > 0 && stack[len(stack)-1].isObject {
+ stack[len(stack)-1].expectingKey = true
+ }
+ }
+ }
+}
+
+var sensitiveJSONKeyRegex = regexp.MustCompile(`(?i)(?:key|token|secret|password|credential|auth)`)
+
+// sanitizeJSONStructure recursively visits all keys and string values in parsed JSON data,
+// scans each key and string leaf using the pipeline, and collects any findings.
+func sanitizeJSONStructure(v any, pipeline *security.Pipeline) (any, []security.Finding) {
+ var findings []security.Finding
+ switch val := v.(type) {
+ case string:
+ res := pipeline.Scan(val)
+ if len(res.Findings) > 0 {
+ findings = append(findings, res.Findings...)
+ if res.Sanitized != "" {
+ return res.Sanitized, findings
+ }
+ return "", findings
+ }
+ return val, nil
+ case map[string]any:
+ newMap := make(map[string]any, len(val))
+ keys := make([]string, 0, len(val))
+ for k := range val {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ // Reserve clean original names before assigning sanitized names so a
+ // secret key can never steal a legitimate key's name/value slot.
+ for _, k := range keys {
+ if keyRes := pipeline.Scan(k); len(keyRes.Findings) == 0 {
+ newMap[k] = nil
+ }
+ }
+ for _, k := range keys {
+ item := val[k]
+ sanitizedKey := k
+ keyRes := pipeline.Scan(k)
+ keyNeedsSanitization := len(keyRes.Findings) > 0
+ if len(keyRes.Findings) > 0 {
+ findings = append(findings, keyRes.Findings...)
+ if keyRes.Sanitized != "" {
+ sanitizedKey = keyRes.Sanitized
+ }
+ }
+ targetKey := sanitizedKey
+ if !keyNeedsSanitization {
+ targetKey = k
+ }
+ if _, exists := newMap[targetKey]; exists && keyNeedsSanitization {
+ for i := 1; ; i++ {
+ cand := fmt.Sprintf("%s_%d", sanitizedKey, i)
+ if _, exists := newMap[cand]; !exists {
+ targetKey = cand
+ break
+ }
+ }
+ }
+ if strVal, ok := item.(string); ok {
+ valRes := pipeline.Scan(strVal)
+ if len(valRes.Findings) > 0 {
+ findings = append(findings, valRes.Findings...)
+ strVal = valRes.Sanitized
+ }
+ if sensitiveJSONKeyRegex.MatchString(sanitizedKey) && len(strVal) >= 8 && !isAlreadyMasked(strVal) {
+ masked := security.Mask(strVal)
+ findings = append(findings, security.Finding{
+ Scanner: "secret_redactor",
+ Name: "json_field",
+ Severity: "high",
+ Detail: fmt.Sprintf("Redacted json_field (%d chars) -> %s", len(strVal), masked),
+ })
+ strVal = masked
+ }
+ newMap[targetKey] = strVal
+ continue
+ }
+ newVal, f := sanitizeJSONStructure(item, pipeline)
+ if len(f) > 0 {
+ findings = append(findings, f...)
+ }
+ newMap[targetKey] = newVal
+ }
+ return newMap, findings
+ case []any:
+ newSlice := make([]any, len(val))
+ for i, item := range val {
+ newVal, f := sanitizeJSONStructure(item, pipeline)
+ if len(f) > 0 {
+ findings = append(findings, f...)
+ }
+ newSlice[i] = newVal
+ }
+ return newSlice, findings
+ case json.Number:
+ res := pipeline.Scan(val.String())
+ if len(res.Findings) > 0 {
+ findings = append(findings, res.Findings...)
+ if res.Sanitized != "" {
+ return res.Sanitized, findings
+ }
+ return "", findings
+ }
+ return val, nil
+ default:
+ return val, nil
+ }
+}
+
+func isAlreadyMasked(value string) bool {
+ return value == "***" || strings.HasSuffix(value, "...") && len(value) == 7
+}
+
// injectTraceID appends the FULLSEND_TRACE_ID to the sandbox .env file.
func injectTraceID(sandboxName, traceID string) error {
if !security.IsShellSafeTraceID(traceID) {
diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go
index 608485e85f..be2d2ce06e 100644
--- a/internal/cli/scan_output_telemetry_test.go
+++ b/internal/cli/scan_output_telemetry_test.go
@@ -2,14 +2,19 @@ package cli
import (
"bytes"
+ "encoding/json"
+ "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"
)
@@ -81,3 +86,493 @@ 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 after the serialized-text backstop.
+ 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.
+ 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-----","BASE64_KEY_MATERIAL_REDACTED","-----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.Contains(t, string(content7), "output removed", "cross-value private-key marker must fail closed")
+ content8, err := os.ReadFile(jsonFile8)
+ require.NoError(t, err)
+ assert.True(t, json.Valid(content8), "backstop handling must preserve valid JSON")
+ assert.Contains(t, string(content8), "output removed", "cross-value backstop match must fail closed")
+ content9, err := os.ReadFile(jsonFile9)
+ require.NoError(t, err)
+ assert.True(t, json.Valid(content9))
+ assert.Contains(t, string(content9), "output removed", "split PEM-like material must fail closed")
+
+ // 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")
+ }
+}
+
+// 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-----","KEY_MATERIAL_BASE64_VALUE_1234567890","-----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.Contains(t, line, "output removed", "cross-value private-key content should fail closed")
+}
+
+func TestSanitizeJSONLinesKeepsCleanDuplicateRecordWhenAnotherRecordChanges(t *testing.T) {
+ pipeline := security.OutputPipeline()
+ content := []byte("{\"a\":1,\"a\":2}\n{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\n")
+ got, findings, _, err := sanitizeJSONLines(content, pipeline)
+ require.NoError(t, err)
+ assert.Positive(t, findings)
+ lines := strings.Split(strings.TrimSuffix(string(got), "\n"), "\n")
+ require.Len(t, lines, 2)
+ assert.Equal(t, `{"a":1,"a":2}`, lines[0], "clean duplicate-key record must remain unchanged")
+ assert.True(t, json.Valid([]byte(lines[1])))
+ assert.NotContains(t, lines[1], "ghp_FAKEtesttoken")
+}
+
+func TestSanitizeJSONLinesFailsClosedForPrivateKeyAcrossRecords(t *testing.T) {
+ pipeline := security.OutputPipeline()
+ begin := "-----BEGIN RSA" + " PRIVATE KEY-----"
+ end := "-----END RSA" + " PRIVATE KEY-----"
+ content := []byte(fmt.Sprintf("[%q]\n[%q]\n[%q]\n", begin, "MIIEpAIBAAKCAQEA0123456789abcdefghijklmnop", end))
+ got, findings, details, err := sanitizeJSONLines(content, pipeline)
+ require.NoError(t, err)
+ assert.Positive(t, findings)
+ require.NotEmpty(t, details)
+ assert.Equal(t, "private_key", details[0].Name)
+ 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)))
+ assert.Contains(t, line, "output removed")
+ }
+}
+
+func TestSanitizeJSONLinesFailsClosedForRawMultilinePEM(t *testing.T) {
+ pipeline := security.OutputPipeline()
+ begin := "-----BEGIN RSA" + " PRIVATE KEY-----"
+ end := "-----END RSA" + " PRIVATE KEY-----"
+ content := []byte(fmt.Sprintf("%s\nMIIEpAIBAAKCAQEA0123456789abcdefghijklmnop\n%s\n", begin, end))
+ got, findings, details, err := sanitizeJSONLines(content, pipeline)
+ require.NoError(t, err)
+ assert.Positive(t, findings)
+ require.NotEmpty(t, details)
+ assert.Equal(t, "private_key", details[0].Name)
+ 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)))
+ assert.Contains(t, line, "output removed")
+ assert.NotContains(t, line, "MIIEpAIBAAKCAQEA")
+ }
+}
+
+func TestScanOutputFiles_JSONLRawMultilinePEMRemainsValid(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "raw_pem.jsonl")
+ begin := "-----BEGIN RSA" + " PRIVATE KEY-----"
+ end := "-----END RSA" + " PRIVATE KEY-----"
+ 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")
+ }
+}
+
+func TestSanitizeJSONLines_DuplicateKeyRecordWithStructuralFindingsFailsClosed(t *testing.T) {
+ pipeline := security.OutputPipeline()
+ // A secret encoded with JSON Unicode escapes in a record that also has duplicate keys.
+ // Raw text scanner doesn't match the unicode escapes, but structural scan decodes and finds it.
+ content := []byte("{\"a\":\"first\",\"a\":\"second\",\"password\":\"\\u0073\\u0065\\u0063\\u0072\\u0065\\u0074_password_1234\"}\n")
+ got, findings, details, err := sanitizeJSONLines(content, pipeline)
+ require.NoError(t, err)
+ assert.Positive(t, findings)
+ require.NotEmpty(t, details)
+ line := strings.TrimSpace(string(got))
+ assert.True(t, json.Valid([]byte(line)))
+ assert.Contains(t, line, "output removed")
+ assert.NotContains(t, line, "password_1234")
+}
+
+func TestSanitizeJSONLines_BackstopNoStructuralFindingsPreservesLineCount(t *testing.T) {
+ const secretVal = `","field2":"`
+ security.ResetRuntimeSecretsForTest()
+ t.Cleanup(security.ResetRuntimeSecretsForTest)
+ require.True(t, security.RegisterRuntimeSecret(secretVal))
+
+ pipeline := security.OutputPipeline()
+ content := []byte("{\"field1\":\"foo\",\"field2\":\"bar\"}\n{\"field3\":\"second record\"}\n")
+ got, findings, details, err := sanitizeJSONLines(content, pipeline)
+ require.NoError(t, err)
+ assert.Positive(t, findings)
+ require.NotEmpty(t, details)
+ assert.Equal(t, 2, strings.Count(string(got), "\n"), "line count must remain exactly 2, no extra blank lines")
+ lines := strings.Split(strings.TrimSuffix(string(got), "\n"), "\n")
+ require.Len(t, lines, 2)
+ assert.True(t, json.Valid([]byte(lines[0])))
+ assert.True(t, json.Valid([]byte(lines[1])))
+ assert.NotContains(t, lines[0], secretVal)
+}
+
+func TestSanitizeJSONLines_NeedsRewriteWithBackstopPrivateKeyFailsClosed(t *testing.T) {
+ pipeline := security.OutputPipeline()
+ begin := "-----BEGIN RSA" + " PRIVATE KEY-----"
+ end := "-----END RSA" + " PRIVATE KEY-----"
+ content := []byte(fmt.Sprintf("{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\",\"pem\":\"%s\\n%s\"}\n", begin, end))
+ got, findings, details, err := sanitizeJSONLines(content, pipeline)
+ require.NoError(t, err)
+ assert.Positive(t, findings)
+ require.NotEmpty(t, details)
+ line := strings.TrimSpace(string(got))
+ assert.True(t, json.Valid([]byte(line)))
+ assert.Contains(t, line, "output removed")
+}
+
+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 := scanOutputFilesWithWriter(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")
+}
+
+func TestScanOutputFiles_QuietJSONWriteFailureIsFatal(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "secret.json")
+ require.NoError(t, os.WriteFile(path, []byte(`{"token":"ghp_FAKEtesttoken000000000000000000000000"}`), 0o644))
+ err := scanOutputFilesWithWriter(dir, "trace-id", "quiet", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error {
+ return os.ErrPermission
+ })
+ require.Error(t, err)
+ assert.EqualError(t, err, "could not write sanitized output file")
+}
+
+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)
+}
+
+func TestSanitizeJSONStructure_CleanKeyWinsSanitizedCollision(t *testing.T) {
+ const sanitized = "ghp_..."
+ pipeline := security.OutputPipeline()
+ input := map[string]any{
+ "ghp_FAKEtesttoken000000000000000000000000": "secretkeyval",
+ sanitized: "plainval",
+ }
+ input["ghp_FAKEtesttoken000000000000000000000000"] = "secretkeyval"
+ for range 20 {
+ got, findings := sanitizeJSONStructure(input, pipeline)
+ require.NotEmpty(t, findings)
+ result := got.(map[string]any)
+ assert.Equal(t, "plainval", result[sanitized], "clean key must retain its name and value")
+ assert.NotContains(t, result, "ghp_FAKEtesttoken000000000000000000000000")
+ assert.Len(t, result, 2)
+ }
+}
+
+// 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"
+ 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])))
+}
+
+func TestHasDuplicateJSONKeys(t *testing.T) {
+ tests := []struct {
+ name string
+ json string
+ want bool
+ }{
+ {"no duplicates", `{"a": 1, "b": 2}`, false},
+ {"duplicate top-level", `{"a": 1, "a": 2}`, true},
+ {"nested duplicate", `{"parent": {"x": 1, "x": 2}}`, true},
+ {"nested no duplicate", `{"p1": {"x": 1}, "p2": {"x": 1}}`, false},
+ {"array with duplicate in object", `[{"k": 1, "k": 2}]`, true},
+ {"array with separate objects", `[{"k": 1}, {"k": 2}]`, false},
+ {"value matches key name", `{"a": "a", "b": "a"}`, false},
+ {"array values inside object", `{"a": [1, 2], "b": 3}`, false},
+ {"out-of-range number before duplicate keys", `{"large": 1e1000, "dup": 1, "dup": 2}`, true},
+ {"out-of-range number without duplicates", `{"large": 1e1000, "no_dup": 1}`, false},
+ {"malformed json", `{"a": `, false},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ assert.Equal(t, tc.want, hasDuplicateJSONKeys([]byte(tc.json)))
+ })
+ }
+}
diff --git a/internal/security/redactor.go b/internal/security/redactor.go
index 47da94e9ab..42ef309553 100644
--- a/internal/security/redactor.go
+++ b/internal/security/redactor.go
@@ -63,6 +63,11 @@ func resetRuntimeSecrets() {
runtimeSecrets = nil
}
+// ResetRuntimeSecretsForTest clears the registry for tests.
+func ResetRuntimeSecretsForTest() {
+ resetRuntimeSecrets()
+}
+
// SecretRedactor scans text for API keys, tokens, credentials, and
// sensitive patterns, replacing them with masked versions. Adapted from
// Hermes Agent's agent/redact.py.
@@ -119,7 +124,7 @@ func (s *SecretRedactor) Scan(text string) ScanResult {
continue
}
seen[match] = true
- masked := mask(match)
+ masked := Mask(match)
result.Findings = append(result.Findings, Finding{
Scanner: "secret_redactor",
Name: p.name,
@@ -173,7 +178,50 @@ func (s *SecretRedactor) Scan(text string) ScanResult {
}
secret := current[start:end]
- masked := mask(secret)
+ minLen := 0
+ switch p.name {
+ case "env_assignment":
+ minLen = 8
+ case "auth_header":
+ minLen = 12
+ case "db_connection_password":
+ minLen = 4
+ case "json_field":
+ minLen = 8
+ }
+ // If the matched secret ends with a backslash and is immediately
+ // followed by a quote delimiter, the trailing backslash was escaping
+ // that delimiter (e.g. \" in JSON or code strings). Preserve the
+ // escape by excluding the backslash from the redacted secret span.
+ originalLen := len(secret)
+ if end < len(current) && (current[end] == '"' || current[end] == '\'') {
+ numBackslashes := 0
+ for k := len(secret) - 1; k >= 0 && secret[k] == '\\'; k-- {
+ numBackslashes++
+ }
+ if numBackslashes%2 == 1 && p.name != "json_field" {
+ secret = secret[:len(secret)-1]
+ end--
+ }
+ }
+ if len(secret) == 0 {
+ continue
+ }
+ masked := Mask(secret)
+ if originalLen < minLen {
+ continue
+ }
+ if p.name != "json_field" && end < len(current) && (current[end] == '"' || current[end] == '\'') {
+ numBackslashes := 0
+ for k := len(secret) - 1; k >= 0 && secret[k] == '\\'; k-- {
+ numBackslashes++
+ }
+ if numBackslashes%2 == 1 {
+ // The quote is escaped in the source. Keep the escaping
+ // backslash outside the redacted span.
+ masked += "\\"
+ }
+ }
result.Findings = append(result.Findings, Finding{
Scanner: "secret_redactor",
Name: p.name,
@@ -194,11 +242,16 @@ func (s *SecretRedactor) Scan(text string) ScanResult {
return result
}
-func mask(value string) string {
+// Mask returns a redacted representation of a secret value.
+func Mask(value string) string {
if len(value) < 10 {
return "***"
}
- return value[:4] + "..."
+ prefix := value[:4]
+ if strings.Contains(prefix, "\\") {
+ return "***"
+ }
+ return prefix + "..."
}
func defaultPrefixPatterns() []secretPattern {
@@ -254,7 +307,7 @@ func defaultStructuralPatterns() []secretPattern {
// the mask keeps it visible. A bare value still ends at the first
// space, as in the PostToolUse hook.
{"env_assignment", `(?i)(?:^|\s)(?:export\s+)?((?:[A-Za-z0-9]+_)*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|PASSWD|AUTH|API_KEY)(?:_[A-Za-z0-9]+)*)\s*=\s*(?:['"](?:(?:basic|bearer|token)[ \t]+)?)?([^\s"'}\]),;]{8,})['"]?`},
- {"json_field", `(?:"[^"]*(?i:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?i:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"([^"]{8,})"|'([^']{8,})')`},
+ {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\[\s\S]|[^"\\])*)"|'((?:''|\\\r?\n|\\.|[^'\r\n\\])*[^'\r\n\\])'|'((?:''|[^'\r\n])*\\)')`},
// The optional quote covers YAML: authorization: "Bearer ".
{"auth_header", `(?i)(?:Authorization|X-Api-Key|X-Auth-Token)\s*:\s*['"]?(?:(?:Basic|Bearer|Token)\s+)?([^\s"'}\]),;]{12,})`},
{"private_key", `-----BEGIN\s+(?:RSA\s+|EC\s+|OPENSSH\s+)?PRIVATE KEY-----[\s\S]*?-----END\s+(?:RSA\s+|EC\s+|OPENSSH\s+)?PRIVATE KEY-----`},
diff --git a/internal/security/scanner_test.go b/internal/security/scanner_test.go
index 0399ad60fd..8e31c37455 100644
--- a/internal/security/scanner_test.go
+++ b/internal/security/scanner_test.go
@@ -2,6 +2,7 @@ package security
import (
"encoding/json"
+ "fmt"
"strings"
"testing"
@@ -382,6 +383,178 @@ func TestSecretRedactor(t *testing.T) {
assert.True(t, json.Valid([]byte(result.Sanitized)),
"output is not valid JSON: %s", result.Sanitized)
})
+
+ t.Run("env assignment does not eat escaping backslash in JSON string", func(t *testing.T) {
+ // Regression test (#5705): [^\s"'}\]),;]{8,} previously consumed \
+ // inside JSON string values before an escaped quote, leaving unescaped
+ // quote syntax like token_usage = metr..."token_usage").
+ tokenVar := "token" + "_usage"
+ input := fmt.Sprintf(`{"remediation": "Guard against null values with %s = metrics.get(\"token_usage\") or {}"}`, tokenVar)
+ result := r.Scan(input)
+ assert.False(t, result.Safe)
+ assert.True(t, hasFinding(result, "env_assignment"))
+ assert.True(t, json.Valid([]byte(result.Sanitized)),
+ "output must remain valid JSON: %s", result.Sanitized)
+ assert.Contains(t, result.Sanitized, `\"token_usage\"`)
+ })
+
+ t.Run("env assignment redacts credentials containing backslashes", func(t *testing.T) {
+ result := r.Scan(`TOKEN=ab\cdEFGHijkl`)
+ assert.False(t, result.Safe)
+ assert.True(t, hasFinding(result, "env_assignment"))
+ assert.NotContains(t, result.Sanitized, `ab\cdEFGHijkl`)
+
+ // Boundary test: exactly 8 characters containing multiple backslashes
+ resultBoundary := r.Scan(`TOKEN=a\b\c\def`)
+ assert.False(t, resultBoundary.Safe)
+ assert.True(t, hasFinding(resultBoundary, "env_assignment"))
+ assert.NotContains(t, resultBoundary.Sanitized, `a\b\c\def`)
+
+ // Trailing backslash before boundary
+ resultTrailing := r.Scan(`TOKEN=abcdefg\`)
+ assert.False(t, resultTrailing.Safe)
+ assert.True(t, hasFinding(resultTrailing, "env_assignment"))
+ assert.NotContains(t, resultTrailing.Sanitized, `abcdefg\`)
+
+ // Exact-minimum-length boundary tests (8 chars) ending in backslash before quote delimiters
+ resultSingleQuote := r.Scan("TOKEN='abcdefg\\'")
+ assert.False(t, resultSingleQuote.Safe)
+ assert.True(t, hasFinding(resultSingleQuote, "env_assignment"))
+ assert.NotContains(t, resultSingleQuote.Sanitized, "abcdefg")
+ assert.Contains(t, resultSingleQuote.Sanitized, `\'`)
+
+ resultDoubleQuote := r.Scan(`TOKEN="abcdefg\""`)
+ assert.False(t, resultDoubleQuote.Safe)
+ assert.True(t, hasFinding(resultDoubleQuote, "env_assignment"))
+ assert.NotContains(t, resultDoubleQuote.Sanitized, "abcdefg")
+ assert.Contains(t, resultDoubleQuote.Sanitized, `\"`)
+ })
+
+ t.Run("db connection redacts password containing backslashes", func(t *testing.T) {
+ result := r.Scan(`postgres://user:pa\ss@host:5432/db`)
+ assert.False(t, result.Safe)
+ assert.True(t, hasFinding(result, "db_connection_password"))
+ assert.NotContains(t, result.Sanitized, `pa\ss`)
+
+ // Boundary test: exactly 4 characters containing interior backslash
+ resultInterior := r.Scan(`postgres://user:p\ss@host:5432/db`)
+ assert.False(t, resultInterior.Safe)
+ assert.True(t, hasFinding(resultInterior, "db_connection_password"))
+ assert.NotContains(t, resultInterior.Sanitized, `p\ss`)
+
+ // Boundary test: trailing backslash before delimiter @
+ resultTrailing := r.Scan(`postgres://user:p\s\@host:5432/db`)
+ assert.False(t, resultTrailing.Safe)
+ assert.True(t, hasFinding(resultTrailing, "db_connection_password"))
+ assert.NotContains(t, resultTrailing.Sanitized, `p\s\`)
+ })
+
+ t.Run("auth header redacts credentials containing backslashes", func(t *testing.T) {
+ result := r.Scan(`Authorization: Bearer ab\cdEFGHijkl1234`)
+ assert.False(t, result.Safe)
+ assert.True(t, hasFinding(result, "auth_header"))
+ assert.NotContains(t, result.Sanitized, `ab\cdEFGHijkl1234`)
+
+ // Boundary test: exactly 12 characters containing multiple backslashes
+ resultBoundary := r.Scan(`Authorization: Bearer a\b\c\d\e\f\g`)
+ assert.False(t, resultBoundary.Safe)
+ assert.True(t, hasFinding(resultBoundary, "auth_header"))
+ assert.NotContains(t, resultBoundary.Sanitized, `a\b\c\d\e\f\g`)
+
+ // Exact-minimum-length boundary tests (12 chars) ending in backslash before quote delimiters
+ resAuthSingle := r.Scan("authorization: 'Bearer abcdefghijk\\'")
+ assert.False(t, resAuthSingle.Safe)
+ assert.True(t, hasFinding(resAuthSingle, "auth_header"))
+ assert.NotContains(t, resAuthSingle.Sanitized, "abcdefghijk")
+ assert.Contains(t, resAuthSingle.Sanitized, `\'`)
+
+ resAuthDouble := r.Scan(`authorization: "Bearer abcdefghijk\""`)
+ assert.False(t, resAuthDouble.Safe)
+ assert.True(t, hasFinding(resAuthDouble, "auth_header"))
+ assert.NotContains(t, resAuthDouble.Sanitized, "abcdefghijk")
+ assert.Contains(t, resAuthDouble.Sanitized, `\"`)
+
+ resAuthUnprefixedSingle := r.Scan("authorization: 'abcdefghijk\\'")
+ assert.False(t, resAuthUnprefixedSingle.Safe)
+ assert.True(t, hasFinding(resAuthUnprefixedSingle, "auth_header"))
+ assert.NotContains(t, resAuthUnprefixedSingle.Sanitized, "abcdefghijk")
+ assert.Contains(t, resAuthUnprefixedSingle.Sanitized, `\'`)
+
+ resAuthUnprefixedDouble := r.Scan(`authorization: "abcdefghijk\""`)
+ assert.False(t, resAuthUnprefixedDouble.Safe)
+ assert.True(t, hasFinding(resAuthUnprefixedDouble, "auth_header"))
+ assert.NotContains(t, resAuthUnprefixedDouble.Sanitized, "abcdefghijk")
+ assert.Contains(t, resAuthUnprefixedDouble.Sanitized, `\"`)
+ })
+
+ t.Run("json_field with embedded escaped quote preserves valid JSON", func(t *testing.T) {
+ input := `{"password": "abcdefghijkl\"rest"}`
+ result := r.Scan(input)
+ assert.False(t, result.Safe)
+ assert.True(t, hasFinding(result, "json_field"))
+ assert.True(t, json.Valid([]byte(result.Sanitized)),
+ "output must remain valid JSON: %s", result.Sanitized)
+ assert.NotContains(t, result.Sanitized, "abcdefghijkl")
+ })
+
+ t.Run("json_field masks backslashes in literal quoted values", func(t *testing.T) {
+ result := r.Scan(`'password': 'ab\\cdef'`)
+ assert.False(t, result.Safe)
+ assert.True(t, hasFinding(result, "json_field"))
+ assert.NotContains(t, result.Sanitized, `ab\\cdef`)
+ })
+
+ t.Run("json_field handles escaped apostrophe through the full value", func(t *testing.T) {
+ result := r.Scan(`'password': 'abcdefgh\'remaining_secret'`)
+ assert.True(t, hasFinding(result, "json_field"))
+ assert.NotContains(t, result.Sanitized, "remaining_secret")
+ })
+
+ t.Run("json_field counts literal trailing backslash toward minimum", func(t *testing.T) {
+ result := r.Scan("'password': 'abcdefg\\'")
+ assert.True(t, hasFinding(result, "json_field"))
+ assert.NotContains(t, result.Sanitized, "abcdefg")
+ })
+
+ t.Run("json_field handles doubled apostrophe in YAML scalar", func(t *testing.T) {
+ result := r.Scan("'password': 'abcdefgh''remaining_secret'")
+ assert.True(t, hasFinding(result, "json_field"))
+ assert.NotContains(t, result.Sanitized, "remaining_secret")
+ })
+
+ t.Run("json_field handles backslash followed by physical newline", func(t *testing.T) {
+ result := r.Scan("'password': 'abcdefgh\\\nijklmnop'")
+ assert.False(t, result.Safe)
+ assert.True(t, hasFinding(result, "json_field"))
+ assert.NotContains(t, result.Sanitized, "ijklmnop")
+ })
+
+ t.Run("json_field handles adjacent sensitive YAML fields with trailing backslash", func(t *testing.T) {
+ input := "'password': 'abcdefgh\\'\n'secret': 'ijklmnop'"
+ result := r.Scan(input)
+ assert.False(t, result.Safe)
+ findings := 0
+ for _, f := range result.Findings {
+ if f.Name == "json_field" {
+ findings++
+ }
+ }
+ assert.Equal(t, 2, findings, "both adjacent fields must be detected and redacted")
+ assert.NotContains(t, result.Sanitized, "abcdefgh")
+ assert.NotContains(t, result.Sanitized, "ijklmnop")
+ })
+
+ t.Run("mask does not leave dangling escape sequence", func(t *testing.T) {
+ input1 := `Authorization: Bearer abc\ndefghijkl`
+ result1 := r.Scan(input1)
+ assert.False(t, result1.Safe)
+ assert.Equal(t, "Authorization: Bearer ***", result1.Sanitized)
+
+ input2 := `Authorization: Bearer \u1234efghijkl`
+ result2 := r.Scan(input2)
+ assert.False(t, result2.Safe)
+ assert.Equal(t, "Authorization: Bearer ***", result2.Sanitized)
+ })
}
func TestSSRFValidator(t *testing.T) {