From 2ff063a28b7c30015083054dd1c517b8e243ec36 Mon Sep 17 00:00:00 2001 From: anevans Date: Mon, 16 Nov 2026 10:07:15 -0500 Subject: [PATCH 01/15] fix(#5705): preserve escaping backslashes in JSON strings and validate JSON integrity When redacting patterns such as env_assignment, auth_header, and db_connection_password, matching up to an escaped quote (") previously consumed the escaping backslash while leaving the unescaped quote delimiter in the sanitized output, producing corrupted JSON syntax. Update the value capture character classes to stop before backslashes that escape delimiter quotes while continuing to redact credentials that legitimately contain backslashes. In addition, add post-sanitization JSON structural integrity validation to scanOutputFiles in the CLI so that if sanitization produces invalid JSON from a previously valid JSON file, the original file is preserved instead of corrupting downstream tools. Closes #5705 Signed-off-by: anevans --- internal/cli/run.go | 4 ++- internal/cli/scan_output_telemetry_test.go | 20 ++++++++++++ internal/security/redactor.go | 12 ++++++-- internal/security/scanner_test.go | 36 ++++++++++++++++++++++ 4 files changed, 68 insertions(+), 4 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index e3ba55d7bf..38da106bec 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -6814,7 +6814,9 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { } // Sanitized may be empty when all content was invisible characters. out := result.Sanitized - if writeErr := os.WriteFile(path, []byte(out), 0o644); writeErr != nil { + if json.Valid(content) && !json.Valid([]byte(out)) { + printer.StepWarn(fmt.Sprintf("Sanitization broke JSON structural validity in %s; retaining original file to preserve structure", relPath)) + } else if writeErr := os.WriteFile(path, []byte(out), 0o644); writeErr != nil { printer.StepWarn(fmt.Sprintf("Could not write sanitized %s: %v", relPath, writeErr)) } } diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index e494176a92..ab73f71ce9 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -2,6 +2,7 @@ package cli import ( "bytes" + "encoding/json" "os" "path/filepath" "strings" @@ -81,3 +82,22 @@ 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 will ensure that the +// resulting file on disk remains structurally valid JSON (#5705). +func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { + dir := t.TempDir() + jsonFile := filepath.Join(dir, "agent-result.json") + validJSON := `{"action":"comment","body":"Token: ghp_FAKEtesttoken000000000000000000000000\n"}` + require.NoError(t, os.WriteFile(jsonFile, []byte(validJSON), 0o644)) + + var buf bytes.Buffer + printer := ui.New(&buf) + require.NoError(t, scanOutputFiles(dir, "trace-id", printer)) + + content, err := os.ReadFile(jsonFile) + require.NoError(t, err) + assert.True(t, json.Valid(content), "sanitized output must remain valid JSON: %s", string(content)) + assert.NotContains(t, string(content), "ghp_FAKEtest") +} diff --git a/internal/security/redactor.go b/internal/security/redactor.go index 47da94e9ab..9ced63131e 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -245,6 +245,12 @@ func defaultPrefixPatterns() []secretPattern { } func defaultStructuralPatterns() []secretPattern { + // Value character pattern: allows non-delimiter characters and backslashes + // when followed by non-delimiter characters (e.g. passwords containing + // backslashes like pa\ss), but stops before backslashes that escape quote + // delimiters (like \" in JSON strings) to preserve JSON structural integrity. + const valChar = `(?:\\+[^\s"'}\]),;\\]|[^\s"'}\]),;\\])` + patterns := []struct { name string pattern string @@ -253,12 +259,12 @@ func defaultStructuralPatterns() []secretPattern { // quote — TOKEN="basic " — and stays outside the capture so // 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,})['"]?`}, + {"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]+)?)?(` + valChar + `{8,})['"]?`}, {"json_field", `(?:"[^"]*(?i:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?i:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"([^"]{8,})"|'([^']{8,})')`}, // 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,})`}, + {"auth_header", `(?i)(?:Authorization|X-Api-Key|X-Auth-Token)\s*:\s*['"]?(?:(?:Basic|Bearer|Token)\s+)?(` + valChar + `{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-----`}, - {"db_connection_password", `(?:postgres(?:ql)?|mysql|mongodb|redis)://[^:]+:([^\s"'}\]),;]{4,})@[^@\s/]+`}, + {"db_connection_password", `(?:postgres(?:ql)?|mysql|mongodb|redis)://[^:]+:(` + valChar + `{4,})@[^@\s/]+`}, } result := make([]secretPattern, len(patterns)) diff --git a/internal/security/scanner_test.go b/internal/security/scanner_test.go index 0399ad60fd..c629593fbc 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,41 @@ 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`) + }) + + 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`) + }) + + 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`) + }) } func TestSSRFValidator(t *testing.T) { From 69b46b71e68f6e40ac9cc8f779b70442b2fa59c6 Mon Sep 17 00:00:00 2001 From: anevans Date: Mon, 16 Nov 2026 11:12:34 -0500 Subject: [PATCH 02/15] fix(#5705): structurally sanitize JSON outputs and prevent escape-splitting redactions When redacting secret patterns in JSON outputs, raw string replacements could consume escaping backslashes or split escape sequences, corrupting JSON syntax. Implement structural JSON sanitization in scanOutputFiles by parsing JSON files and sanitizing string leaves rather than performing raw text replacement across the entire file, guaranteeing that valid JSON files remain syntactically valid and completely redacted (failing closed). In addition, update the json_field regex to capture escaped characters within quotes, and update mask() to avoid creating dangling or invalid escape sequences when masking secrets. Signed-off-by: anevans --- internal/cli/run.go | 102 ++++++++++++++++++++- internal/cli/scan_output_telemetry_test.go | 40 ++++++-- internal/security/redactor.go | 8 +- internal/security/scanner_test.go | 22 +++++ 4 files changed, 157 insertions(+), 15 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index 38da106bec..ad3189281d 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -6797,11 +6797,43 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { return nil } + relPath, _ := filepath.Rel(outputDir, path) + + // If the file is valid JSON, structurally sanitize string leaves to guarantee + // that redaction never breaks JSON syntax and fails closed (#5705). + var jsonVal any + if json.Unmarshal(content, &jsonVal) == nil { + sanitizedVal, findings := sanitizeJSONStructure(jsonVal, pipeline) + if len(findings) > 0 { + findingCount += len(findings) + for _, f := range findings { + 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, + }) + } + marshaled, err := json.MarshalIndent(sanitizedVal, "", " ") + if err != nil { + printer.StepWarn(fmt.Sprintf("Could not marshal sanitized JSON %s: %v", relPath, err)) + return nil + } + marshaled = append(marshaled, '\n') + if writeErr := os.WriteFile(path, marshaled, 0o644); writeErr != nil { + printer.StepWarn(fmt.Sprintf("Could not write sanitized %s: %v", relPath, writeErr)) + } + } + 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 { printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s: %s", f.Name, relPath, f.Detail)) security.AppendFinding(findingsPath, @@ -6814,9 +6846,7 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { } // Sanitized may be empty when all content was invisible characters. out := result.Sanitized - if json.Valid(content) && !json.Valid([]byte(out)) { - printer.StepWarn(fmt.Sprintf("Sanitization broke JSON structural validity in %s; retaining original file to preserve structure", relPath)) - } else if writeErr := os.WriteFile(path, []byte(out), 0o644); writeErr != nil { + if writeErr := os.WriteFile(path, []byte(out), 0o644); writeErr != nil { printer.StepWarn(fmt.Sprintf("Could not write sanitized %s: %v", relPath, writeErr)) } } @@ -6834,6 +6864,70 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { return nil } +var sensitiveJSONKeyRegex = regexp.MustCompile(`(?i)(?:key|token|secret|password|credential|auth)`) + +func maskSecretValue(value string) string { + if len(value) < 10 { + return "***" + } + prefix := value[:4] + if strings.Contains(prefix, "\\") { + return "***" + } + return prefix + "..." +} + +// sanitizeJSONStructure recursively visits all string values in parsed JSON data, +// scans each 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)) + for k, item := range val { + if strVal, ok := item.(string); ok && sensitiveJSONKeyRegex.MatchString(k) && len(strVal) >= 8 { + masked := maskSecretValue(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), + }) + newMap[k] = masked + continue + } + newVal, f := sanitizeJSONStructure(item, pipeline) + if len(f) > 0 { + findings = append(findings, f...) + } + newMap[k] = 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 + default: + return val, nil + } +} + // 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 ab73f71ce9..00a00dbf52 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -84,20 +84,42 @@ func TestScanOutputFiles_SkipsStagedSkillsAndPersonaManifest(t *testing.T) { } // TestScanOutputFiles_PreservesJSONStructuralValidity pins that if an output -// file was valid JSON before sanitization, scanOutputFiles will ensure that the -// resulting file on disk remains structurally valid JSON (#5705). +// 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() - jsonFile := filepath.Join(dir, "agent-result.json") - validJSON := `{"action":"comment","body":"Token: ghp_FAKEtesttoken000000000000000000000000\n"}` - require.NoError(t, os.WriteFile(jsonFile, []byte(validJSON), 0o644)) + + // 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)) var buf bytes.Buffer printer := ui.New(&buf) require.NoError(t, scanOutputFiles(dir, "trace-id", printer)) - content, err := os.ReadFile(jsonFile) - require.NoError(t, err) - assert.True(t, json.Valid(content), "sanitized output must remain valid JSON: %s", string(content)) - assert.NotContains(t, string(content), "ghp_FAKEtest") + for _, p := range []struct { + path string + secret string + }{ + {jsonFile1, "ghp_FAKEtest"}, + {jsonFile2, "secret_password_1234"}, + {jsonFile3, "abcdefghijkl1234"}, + } { + 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)) + } } diff --git a/internal/security/redactor.go b/internal/security/redactor.go index 9ced63131e..e61cca1b1b 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -198,7 +198,11 @@ 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 { @@ -260,7 +264,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]+)?)?(` + valChar + `{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)[^"]*"|'[^']*(?i:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\.|[^"\\]){8,})"|'((?:\\.|[^'\\]){8,})')`}, // The optional quote covers YAML: authorization: "Bearer ". {"auth_header", `(?i)(?:Authorization|X-Api-Key|X-Auth-Token)\s*:\s*['"]?(?:(?:Basic|Bearer|Token)\s+)?(` + valChar + `{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 c629593fbc..832eedb903 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -418,6 +418,28 @@ func TestSecretRedactor(t *testing.T) { assert.True(t, hasFinding(result, "auth_header")) assert.NotContains(t, result.Sanitized, `ab\cdEFGHijkl1234`) }) + + 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("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) { From 12a4652b5360f1038704f7cbc509174535821852 Mon Sep 17 00:00:00 2001 From: anevans Date: Mon, 16 Nov 2026 12:31:14 -0500 Subject: [PATCH 03/15] fix(#5705): sanitize JSON keys and preserve number precision Scan object keys and string leaves in sanitizeJSONStructure to avoid leaking credentials in JSON map keys. Decode JSON using dec.UseNumber() and encode with SetEscapeHTML(false) to prevent precision loss on large integers and HTML escaping. Restore character-based quantifier classes in redactor.go while safely preserving quote-escaping backslashes via delimiter inspection. Add boundary tests for env_assignment, auth_header, and db_connection_password at minimum lengths with backslashes. Add test coverage in scan_output_telemetry_test.go for key sanitization, large numbers, and float formatting. Signed-off-by: anevans --- internal/cli/run.go | 134 +++++++++++++-------- internal/cli/scan_output_telemetry_test.go | 18 +++ internal/security/redactor.go | 51 ++++++-- internal/security/scanner_test.go | 30 +++++ 4 files changed, 174 insertions(+), 59 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index ad3189281d..3b7c98a7d0 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -6799,34 +6799,57 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { relPath, _ := filepath.Rel(outputDir, path) - // If the file is valid JSON, structurally sanitize string leaves to guarantee + // If the file is valid JSON, structurally sanitize keys and string leaves to guarantee // that redaction never breaks JSON syntax and fails closed (#5705). + dec := json.NewDecoder(bytes.NewReader(content)) + dec.UseNumber() var jsonVal any - if json.Unmarshal(content, &jsonVal) == nil { - sanitizedVal, findings := sanitizeJSONStructure(jsonVal, pipeline) - if len(findings) > 0 { - findingCount += len(findings) - for _, f := range findings { - 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, - }) - } - marshaled, err := json.MarshalIndent(sanitizedVal, "", " ") - if err != nil { - printer.StepWarn(fmt.Sprintf("Could not marshal sanitized JSON %s: %v", relPath, err)) - return nil - } - marshaled = append(marshaled, '\n') - if writeErr := os.WriteFile(path, marshaled, 0o644); writeErr != nil { - printer.StepWarn(fmt.Sprintf("Could not write sanitized %s: %v", relPath, writeErr)) + 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) + for _, f := range findings { + 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) + enc.SetIndent("", " ") + if err := enc.Encode(sanitizedVal); err != nil { + printer.StepWarn(fmt.Sprintf("Could not marshal sanitized JSON %s: %v", relPath, err)) + return nil + } + marshaled := buf.Bytes() + // Backstop check: verify marshaled text contains no unredacted secrets + backstop := pipeline.Scan(string(marshaled)) + if len(backstop.Findings) > 0 && backstop.Sanitized != "" && json.Valid([]byte(backstop.Sanitized)) { + marshaled = []byte(backstop.Sanitized) + for _, f := range backstop.Findings { + 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 writeErr := os.WriteFile(path, marshaled, 0o644); writeErr != nil { + printer.StepWarn(fmt.Sprintf("Could not write sanitized %s: %v", relPath, writeErr)) + } } + return nil } - return nil } // Non-JSON files: run plain text pipeline scan. @@ -6866,19 +6889,8 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { var sensitiveJSONKeyRegex = regexp.MustCompile(`(?i)(?:key|token|secret|password|credential|auth)`) -func maskSecretValue(value string) string { - if len(value) < 10 { - return "***" - } - prefix := value[:4] - if strings.Contains(prefix, "\\") { - return "***" - } - return prefix + "..." -} - -// sanitizeJSONStructure recursively visits all string values in parsed JSON data, -// scans each string leaf using the pipeline, and collects any findings. +// 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) { @@ -6895,22 +6907,50 @@ func sanitizeJSONStructure(v any, pipeline *security.Pipeline) (any, []security. case map[string]any: newMap := make(map[string]any, len(val)) for k, item := range val { - if strVal, ok := item.(string); ok && sensitiveJSONKeyRegex.MatchString(k) && len(strVal) >= 8 { - masked := maskSecretValue(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), - }) - newMap[k] = masked + sanitizedKey := k + keyRes := pipeline.Scan(k) + if len(keyRes.Findings) > 0 { + findings = append(findings, keyRes.Findings...) + if keyRes.Sanitized != "" { + sanitizedKey = keyRes.Sanitized + } + } + targetKey := sanitizedKey + if _, exists := newMap[targetKey]; exists { + 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...) + newMap[targetKey] = valRes.Sanitized + continue + } + if sensitiveJSONKeyRegex.MatchString(k) && len(strVal) >= 8 { + 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), + }) + newMap[targetKey] = masked + continue + } + newMap[targetKey] = strVal continue } newVal, f := sanitizeJSONStructure(item, pipeline) if len(f) > 0 { findings = append(findings, f...) } - newMap[k] = newVal + newMap[targetKey] = newVal } return newMap, findings case []any: diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 00a00dbf52..9e8d344a9a 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -105,6 +105,16 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { 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)) + var buf bytes.Buffer printer := ui.New(&buf) require.NoError(t, scanOutputFiles(dir, "trace-id", printer)) @@ -116,10 +126,18 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { {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)) } + + 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") } diff --git a/internal/security/redactor.go b/internal/security/redactor.go index e61cca1b1b..3c9d69c367 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -119,7 +119,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 +173,39 @@ func (s *SecretRedactor) Scan(text string) ScanResult { } secret := current[start:end] - masked := mask(secret) + // If the matched secret ends with a backslash and is immediately + // followed by a quote delimiter, the trailing backslash was escaping + // that delimiter (e.g. \" in JSON or code strings). Preserve the + // escape by excluding the backslash from the redacted secret span. + 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 { + secret = secret[:len(secret)-1] + end-- + } + } + if len(secret) == 0 { + continue + } + 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 len(secret) < minLen { + continue + } + + masked := Mask(secret) result.Findings = append(result.Findings, Finding{ Scanner: "secret_redactor", Name: p.name, @@ -194,7 +226,8 @@ 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 "***" } @@ -249,12 +282,6 @@ func defaultPrefixPatterns() []secretPattern { } func defaultStructuralPatterns() []secretPattern { - // Value character pattern: allows non-delimiter characters and backslashes - // when followed by non-delimiter characters (e.g. passwords containing - // backslashes like pa\ss), but stops before backslashes that escape quote - // delimiters (like \" in JSON strings) to preserve JSON structural integrity. - const valChar = `(?:\\+[^\s"'}\]),;\\]|[^\s"'}\]),;\\])` - patterns := []struct { name string pattern string @@ -263,12 +290,12 @@ func defaultStructuralPatterns() []secretPattern { // quote — TOKEN="basic " — and stays outside the capture so // 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]+)?)?(` + valChar + `{8,})['"]?`}, + {"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,})')`}, // The optional quote covers YAML: authorization: "Bearer ". - {"auth_header", `(?i)(?:Authorization|X-Api-Key|X-Auth-Token)\s*:\s*['"]?(?:(?:Basic|Bearer|Token)\s+)?(` + valChar + `{12,})`}, + {"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-----`}, - {"db_connection_password", `(?:postgres(?:ql)?|mysql|mongodb|redis)://[^:]+:(` + valChar + `{4,})@[^@\s/]+`}, + {"db_connection_password", `(?:postgres(?:ql)?|mysql|mongodb|redis)://[^:]+:([^\s"'}\]),;]{4,})@[^@\s/]+`}, } result := make([]secretPattern, len(patterns)) diff --git a/internal/security/scanner_test.go b/internal/security/scanner_test.go index 832eedb903..68d53ea3f0 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -403,6 +403,18 @@ func TestSecretRedactor(t *testing.T) { 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\`) }) t.Run("db connection redacts password containing backslashes", func(t *testing.T) { @@ -410,6 +422,18 @@ func TestSecretRedactor(t *testing.T) { 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) { @@ -417,6 +441,12 @@ func TestSecretRedactor(t *testing.T) { 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`) }) t.Run("json_field with embedded escaped quote preserves valid JSON", func(t *testing.T) { From f8b4393be9b6cc59dbca8e8876fbbaa52c5b9da0 Mon Sep 17 00:00:00 2001 From: anevans Date: Mon, 16 Nov 2026 14:13:18 -0500 Subject: [PATCH 04/15] fix(#5705): fail closed on duplicate JSON keys and backstop findings Detect duplicate JSON keys while decoding and fall back to plain-text sanitization so all occurrences of duplicate keys are redacted. Ensure backstop findings are always recorded and sanitized output is written even when re-encoding is not valid JSON. Fall back to plain-text sanitization on JSON marshal errors instead of failing open. Preserve line count for single-record .jsonl files and compact JSON files by skipping the structural path for .jsonl/.ndjson and omitting indentation on compact JSON documents. Add regression tests for duplicate JSON keys, single-record JSONL line count preservation, and duplicate key token decoding. Signed-off-by: anevans --- internal/cli/run.go | 157 +++++++++++++++------ internal/cli/scan_output_telemetry_test.go | 83 +++++++++++ 2 files changed, 199 insertions(+), 41 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index 3b7c98a7d0..c6ce47c1af 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -6799,42 +6799,25 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { relPath, _ := filepath.Rel(outputDir, path) - // If the file is valid JSON, structurally sanitize keys and string leaves to guarantee - // that redaction never breaks JSON syntax and fails closed (#5705). - 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) - for _, f := range findings { - 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) - enc.SetIndent("", " ") - if err := enc.Encode(sanitizedVal); err != nil { - printer.StepWarn(fmt.Sprintf("Could not marshal sanitized JSON %s: %v", relPath, err)) - return nil - } - marshaled := buf.Bytes() - // Backstop check: verify marshaled text contains no unredacted secrets - backstop := pipeline.Scan(string(marshaled)) - if len(backstop.Findings) > 0 && backstop.Sanitized != "" && json.Valid([]byte(backstop.Sanitized)) { - marshaled = []byte(backstop.Sanitized) - for _, f := range backstop.Findings { - printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s (backstop): %s", f.Name, relPath, f.Detail)) + 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 { + rawScan := pipeline.Scan(string(content)) + sanitizedVal, findings := sanitizeJSONStructure(jsonVal, pipeline) + if len(findings) > 0 { + findingCount += len(findings) + for _, f := range findings { + printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s: %s", f.Name, relPath, f.Detail)) security.AppendFinding(findingsPath, security.TracedFinding{ TraceID: traceID, @@ -6843,16 +6826,50 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { 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 { + 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 check: verify marshaled text contains no unredacted secrets. + backstop := pipeline.Scan(string(marshaled)) + if len(backstop.Findings) > 0 { + findingCount += len(backstop.Findings) + for _, f := range backstop.Findings { + 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 != "" { + marshaled = []byte(backstop.Sanitized) + } + } + if writeErr := os.WriteFile(path, marshaled, 0o644); writeErr != nil { + printer.StepWarn(fmt.Sprintf("Could not write sanitized %s: %v", relPath, writeErr)) + } + return nil + } + } else if len(rawScan.Findings) == 0 { + // Clean JSON with no findings structurally or in raw scan. + return nil } - if writeErr := os.WriteFile(path, marshaled, 0o644); writeErr != nil { - printer.StepWarn(fmt.Sprintf("Could not write sanitized %s: %v", relPath, writeErr)) - } + // If structural pass found 0 findings but rawScan found secrets, fall through to text scan. } - return nil } } - // Non-JSON files: run plain text pipeline scan. + // Non-JSON files or fallback: run plain text pipeline scan. text := string(content) result := pipeline.Scan(text) if len(result.Findings) > 0 { @@ -6887,6 +6904,64 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { return nil } +type jsonContainerFrame struct { + isObject bool + expectingKey bool + keys map[string]bool +} + +// 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)) + 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, diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 9e8d344a9a..3716686b9c 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -3,6 +3,7 @@ package cli import ( "bytes" "encoding/json" + "fmt" "os" "path/filepath" "strings" @@ -141,3 +142,85 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { assert.Contains(t, string(content4), "1.0", "float formatting must be preserved") assert.Contains(t, string(content4), "&val", "HTML characters must not be escaped") } + +// 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)) + + 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") +} + +// 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) +} + +// 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 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}, + {"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))) + }) + } +} From 727d5aeb602f55cb99b4d4712dc27dc1fb54aa14 Mon Sep 17 00:00:00 2001 From: anevans Date: Tue, 17 Nov 2026 08:44:28 -0500 Subject: [PATCH 05/15] fix(#5705): parse JSON numbers as Number and check pre-trim length Call dec.UseNumber() in hasDuplicateJSONKeys to prevent float64 parsing overflow from terminating duplicate key detection early. Apply minimum length checks to captured credentials prior to trimming delimiter-escaping backslashes, ensuring credentials at exact pattern minimums ending in backslashes before quotes are redacted. Add regression and boundary tests for both paths. Signed-off-by: anevans --- internal/cli/run.go | 1 + internal/cli/scan_output_telemetry_test.go | 11 +++++++ internal/security/redactor.go | 29 +++++++++-------- internal/security/scanner_test.go | 38 ++++++++++++++++++++++ 4 files changed, 65 insertions(+), 14 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index c6ce47c1af..bc0c42af7c 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -6914,6 +6914,7 @@ type jsonContainerFrame struct { // 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() diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 3716686b9c..f931ad0b93 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -153,6 +153,10 @@ func TestScanOutputFiles_DuplicateJSONKeys(t *testing.T) { 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)) @@ -161,6 +165,11 @@ func TestScanOutputFiles_DuplicateJSONKeys(t *testing.T) { 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 @@ -216,6 +225,8 @@ func TestHasDuplicateJSONKeys(t *testing.T) { {"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 { diff --git a/internal/security/redactor.go b/internal/security/redactor.go index 3c9d69c367..cb5cd467e1 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -173,6 +173,21 @@ func (s *SecretRedactor) Scan(text string) ScanResult { } secret := current[start:end] + 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 len(secret) < minLen { + continue + } + // 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 @@ -190,20 +205,6 @@ func (s *SecretRedactor) Scan(text string) ScanResult { if len(secret) == 0 { continue } - 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 len(secret) < minLen { - continue - } masked := Mask(secret) result.Findings = append(result.Findings, Finding{ diff --git a/internal/security/scanner_test.go b/internal/security/scanner_test.go index 68d53ea3f0..672ff9abc8 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -415,6 +415,19 @@ func TestSecretRedactor(t *testing.T) { 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) { @@ -447,6 +460,31 @@ func TestSecretRedactor(t *testing.T) { 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) { From 634e9ad2b28d325e2ba7c74caa7e7026914b0052 Mon Sep 17 00:00:00 2001 From: anevans Date: Tue, 17 Nov 2026 10:47:36 -0500 Subject: [PATCH 06/15] test(#5705): assert decoded JSON secrets are redacted Signed-off-by: anevans --- internal/cli/scan_output_telemetry_test.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index f931ad0b93..078be913bf 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -136,11 +136,27 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { 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") + 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") + } } // TestScanOutputFiles_DuplicateJSONKeys verifies that JSON files containing From f80f2bc6bddf71f8d83e7d743258dfc0b17ee19e Mon Sep 17 00:00:00 2001 From: anevans Date: Tue, 17 Nov 2026 11:28:47 -0500 Subject: [PATCH 07/15] fix(#5705): fail run when output sanitization write fails Signed-off-by: anevans --- internal/cli/run.go | 15 +++++--- internal/cli/scan_output_telemetry_test.go | 40 ++++++++++++++++++++++ 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index bc0c42af7c..cc490a00ce 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -3365,7 +3365,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, printer); err != nil { - printer.StepWarn("Output scan error: " + err.Error()) + printer.StepFail("Output scan failed: " + err.Error()) + return fmt.Errorf("post-agent output scan failed: %w", err) } // Extract sandbox-side security findings for audit trail. @@ -6754,6 +6755,10 @@ func scanRepoContextFiles(repoDir string) []security.Finding { // secret redaction) on extracted output files, recursively walking all // subdirectories (iteration-N/output/, etc.). func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { + return scanOutputFilesWithWriter(outputDir, traceID, printer, os.WriteFile) +} + +func scanOutputFilesWithWriter(outputDir, traceID string, printer *ui.Printer, writeFile func(string, []byte, os.FileMode) error) error { if _, err := os.Stat(outputDir); os.IsNotExist(err) { printer.StepInfo("No output files to scan") return nil @@ -6855,8 +6860,8 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { marshaled = []byte(backstop.Sanitized) } } - if writeErr := os.WriteFile(path, marshaled, 0o644); writeErr != nil { - printer.StepWarn(fmt.Sprintf("Could not write sanitized %s: %v", relPath, writeErr)) + if writeErr := writeFile(path, marshaled, 0o644); writeErr != nil { + return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) } return nil } @@ -6886,8 +6891,8 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { } // Sanitized may be empty when all content was invisible characters. out := result.Sanitized - if writeErr := os.WriteFile(path, []byte(out), 0o644); writeErr != nil { - printer.StepWarn(fmt.Sprintf("Could not write sanitized %s: %v", relPath, writeErr)) + if writeErr := writeFile(path, []byte(out), 0o644); writeErr != nil { + return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) } } return nil diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 078be913bf..6fbb8d87d0 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "path/filepath" + "sort" "strings" "testing" @@ -157,6 +158,33 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { 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") } // TestScanOutputFiles_DuplicateJSONKeys verifies that JSON files containing @@ -210,6 +238,18 @@ func TestScanOutputFiles_SingleRecordJSONL_PreservesLineCount(t *testing.T) { assert.Len(t, lines, 1) } +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") +} + // TestScanOutputFiles_CleanJSON verifies that clean JSON files with no findings // remain completely untouched byte-for-byte. func TestScanOutputFiles_CleanJSON(t *testing.T) { From ceb67005509e8965c64d876e886e8fdbfdc4b953 Mon Sep 17 00:00:00 2001 From: anevans Date: Tue, 17 Nov 2026 15:13:43 -0500 Subject: [PATCH 08/15] fix(#5705): prevent cross-value JSON redaction Signed-off-by: anevans --- internal/cli/run.go | 38 +++++++++++++++++++--- internal/cli/scan_output_telemetry_test.go | 33 +++++++++++++++++++ 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index cc490a00ce..d664af44b9 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -6817,7 +6817,6 @@ func scanOutputFilesWithWriter(outputDir, traceID string, printer *ui.Printer, w if dec.Decode(&jsonVal) == nil { var trailing any if dec.Decode(&trailing) == io.EOF { - rawScan := pipeline.Scan(string(content)) sanitizedVal, findings := sanitizeJSONStructure(jsonVal, pipeline) if len(findings) > 0 { findingCount += len(findings) @@ -6865,11 +6864,34 @@ func scanOutputFilesWithWriter(outputDir, traceID string, printer *ui.Printer, w } return nil } - } else if len(rawScan.Findings) == 0 { - // Clean JSON with no findings structurally or in raw scan. + } else { + // A raw whole-document scan can match across JSON value + // boundaries (notably BEGIN/END private-key markers). Such + // patterns must still be considered within each decoded string + // value, but must never be applied across JSON framing. + rawScan := pipeline.Scan(string(content)) + if len(rawScan.Findings) == 0 { + return nil + } + // A whole-document match that is not found in any individual + // key/value cannot safely be attributed to a JSON value. + // Fail closed without emitting malformed JSON. + findings := make([]security.Finding, 0, len(rawScan.Findings)) + for _, finding := range rawScan.Findings { + printer.StepWarn(fmt.Sprintf("Removed JSON output %s after an unscoped text-scan finding [%s]", relPath, finding.Name)) + security.AppendFinding(findingsPath, security.TracedFinding{ + TraceID: traceID, Timestamp: time.Now().UTC().Format(time.RFC3339), + Phase: "host_output", Finding: finding, + }) + findings = append(findings, finding) + } + findingCount += len(findings) + marker := []byte(`{"error":"output removed because a text-scan finding could not be attributed to a JSON value"}`) + if writeErr := writeFile(path, marker, 0o644); writeErr != nil { + return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) + } return nil } - // If structural pass found 0 findings but rawScan found secrets, fall through to text scan. } } } @@ -6891,6 +6913,14 @@ func scanOutputFilesWithWriter(outputDir, traceID string, printer *ui.Printer, w } // Sanitized may be empty when all content was invisible characters. out := result.Sanitized + // 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 !isJSONL && json.Valid(content) && !json.Valid([]byte(out)) { + 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 { return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) } diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 6fbb8d87d0..3ae9328e46 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "os" + "os/exec" "path/filepath" "sort" "strings" @@ -117,6 +118,19 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { validJSON5 := `{"tokens":["ghp_FAKEtesttoken000000000000000000000001"],"ghp_FAKEtesttoken000000000000000000000002":1,"ghp_FAKEtesttoken000000000000000000000003":2}` require.NoError(t, os.WriteFile(jsonFile5, []byte(validJSON5), 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=env"}` + 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)) + var buf bytes.Buffer printer := ui.New(&buf) require.NoError(t, scanOutputFiles(dir, "trace-id", printer)) @@ -185,6 +199,25 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { 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.Contains(t, scribeResult["body"], "SCRIBE_SECRET_BACKEND=env") + + 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", "ambiguous whole-document match 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 From c52bfcc041aa77c426f0c19e8576aeb30c5181c0 Mon Sep 17 00:00:00 2001 From: anevans Date: Tue, 17 Nov 2026 15:27:52 -0500 Subject: [PATCH 09/15] fix(#5705): avoid repeated JSON redaction Signed-off-by: anevans --- internal/cli/run.go | 48 +++------------------- internal/cli/scan_output_telemetry_test.go | 28 ++++++++++++- internal/security/redactor.go | 23 +++++++---- 3 files changed, 47 insertions(+), 52 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index d664af44b9..ea2bd406a4 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -6841,55 +6841,17 @@ func scanOutputFilesWithWriter(outputDir, traceID string, printer *ui.Printer, w // Fall through to plain text scan below instead of failing open. } else { marshaled := buf.Bytes() - // Backstop check: verify marshaled text contains no unredacted secrets. - backstop := pipeline.Scan(string(marshaled)) - if len(backstop.Findings) > 0 { - findingCount += len(backstop.Findings) - for _, f := range backstop.Findings { - 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 != "" { - marshaled = []byte(backstop.Sanitized) - } - } + // Structural scanning is authoritative here. A raw-text + // backstop can match escaped syntax across value boundaries + // and double-redact an already-masked value. if writeErr := writeFile(path, marshaled, 0o644); writeErr != nil { return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) } return nil } } else { - // A raw whole-document scan can match across JSON value - // boundaries (notably BEGIN/END private-key markers). Such - // patterns must still be considered within each decoded string - // value, but must never be applied across JSON framing. - rawScan := pipeline.Scan(string(content)) - if len(rawScan.Findings) == 0 { - return nil - } - // A whole-document match that is not found in any individual - // key/value cannot safely be attributed to a JSON value. - // Fail closed without emitting malformed JSON. - findings := make([]security.Finding, 0, len(rawScan.Findings)) - for _, finding := range rawScan.Findings { - printer.StepWarn(fmt.Sprintf("Removed JSON output %s after an unscoped text-scan finding [%s]", relPath, finding.Name)) - security.AppendFinding(findingsPath, security.TracedFinding{ - TraceID: traceID, Timestamp: time.Now().UTC().Format(time.RFC3339), - Phase: "host_output", Finding: finding, - }) - findings = append(findings, finding) - } - findingCount += len(findings) - marker := []byte(`{"error":"output removed because a text-scan finding could not be attributed to a JSON value"}`) - if writeErr := writeFile(path, marker, 0o644); writeErr != nil { - return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) - } + // Every value and key has been scanned independently. Do not + // apply a raw whole-document pattern that can cross values. return nil } } diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 3ae9328e46..3ccce188be 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -128,7 +128,7 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { // 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"}]` + validJSON7 := `["see -----BEGIN RSA` + ` PRIVATE KEY----- marker", {"note": "and -----END RSA` + ` PRIVATE KEY----- marker"}]` require.NoError(t, os.WriteFile(jsonFile7, []byte(validJSON7), 0o644)) var buf bytes.Buffer @@ -210,7 +210,8 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { 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", "ambiguous whole-document match must fail closed") + assert.Contains(t, string(content7), "-----BEGIN RSA"+" PRIVATE KEY-----") + assert.Contains(t, string(content7), "-----END RSA"+" PRIVATE KEY-----") // jq is the parser implicated by the original incident; exercise it when // available, while keeping the Go validity assertions portable. @@ -283,6 +284,29 @@ func TestScanOutputFiles_ReturnsErrorWhenSanitizedWriteFails(t *testing.T) { assert.Contains(t, err.Error(), "could not write sanitized secret.txt") } +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) { diff --git a/internal/security/redactor.go b/internal/security/redactor.go index cb5cd467e1..8bf238a92e 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -184,10 +184,6 @@ func (s *SecretRedactor) Scan(text string) ScanResult { case "json_field": minLen = 8 } - if len(secret) < minLen { - continue - } - // 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 @@ -197,7 +193,7 @@ func (s *SecretRedactor) Scan(text string) ScanResult { for k := len(secret) - 1; k >= 0 && secret[k] == '\\'; k-- { numBackslashes++ } - if numBackslashes%2 == 1 { + if numBackslashes%2 == 1 && p.name == "json_field" { secret = secret[:len(secret)-1] end-- } @@ -205,8 +201,21 @@ func (s *SecretRedactor) Scan(text string) ScanResult { if len(secret) == 0 { continue } - masked := Mask(secret) + if len(secret) < 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, @@ -292,7 +301,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*(?:"((?:\\.|[^"\\]){8,})"|'((?:''|[^']){8,})'|` + "'" + `([^\r\n]{8,}\\)` + "'" + `|'((?:\\.|[^']){8,})')`}, // 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-----`}, From 65984d9a8563c6b7d283711f8f0dbf226b00c62e Mon Sep 17 00:00:00 2001 From: anevans Date: Tue, 17 Nov 2026 15:31:17 -0500 Subject: [PATCH 10/15] fix(#5705): harden JSON redaction backstop Signed-off-by: anevans --- internal/cli/run.go | 34 ++++++++++++++++++++-- internal/cli/scan_output_telemetry_test.go | 10 +++++++ internal/security/redactor.go | 2 +- internal/security/scanner_test.go | 7 +++++ 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index ea2bd406a4..4a9e455866 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -6841,9 +6841,37 @@ func scanOutputFilesWithWriter(outputDir, traceID string, printer *ui.Printer, w // Fall through to plain text scan below instead of failing open. } else { marshaled := buf.Bytes() - // Structural scanning is authoritative here. A raw-text - // backstop can match escaped syntax across value boundaries - // and double-redact an already-masked value. + // 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 := len(findings) == 0 + for _, finding := range backstop.Findings { + if finding.Name == "private_key" { + changed = true + marshaled = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`) + break + } + } + if changed { + findingCount += len(backstop.Findings) + for _, f := range backstop.Findings { + 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 != "" { + if !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 { return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) } diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 3ccce188be..77fbc0f473 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -118,6 +118,12 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { 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") @@ -212,6 +218,10 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { assert.True(t, json.Valid(content7), "cross-value private-key match must not corrupt JSON") assert.Contains(t, string(content7), "-----BEGIN RSA"+" PRIVATE KEY-----") assert.Contains(t, string(content7), "-----END RSA"+" PRIVATE KEY-----") + 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") // jq is the parser implicated by the original incident; exercise it when // available, while keeping the Go validity assertions portable. diff --git a/internal/security/redactor.go b/internal/security/redactor.go index 8bf238a92e..d1299c0a75 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -301,7 +301,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)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\.|[^"\\]){8,})"|'((?:''|[^']){8,})'|` + "'" + `([^\r\n]{8,}\\)` + "'" + `|'((?:\\.|[^']){8,})')`}, + {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\.|[^"\\])*)"|'((?:''|[^'])*)'|` + "'" + `([^\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 672ff9abc8..8db201ad3f 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -497,6 +497,13 @@ func TestSecretRedactor(t *testing.T) { 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("mask does not leave dangling escape sequence", func(t *testing.T) { input1 := `Authorization: Bearer abc\ndefghijkl` result1 := r.Scan(input1) From 54b7afe643adcca3ae472250c6f3b514c5766812 Mon Sep 17 00:00:00 2001 From: anevans Date: Wed, 18 Nov 2026 09:54:29 -0500 Subject: [PATCH 11/15] fix(#5705): close remaining output sanitizer gaps Signed-off-by: anevans --- .pre-commit-config.yaml | 2 +- internal/cli/run.go | 106 ++++++++++++++++----- internal/cli/scan_output_telemetry_test.go | 54 ++++++++++- internal/security/redactor.go | 7 +- internal/security/scanner_test.go | 12 +++ 5 files changed, 151 insertions(+), 30 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0349e77620..6c785d67f7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -9,7 +9,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - id: detect-private-key - exclude: "internal/layers/secrets_test\\.go$|internal/security/scanner_test\\.go$|internal/dispatch/gcf/provisioner_test\\.go$|internal/cli/mint_test\\.go$|tests/.*test_.*\\.py$" + exclude: "internal/layers/secrets_test\\.go$|internal/security/scanner_test\\.go$|internal/dispatch/gcf/provisioner_test\\.go$|internal/cli/mint_test\\.go$|internal/cli/scan_output_telemetry_test\\.go$|tests/.*test_.*\\.py$" - id: check-added-large-files args: ["--maxkb=1000"] - id: check-merge-conflict diff --git a/internal/cli/run.go b/internal/cli/run.go index de2e0c19e5..7fd025519e 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7052,7 +7052,9 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri if len(findings) > 0 { findingCount += len(findings) for _, f := range findings { - printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s: %s", f.Name, relPath, f.Detail)) + if !quiet { + printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s: %s", f.Name, relPath, f.Detail)) + } security.AppendFinding(findingsPath, security.TracedFinding{ TraceID: traceID, @@ -7077,25 +7079,27 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri // JSON; otherwise discard the potentially malformed payload. backstop := pipeline.Scan(string(marshaled)) if len(backstop.Findings) > 0 { - changed := len(findings) == 0 + changed := false + privateKey := false for _, finding := range backstop.Findings { if finding.Name == "private_key" { - changed = true - marshaled = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`) - break + privateKey = true } } + changed = privateKey || len(findings) == 0 if changed { findingCount += len(backstop.Findings) for _, f := range backstop.Findings { - printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s (backstop): %s", f.Name, relPath, f.Detail)) + 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 != "" { - if !json.Valid([]byte(backstop.Sanitized)) { + if privateKey || !json.Valid([]byte(backstop.Sanitized)) { marshaled = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`) } else { marshaled = []byte(backstop.Sanitized) @@ -7105,16 +7109,49 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri } if writeErr := writeFile(path, marshaled, 0o644); writeErr != nil { if quiet { - unwritable++ - } else { - return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) + return fmt.Errorf("could not write sanitized output file") } + return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) } return nil } } else { - // Every value and key has been scanned independently. Do not - // apply a raw whole-document pattern that can cross values. + // 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()) + privateKey := false + for _, f := range backstop.Findings { + if f.Name == "private_key" { + privateKey = true + } + } + if !privateKey { + 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, + }) + } + marker := []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`) + if writeErr := writeFile(path, marker, 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 } } @@ -7250,9 +7287,23 @@ func sanitizeJSONStructure(v any, pipeline *security.Pipeline) (any, []security. return val, nil case map[string]any: newMap := make(map[string]any, len(val)) - for k, item := range 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 != "" { @@ -7260,23 +7311,29 @@ func sanitizeJSONStructure(v any, pipeline *security.Pipeline) (any, []security. } } targetKey := sanitizedKey + if !keyNeedsSanitization { + targetKey = k + } if _, exists := newMap[targetKey]; exists { - for i := 1; ; i++ { - cand := fmt.Sprintf("%s_%d", sanitizedKey, i) - if _, exists := newMap[cand]; !exists { - targetKey = cand - break + if keyNeedsSanitization { + for i := 1; ; i++ { + cand := fmt.Sprintf("%s_%d", sanitizedKey, i) + if _, exists := newMap[cand]; !exists { + targetKey = cand + break + } } + } else { + // The original key was reserved during the first pass. } } if strVal, ok := item.(string); ok { valRes := pipeline.Scan(strVal) if len(valRes.Findings) > 0 { findings = append(findings, valRes.Findings...) - newMap[targetKey] = valRes.Sanitized - continue + strVal = valRes.Sanitized } - if sensitiveJSONKeyRegex.MatchString(k) && len(strVal) >= 8 { + if sensitiveJSONKeyRegex.MatchString(sanitizedKey) && len(strVal) >= 8 && !isAlreadyMasked(strVal) { masked := security.Mask(strVal) findings = append(findings, security.Finding{ Scanner: "secret_redactor", @@ -7284,8 +7341,7 @@ func sanitizeJSONStructure(v any, pipeline *security.Pipeline) (any, []security. Severity: "high", Detail: fmt.Sprintf("Redacted json_field (%d chars) -> %s", len(strVal), masked), }) - newMap[targetKey] = masked - continue + strVal = masked } newMap[targetKey] = strVal continue @@ -7312,6 +7368,10 @@ func sanitizeJSONStructure(v any, pipeline *security.Pipeline) (any, []security. } } +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 f781f63220..704d02e6cb 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -14,6 +14,7 @@ import ( "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" ) @@ -137,6 +138,10 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { 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)) @@ -167,6 +172,17 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { } 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) @@ -211,17 +227,20 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { 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.Contains(t, scribeResult["body"], "SCRIBE_SECRET_BACKEND=env") + assert.Contains(t, scribeResult["body"], "SCRIBE_SECRET_BACKEND=env", "incident-shaped wording should remain parseable and intact") 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), "-----BEGIN RSA"+" PRIVATE KEY-----") - assert.Contains(t, string(content7), "-----END RSA"+" PRIVATE KEY-----") + 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. @@ -294,6 +313,17 @@ func TestScanOutputFiles_ReturnsErrorWhenSanitizedWriteFails(t *testing.T) { 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") @@ -317,6 +347,24 @@ func TestScanOutputFiles_BackstopDoesNotRemaskExistingMask(t *testing.T) { 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) { diff --git a/internal/security/redactor.go b/internal/security/redactor.go index d1299c0a75..d7d0907faf 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -188,12 +188,13 @@ func (s *SecretRedactor) Scan(text string) ScanResult { // 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" { + if numBackslashes%2 == 1 && p.name != "json_field" { secret = secret[:len(secret)-1] end-- } @@ -202,7 +203,7 @@ func (s *SecretRedactor) Scan(text string) ScanResult { continue } masked := Mask(secret) - if len(secret) < minLen { + if originalLen < minLen { continue } if p.name != "json_field" && end < len(current) && (current[end] == '"' || current[end] == '\'') { @@ -301,7 +302,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)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\.|[^"\\])*)"|'((?:''|[^'])*)'|` + "'" + `([^\r\n]*\\)` + "'" + `|'((?:\\.|[^'])*)')`}, + {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*(?:\\.[^'\\]*)?)'|` + "'" + `([^\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 8db201ad3f..ef49fd970d 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -504,6 +504,18 @@ func TestSecretRedactor(t *testing.T) { 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("mask does not leave dangling escape sequence", func(t *testing.T) { input1 := `Authorization: Bearer abc\ndefghijkl` result1 := r.Scan(input1) From 22eb011646e69640e9a4374419b0266539b63498 Mon Sep 17 00:00:00 2001 From: anevans Date: Wed, 18 Nov 2026 11:14:35 -0500 Subject: [PATCH 12/15] fix(#5705): harden JSONL output sanitization Signed-off-by: anevans --- internal/cli/run.go | 185 +++++++++++++++++++-- internal/cli/scan_output_telemetry_test.go | 24 +++ internal/security/redactor.go | 2 +- internal/security/scanner_test.go | 6 + 4 files changed, 199 insertions(+), 18 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index 7fd025519e..8a4e178a64 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7032,11 +7032,39 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri 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" + 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 @@ -7051,6 +7079,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri 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)) @@ -7070,7 +7099,9 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri enc.SetIndent("", " ") } if err := enc.Encode(sanitizedVal); err != nil { - printer.StepWarn(fmt.Sprintf("Could not marshal sanitized JSON %s: %v; falling back to text scan", relPath, err)) + 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() @@ -7086,7 +7117,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri privateKey = true } } - changed = privateKey || len(findings) == 0 + changed = privateKey || len(structuralFindings) == 0 || backstopHasNewFinding(backstop.Findings, structuralFindings) if changed { findingCount += len(backstop.Findings) for _, f := range backstop.Findings { @@ -7098,7 +7129,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri Phase: "host_output", Finding: f, }) } - if backstop.Sanitized != "" { + 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 { @@ -7111,7 +7142,10 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri if quiet { return fmt.Errorf("could not write sanitized output file") } - return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) + 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 } @@ -7181,11 +7215,19 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri // 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 !isJSONL && json.Valid(content) && !json.Valid([]byte(out)) { - printer.StepWarn(fmt.Sprintf("Text redaction would invalidate JSON in %s; replacing output with a redacted JSON marker", relPath)) + 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 && isJSONL { + return fmt.Errorf("could not write sanitized output file") + } + if isJSONL { + return fmt.Errorf("could not write sanitized output file: %w", writeErr) + } return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) } } @@ -7215,6 +7257,119 @@ type jsonContainerFrame struct { 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 + 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 !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)) + findings += len(result.Findings) + allFindings = append(allFindings, result.Findings...) + 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 + } + originalBackstop := pipeline.Scan(encodedOriginal.String()) + if len(originalBackstop.Findings) > 0 { + findings += len(originalBackstop.Findings) + allFindings = append(allFindings, originalBackstop.Findings...) + privateKey := false + for _, finding := range originalBackstop.Findings { + privateKey = privateKey || finding.Name == "private_key" + } + if privateKey { + line = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`) + } else { + line = bytes.TrimSuffix(encodedOriginal.Bytes(), []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 { @@ -7314,17 +7469,13 @@ func sanitizeJSONStructure(v any, pipeline *security.Pipeline) (any, []security. if !keyNeedsSanitization { targetKey = k } - if _, exists := newMap[targetKey]; exists { - if keyNeedsSanitization { - for i := 1; ; i++ { - cand := fmt.Sprintf("%s_%d", sanitizedKey, i) - if _, exists := newMap[cand]; !exists { - targetKey = cand - break - } + 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 } - } else { - // The original key was reserved during the first pass. } } if strVal, ok := item.(string); ok { diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 704d02e6cb..da85ff7dcf 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -301,6 +301,30 @@ func TestScanOutputFiles_SingleRecordJSONL_PreservesLineCount(t *testing.T) { 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 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") diff --git a/internal/security/redactor.go b/internal/security/redactor.go index d7d0907faf..e24f80f14c 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -302,7 +302,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)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*(?:\\.[^'\\]*)?)'|` + "'" + `([^\r\n]*\\)` + "'" + `)`}, + {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\.|[^"\\])*)"|'((?:''|\\.|[^'\\])*)'|` + "'" + `([^\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 ef49fd970d..f5f170d2f4 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -516,6 +516,12 @@ func TestSecretRedactor(t *testing.T) { 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("mask does not leave dangling escape sequence", func(t *testing.T) { input1 := `Authorization: Bearer abc\ndefghijkl` result1 := r.Scan(input1) From 701dae6fd79d69b12b086be9fcfdfbf9de831cd8 Mon Sep 17 00:00:00 2001 From: anevans Date: Wed, 18 Nov 2026 13:57:18 -0500 Subject: [PATCH 13/15] fix(#5705): close remaining output sanitization gaps Signed-off-by: anevans --- internal/cli/run.go | 30 +++++++++++++----- internal/cli/scan_output_telemetry_test.go | 36 ++++++++++++++++++++-- internal/security/redactor.go | 2 +- internal/security/scanner_test.go | 7 +++++ 4 files changed, 64 insertions(+), 11 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index 8a4e178a64..63f03a3544 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7222,12 +7222,9 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri out = `{"error":"output removed because text redaction would invalidate JSON"}` } if writeErr := writeFile(path, []byte(out), 0o644); writeErr != nil { - if quiet && isJSONL { + if quiet { return fmt.Errorf("could not write sanitized output file") } - if isJSONL { - return fmt.Errorf("could not write sanitized output file: %w", writeErr) - } return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) } } @@ -7261,6 +7258,15 @@ func sanitizeJSONLines(content []byte, pipeline *security.Pipeline) ([]byte, int 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') @@ -7273,7 +7279,13 @@ func sanitizeJSONLines(content []byte, pipeline *security.Pipeline) ([]byte, int } trimmed := bytes.TrimSpace(line) if len(trimmed) > 0 { - if !json.Valid(trimmed) { + if streamHasPrivateKey && json.Valid(trimmed) { + 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) @@ -7294,9 +7306,11 @@ func sanitizeJSONLines(content []byte, pipeline *security.Pipeline) ([]byte, int result := pipeline.Scan(string(line)) findings += len(result.Findings) allFindings = append(allFindings, result.Findings...) - line = []byte(result.Sanitized) - if !json.Valid(line) { - line = []byte(`{"error":"output removed because text redaction would invalidate JSON"}`) + if len(result.Findings) > 0 && 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 diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index da85ff7dcf..103f0e7ab2 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -128,7 +128,7 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { // 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=env"}` + 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 @@ -227,7 +227,8 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { 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.Contains(t, scribeResult["body"], "SCRIBE_SECRET_BACKEND=env", "incident-shaped wording should remain parseable and intact") + 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) @@ -315,6 +316,37 @@ func TestScanOutputFiles_JSONLCrossValuePrivateKeyRemainsValid(t *testing.T) { 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 TestScanOutputFiles_QuietJSONFallbackDoesNotPrintPath(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "agent-chosen-secret-name.json") diff --git a/internal/security/redactor.go b/internal/security/redactor.go index e24f80f14c..5b9f56395c 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -302,7 +302,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)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\.|[^"\\])*)"|'((?:''|\\.|[^'\\])*)'|` + "'" + `([^\r\n]*\\)` + "'" + `)`}, + {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\[\s\S]|[^"\\])*)"|'((?:''|\\[\s\S]|[^'\\])*)'|` + "'" + `([^\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 f5f170d2f4..3501e75456 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -522,6 +522,13 @@ func TestSecretRedactor(t *testing.T) { 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("mask does not leave dangling escape sequence", func(t *testing.T) { input1 := `Authorization: Bearer abc\ndefghijkl` result1 := r.Scan(input1) From 3b6f25ef93ce6f248c60bb43406006aba7054308 Mon Sep 17 00:00:00 2001 From: anevans Date: Wed, 18 Nov 2026 14:32:48 -0500 Subject: [PATCH 14/15] fix(#5705): scan numeric JSON leaves and honor backstop runtime secrets Signed-off-by: anevans --- internal/cli/run.go | 45 +++++++++++++++++----- internal/cli/scan_output_telemetry_test.go | 29 +++++++++++++- 2 files changed, 63 insertions(+), 11 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index 63f03a3544..b7102af8de 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7160,13 +7160,17 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri 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 !privateKey { + if !hasNewFinding { return nil } findingCount += len(backstop.Findings) @@ -7179,8 +7183,13 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri Phase: "host_output", Finding: f, }) } - marker := []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`) - if writeErr := writeFile(path, marker, 0o644); writeErr != nil { + 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") } @@ -7322,17 +7331,23 @@ func sanitizeJSONLines(content []byte, pipeline *security.Pipeline) ([]byte, int return nil, findings, allFindings, err } originalBackstop := pipeline.Scan(encodedOriginal.String()) - if len(originalBackstop.Findings) > 0 { + 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...) - privateKey := false - for _, finding := range originalBackstop.Findings { - privateKey = privateKey || finding.Name == "private_key" - } - if privateKey { + if privateKey || originalBackstop.Sanitized == "" || !json.Valid([]byte(originalBackstop.Sanitized)) { line = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`) } else { - line = bytes.TrimSuffix(encodedOriginal.Bytes(), []byte("\n")) + line = []byte(originalBackstop.Sanitized) } } } @@ -7528,6 +7543,16 @@ func sanitizeJSONStructure(v any, pipeline *security.Pipeline) (any, []security. 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 } diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 103f0e7ab2..c8be94761f 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -362,7 +362,7 @@ func TestScanOutputFiles_ReturnsErrorWhenSanitizedWriteFails(t *testing.T) { path := filepath.Join(dir, "secret.txt") require.NoError(t, os.WriteFile(path, []byte("Token: ghp_FAKEtesttoken000000000000000000000000"), 0o644)) - err := scanOutputFilesWithWriter(dir, "trace-id", "normal", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { + err := scanOutputFilesWithWriter(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { return os.ErrPermission }) require.Error(t, err) @@ -438,6 +438,33 @@ func TestScanOutputFiles_CleanJSON(t *testing.T) { 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 From 05deda0a2940834eda38fddbd5c7f4478b2a003b Mon Sep 17 00:00:00 2001 From: anevans Date: Wed, 18 Nov 2026 15:45:21 -0500 Subject: [PATCH 15/15] fix(#5705): address review findings on PEM lines, duplicate keys, and YAML fields Fail closed on raw multiline PEM blocks in JSONL streams regardless of whether individual lines parse as JSON. Replace duplicate-key JSONL records with an error marker when structural findings cannot be safely serialized. Trim trailing newline from the JSONL no-structural-findings backstop encoder to prevent extra blank lines. Prevent trailing literal backslashes in single-quoted YAML fields from consuming adjacent fields in json_field regex. Remove detect-private-key pre-commit exclusion by concatenating test PEM fixture strings. Signed-off-by: anevans --- .pre-commit-config.yaml | 2 +- internal/cli/run.go | 23 +++--- internal/cli/scan_output_telemetry_test.go | 89 +++++++++++++++++++++- internal/security/redactor.go | 7 +- internal/security/scanner_test.go | 15 ++++ 5 files changed, 124 insertions(+), 12 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6c785d67f7..0349e77620 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -9,7 +9,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - id: detect-private-key - exclude: "internal/layers/secrets_test\\.go$|internal/security/scanner_test\\.go$|internal/dispatch/gcf/provisioner_test\\.go$|internal/cli/mint_test\\.go$|internal/cli/scan_output_telemetry_test\\.go$|tests/.*test_.*\\.py$" + exclude: "internal/layers/secrets_test\\.go$|internal/security/scanner_test\\.go$|internal/dispatch/gcf/provisioner_test\\.go$|internal/cli/mint_test\\.go$|tests/.*test_.*\\.py$" - id: check-added-large-files args: ["--maxkb=1000"] - id: check-merge-conflict diff --git a/internal/cli/run.go b/internal/cli/run.go index 3b3792e725..e78b590b94 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7322,7 +7322,7 @@ func sanitizeJSONLines(content []byte, pipeline *security.Pipeline) ([]byte, int } trimmed := bytes.TrimSpace(line) if len(trimmed) > 0 { - if streamHasPrivateKey && json.Valid(trimmed) { + if streamHasPrivateKey { line = []byte(`{"error":"output removed because output contained a cross-record private key"}`) if len(allFindings) == 0 { findings += len(streamScan.Findings) @@ -7347,12 +7347,16 @@ func sanitizeJSONLines(content []byte, pipeline *security.Pipeline) ([]byte, int allFindings = append(allFindings, fs...) if hasDuplicateJSONKeys(trimmed) { result := pipeline.Scan(string(line)) - findings += len(result.Findings) - allFindings = append(allFindings, result.Findings...) - if len(result.Findings) > 0 && result.Sanitized != "" { - line = []byte(result.Sanitized) - if !json.Valid(line) { - line = []byte(`{"error":"output removed because text redaction would invalidate JSON"}`) + 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 { @@ -7364,7 +7368,8 @@ func sanitizeJSONLines(content []byte, pipeline *security.Pipeline) ([]byte, int if err := enc.Encode(value); err != nil { return nil, findings, allFindings, err } - originalBackstop := pipeline.Scan(encodedOriginal.String()) + encodedBytes := bytes.TrimSuffix(encodedOriginal.Bytes(), []byte("\n")) + originalBackstop := pipeline.Scan(string(encodedBytes)) hasNewFinding := false privateKey := false for _, f := range originalBackstop.Findings { @@ -7381,7 +7386,7 @@ func sanitizeJSONLines(content []byte, pipeline *security.Pipeline) ([]byte, int if privateKey || originalBackstop.Sanitized == "" || !json.Valid([]byte(originalBackstop.Sanitized)) { line = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`) } else { - line = []byte(originalBackstop.Sanitized) + line = bytes.TrimSuffix([]byte(originalBackstop.Sanitized), []byte("\n")) } } } diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index c8be94761f..be2d2ce06e 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -139,7 +139,7 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { 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-----"]` + 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 @@ -347,6 +347,93 @@ func TestSanitizeJSONLinesFailsClosedForPrivateKeyAcrossRecords(t *testing.T) { } } +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") diff --git a/internal/security/redactor.go b/internal/security/redactor.go index 5b9f56395c..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. @@ -302,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)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\[\s\S]|[^"\\])*)"|'((?:''|\\[\s\S]|[^'\\])*)'|` + "'" + `([^\r\n]*\\)` + "'" + `)`}, + {"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 3501e75456..8e31c37455 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -529,6 +529,21 @@ func TestSecretRedactor(t *testing.T) { 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)