From 2ff063a28b7c30015083054dd1c517b8e243ec36 Mon Sep 17 00:00:00 2001 From: anevans Date: Mon, 16 Nov 2026 10:07:15 -0500 Subject: [PATCH 01/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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) From f66628bf139cbffaa42bb0d7aaf9f15b474c5d49 Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 19 Nov 2026 09:42:17 -0500 Subject: [PATCH 16/51] fix(#5705): fail closed on duplicate-key and cross-record JSON secrets Move the JSON output sanitization helpers into internal/security so the structural walker, the JSONL record splitter, and duplicate-key detection live beside the redactor instead of in internal/cli. Scan duplicate-key documents with a token-preserving walk. Map decoding drops earlier occurrences, so an escaped secret in an overwritten value survived both the raw-text scan and the decoded value. Every key and scalar is now scanned, and a key removed entirely (a null byte or a bidi override) is replaced with a placeholder instead of being restored. Redact JSONL records individually before the whole-stream pass, and fail closed only for the records a genuinely cross-record match covers. A private key confined to one record is redacted in place instead of replacing every record in the file, and a cross-record runtime secret is no longer detected and discarded. Always apply the serialized-output backstop instead of dismissing a finding because its name and count match the structural pass; that comparison hid a second, different runtime secret. The redactor now skips a captured value that is already a mask placeholder, so the backstop stays idempotent without weakening redaction. Collect sanitized-output write failures and return them joined after the walk, so one unwritable file no longer leaves every later file unredacted. Document the fail-closed markers and the fatal write errors. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 25 + .../user/run-artifacts-and-private-data.md | 4 +- internal/cli/run.go | 519 ++------------- internal/cli/scan_output_telemetry_test.go | 80 ++- internal/security/jsonsanitize.go | 608 ++++++++++++++++++ internal/security/jsonsanitize_test.go | 272 ++++++++ internal/security/redactor.go | 25 +- 7 files changed, 1028 insertions(+), 505 deletions(-) create mode 100644 internal/security/jsonsanitize.go create mode 100644 internal/security/jsonsanitize_test.go diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index f06be8cc3a..8ec41547bb 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -612,6 +612,31 @@ The post-run output scan skips `/skills/` and origins and warnings are documented in [Configuring with Skills § The persona list file](../guides/user/customizing-with-skills.md#the-persona-list-file). +### The post-run output scan + +`scanOutputFiles` runs the output pipeline (Unicode normalization, then secret +redaction) over every file under `output/` except the skips above and +`security/findings.jsonl`. Valid JSON is sanitized structurally so redaction +never changes its syntax: object keys and scalar leaves are scanned +individually, and a document with duplicate keys goes through a +token-preserving walk so every decoded occurrence is scanned, including an +earlier value that map decoding would drop. `.jsonl`/`.ndjson` files are +sanitized one record at a time to preserve the record framing; a secret that +spans records cannot be redacted without rewriting that framing, so only the +records it covers are replaced. + +Some content cannot be redacted in place. A JSON document or JSONL record is +replaced with a valid fail-closed marker instead — never with corrupted +syntax — when a private-key block or a cross-record match spans JSON +framing, or when a text redaction would leave invalid JSON. Markers look +like `{"error":"output removed because …"}` and are logged as findings in +`security/findings.jsonl`. + +A sanitized file that cannot be written does not stop the walk: every +remaining file is still scanned and redacted, and the run fails closed +afterwards with all write errors joined. In `quiet` mode the affected paths +are counted, not named (ADR 0163). + ## Agent rule layering When `fullsend run` executes an agent, Claude Code loads instructions from diff --git a/docs/guides/user/run-artifacts-and-private-data.md b/docs/guides/user/run-artifacts-and-private-data.md index 901d5d4ecb..752ba15233 100644 --- a/docs/guides/user/run-artifacts-and-private-data.md +++ b/docs/guides/user/run-artifacts-and-private-data.md @@ -345,7 +345,9 @@ Tool results in those files can quote what the agent read, such as the text of a private Jira issue. On a public repository, any signed-in user can download the artifact until it expires. The output scan masks secret literals; it does not remove personal data, customer names or other private -business text. +business text. When a secret cannot be masked without breaking a file's JSON +structure, the affected JSON document or JSONL record is replaced with a JSON +error marker, and a sanitized file that cannot be written fails the run. `fullsend run` leaves `output/` untouched. At the end of the job, `fullsend prepare-artifacts` builds a filtered copy at the level you set, and diff --git a/internal/cli/run.go b/internal/cli/run.go index 5747b75ae7..4274387852 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7087,6 +7087,10 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri findingCount := 0 // At quiet, unreadable and unwritable files are counted, not named. unreadable, unwritable := 0, 0 + // Write failures are collected rather than returned from the walk callback + // so every remaining file is still scanned and redacted. The run still + // fails closed once the walk finishes (#5705). + var writeErrs []error findingsPath := filepath.Join(outputDir, "security", "findings.jsonl") err := filepath.WalkDir(outputDir, func(path string, d os.DirEntry, err error) error { @@ -7117,185 +7121,69 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri return nil } content, readErr := os.ReadFile(path) + relPath, _ := filepath.Rel(outputDir, path) if readErr != nil { if quiet { unreadable++ return nil } - relPath, _ := filepath.Rel(outputDir, path) 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) + ext := strings.ToLower(filepath.Ext(path)) + + // JSONL and NDJSON are sanitized record by record so one record never + // rewrites another (#5705). + if ext == ".jsonl" || ext == ".ndjson" { + out, jsonLineFindings, scanErr := security.SanitizeJSONLines(content, pipeline) if scanErr != nil { - return fmt.Errorf("could not sanitize JSONL output: %w", scanErr) + return fmt.Errorf("could not sanitize JSONL output %s: %w", relPath, scanErr) } - if jsonLineFindings > 0 { - findingCount += jsonLineFindings - for _, f := range jsonLineDetails { + if len(jsonLineFindings) > 0 { + findingCount += len(jsonLineFindings) + for _, f := range jsonLineFindings { if !quiet { - printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s: %s", f.Name, filepath.Base(path), f.Detail)) + 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, }) } - // 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) + writeErrs = append(writeErrs, writeFailure(quiet, relPath, writeErr, &unwritable)) } } return nil } - relPath, _ := filepath.Rel(outputDir, path) - - ext := strings.ToLower(filepath.Ext(path)) - isJSONL = ext == ".jsonl" || ext == ".ndjson" - - // If the file is valid JSON (and not JSONL or containing duplicate keys), structurally - // sanitize keys and string leaves to guarantee that redaction never breaks JSON syntax - // and fails closed (#5705). - if !isJSONL && !hasDuplicateJSONKeys(content) { - dec := json.NewDecoder(bytes.NewReader(content)) - dec.UseNumber() - var jsonVal any - if dec.Decode(&jsonVal) == nil { - var trailing any - if dec.Decode(&trailing) == io.EOF { - sanitizedVal, findings := sanitizeJSONStructure(jsonVal, pipeline) - if len(findings) > 0 { - findingCount += len(findings) - structuralFindings := findings - for _, f := range findings { - if !quiet { - printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s: %s", f.Name, relPath, f.Detail)) - } - security.AppendFinding(findingsPath, - security.TracedFinding{ - TraceID: traceID, - Timestamp: time.Now().UTC().Format(time.RFC3339), - Phase: "host_output", - Finding: f, - }) - } - var buf bytes.Buffer - enc := json.NewEncoder(&buf) - enc.SetEscapeHTML(false) - if bytes.Contains(bytes.TrimRight(content, "\r\n"), []byte("\n")) { - enc.SetIndent("", " ") - } - if err := enc.Encode(sanitizedVal); err != nil { - if !quiet { - printer.StepWarn(fmt.Sprintf("Could not marshal sanitized JSON %s: %v; falling back to text scan", relPath, err)) - } - // Fall through to plain text scan below instead of failing open. - } else { - marshaled := buf.Bytes() - // Backstop the serialized output. If text redaction finds - // another secret, only accept it when the result remains valid - // JSON; otherwise discard the potentially malformed payload. - backstop := pipeline.Scan(string(marshaled)) - if len(backstop.Findings) > 0 { - changed := false - privateKey := false - for _, finding := range backstop.Findings { - if finding.Name == "private_key" { - privateKey = true - } - } - changed = privateKey || len(structuralFindings) == 0 || backstopHasNewFinding(backstop.Findings, structuralFindings) - if changed { - findingCount += len(backstop.Findings) - for _, f := range backstop.Findings { - if !quiet { - printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s (backstop): %s", f.Name, relPath, f.Detail)) - } - security.AppendFinding(findingsPath, security.TracedFinding{ - TraceID: traceID, Timestamp: time.Now().UTC().Format(time.RFC3339), - Phase: "host_output", Finding: f, - }) - } - if backstop.Sanitized != "" && (privateKey || len(structuralFindings) == 0 || backstopHasNewFinding(backstop.Findings, structuralFindings)) { - if privateKey || !json.Valid([]byte(backstop.Sanitized)) { - marshaled = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`) - } else { - marshaled = []byte(backstop.Sanitized) - } - } - } - } - if writeErr := writeFile(path, marshaled, 0o644); writeErr != nil { - if quiet { - return fmt.Errorf("could not write sanitized output file") - } - if !isJSONL { - return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) - } - return fmt.Errorf("could not write sanitized output file: %w", writeErr) - } - return nil - } - } else { - // Scan encoded JSON for patterns spanning separate leaves. Such a - // match cannot be safely applied as raw text, so replace the - // whole document with a valid fail-closed marker. - var buf bytes.Buffer - enc := json.NewEncoder(&buf) - enc.SetEscapeHTML(false) - if err := enc.Encode(jsonVal); err != nil { - return fmt.Errorf("could not encode JSON output for security scan") - } - backstop := pipeline.Scan(buf.String()) - hasNewFinding := false - privateKey := false - for _, f := range backstop.Findings { - if f.Name == "private_key" { - privateKey = true - hasNewFinding = true - } else if f.Name == "runtime_secret" { - hasNewFinding = true - } - } - if !hasNewFinding { - return nil - } - findingCount += len(backstop.Findings) - for _, f := range backstop.Findings { - if !quiet { - printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s (backstop): %s", f.Name, relPath, f.Detail)) - } - security.AppendFinding(findingsPath, security.TracedFinding{ - TraceID: traceID, Timestamp: time.Now().UTC().Format(time.RFC3339), - Phase: "host_output", Finding: f, - }) - } - var finalBytes []byte - if privateKey || backstop.Sanitized == "" || !json.Valid([]byte(backstop.Sanitized)) { - finalBytes = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`) - } else { - finalBytes = []byte(backstop.Sanitized) - } - if writeErr := writeFile(path, finalBytes, 0o644); writeErr != nil { - if quiet { - return fmt.Errorf("could not write sanitized output file") - } - return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) - } - return nil + // Structurally sanitize valid JSON so redaction never breaks JSON + // syntax and fails closed (#5705). Non-JSON files fall through to the + // plain text scan below. + if json.Valid(bytes.TrimSpace(content)) { + out, jsonFindings, jsonErr := security.SanitizeJSONDocument(content, pipeline) + if jsonErr != nil { + return fmt.Errorf("could not sanitize JSON output %s: %w", relPath, jsonErr) + } + if len(jsonFindings) > 0 { + findingCount += len(jsonFindings) + for _, f := range jsonFindings { + if !quiet { + printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s: %s", f.Name, relPath, f.Detail)) } + security.AppendFinding(findingsPath, security.TracedFinding{ + TraceID: traceID, Timestamp: time.Now().UTC().Format(time.RFC3339), + Phase: "host_output", Finding: f, + }) + } + if writeErr := writeFile(path, out, 0o644); writeErr != nil { + writeErrs = append(writeErrs, writeFailure(quiet, relPath, writeErr, &unwritable)) } } + return nil } - // Non-JSON files or fallback: run plain text pipeline scan. + // Non-JSON files: run plain text pipeline scan. text := string(content) result := pipeline.Scan(text) if len(result.Findings) > 0 { @@ -7314,10 +7202,8 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri } // 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. + // A malformed input that still parses as JSON must not be turned + // into invalid JSON by a cross-value text redaction. 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)) @@ -7325,10 +7211,7 @@ 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 { - return fmt.Errorf("could not write sanitized output file") - } - return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) + writeErrs = append(writeErrs, writeFailure(quiet, relPath, writeErr, &unwritable)) } } return nil @@ -7348,317 +7231,21 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri } else { printer.StepDone("Output files clean — no issues found") } - return nil -} - -type jsonContainerFrame struct { - isObject bool - expectingKey bool - keys map[string]bool -} - -func sanitizeJSONLines(content []byte, pipeline *security.Pipeline) ([]byte, int, []security.Finding, error) { - var out bytes.Buffer - findings := 0 - var allFindings []security.Finding - // Keep a whole-stream pass for multiline patterns such as PEM private keys - // that can span otherwise-valid JSONL records. We only use it as a detector: - // raw replacement would consume JSON framing, so matching streams are - // replaced record-by-record with valid fail-closed JSON markers. - streamScan := pipeline.Scan(string(content)) - streamHasPrivateKey := false - for _, finding := range streamScan.Findings { - streamHasPrivateKey = streamHasPrivateKey || finding.Name == "private_key" - } - for len(content) > 0 { - line := content - newline := bytes.IndexByte(content, '\n') - hasNewline := newline >= 0 - if hasNewline { - line = content[:newline] - content = content[newline+1:] - } else { - content = nil - } - trimmed := bytes.TrimSpace(line) - if len(trimmed) > 0 { - if streamHasPrivateKey { - line = []byte(`{"error":"output removed because output contained a cross-record private key"}`) - if len(allFindings) == 0 { - findings += len(streamScan.Findings) - allFindings = append(allFindings, streamScan.Findings...) - } - } else if !json.Valid(trimmed) { - result := pipeline.Scan(string(line)) - if len(result.Findings) > 0 { - findings += len(result.Findings) - allFindings = append(allFindings, result.Findings...) - line = []byte(result.Sanitized) - } - } else { - var value any - dec := json.NewDecoder(bytes.NewReader(trimmed)) - dec.UseNumber() - if err := dec.Decode(&value); err != nil { - return nil, findings, allFindings, err - } - sanitized, fs := sanitizeJSONStructure(value, pipeline) - findings += len(fs) - allFindings = append(allFindings, fs...) - if hasDuplicateJSONKeys(trimmed) { - result := pipeline.Scan(string(line)) - if len(fs) > 0 { - line = []byte(`{"error":"output removed because structural findings cannot be safely applied to duplicate-key JSON"}`) - } else if len(result.Findings) > 0 { - findings += len(result.Findings) - allFindings = append(allFindings, result.Findings...) - if result.Sanitized != "" { - line = []byte(result.Sanitized) - if !json.Valid(line) { - line = []byte(`{"error":"output removed because text redaction would invalidate JSON"}`) - } - } - } - } else { - needsRewrite := len(fs) > 0 - if !needsRewrite { - var encodedOriginal bytes.Buffer - enc := json.NewEncoder(&encodedOriginal) - enc.SetEscapeHTML(false) - if err := enc.Encode(value); err != nil { - return nil, findings, allFindings, err - } - encodedBytes := bytes.TrimSuffix(encodedOriginal.Bytes(), []byte("\n")) - originalBackstop := pipeline.Scan(string(encodedBytes)) - hasNewFinding := false - privateKey := false - for _, f := range originalBackstop.Findings { - if f.Name == "private_key" { - privateKey = true - hasNewFinding = true - } else if f.Name == "runtime_secret" { - hasNewFinding = true - } - } - if hasNewFinding { - findings += len(originalBackstop.Findings) - allFindings = append(allFindings, originalBackstop.Findings...) - if privateKey || originalBackstop.Sanitized == "" || !json.Valid([]byte(originalBackstop.Sanitized)) { - line = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`) - } else { - line = bytes.TrimSuffix([]byte(originalBackstop.Sanitized), []byte("\n")) - } - } - } - if needsRewrite { - var encoded bytes.Buffer - enc := json.NewEncoder(&encoded) - enc.SetEscapeHTML(false) - if err := enc.Encode(sanitized); err != nil { - return nil, findings, allFindings, err - } - line = bytes.TrimSuffix(encoded.Bytes(), []byte("\n")) - backstop := pipeline.Scan(string(line)) - if len(backstop.Findings) > 0 { - findings += len(backstop.Findings) - allFindings = append(allFindings, backstop.Findings...) - privateKey := false - for _, finding := range backstop.Findings { - privateKey = privateKey || finding.Name == "private_key" - } - if privateKey || !json.Valid([]byte(backstop.Sanitized)) { - line = []byte(`{"error":"output removed because backstop redaction would invalidate JSON"}`) - } else { - line = []byte(backstop.Sanitized) - } - } - } - } - } - } - out.Write(line) - if hasNewline { - out.WriteByte('\n') - } - } - return out.Bytes(), findings, allFindings, nil -} - -func backstopHasNewFinding(backstop, structural []security.Finding) bool { - counts := make(map[string]int, len(structural)) - for _, finding := range structural { - counts[finding.Name]++ - } - for _, finding := range backstop { - if counts[finding.Name] == 0 { - return true - } - counts[finding.Name]-- - } - return false -} - -// hasDuplicateJSONKeys parses content token by token and returns true if any -// JSON object within the payload contains duplicate keys. -func hasDuplicateJSONKeys(content []byte) bool { - dec := json.NewDecoder(bytes.NewReader(content)) - dec.UseNumber() - var stack []*jsonContainerFrame - for { - tok, err := dec.Token() - if err != nil { - return false - } - switch t := tok.(type) { - case json.Delim: - switch t { - case '{': - stack = append(stack, &jsonContainerFrame{ - isObject: true, - expectingKey: true, - keys: make(map[string]bool), - }) - case '[': - stack = append(stack, &jsonContainerFrame{ - isObject: false, - }) - case '}', ']': - if len(stack) > 0 { - stack = stack[:len(stack)-1] - } - if len(stack) > 0 && stack[len(stack)-1].isObject { - stack[len(stack)-1].expectingKey = true - } - } - case string: - if len(stack) > 0 && stack[len(stack)-1].isObject { - top := stack[len(stack)-1] - if top.expectingKey { - if top.keys[t] { - return true - } - top.keys[t] = true - top.expectingKey = false - } else { - top.expectingKey = true - } - } - default: - if len(stack) > 0 && stack[len(stack)-1].isObject { - stack[len(stack)-1].expectingKey = true - } - } + if err := errors.Join(writeErrs...); err != nil { + return err } + return nil } -var sensitiveJSONKeyRegex = regexp.MustCompile(`(?i)(?:key|token|secret|password|credential|auth)`) - -// sanitizeJSONStructure recursively visits all keys and string values in parsed JSON data, -// scans each key and string leaf using the pipeline, and collects any findings. -func sanitizeJSONStructure(v any, pipeline *security.Pipeline) (any, []security.Finding) { - var findings []security.Finding - switch val := v.(type) { - case string: - res := pipeline.Scan(val) - if len(res.Findings) > 0 { - findings = append(findings, res.Findings...) - if res.Sanitized != "" { - return res.Sanitized, findings - } - return "", findings - } - return val, nil - case map[string]any: - newMap := make(map[string]any, len(val)) - keys := make([]string, 0, len(val)) - for k := range val { - keys = append(keys, k) - } - sort.Strings(keys) - // Reserve clean original names before assigning sanitized names so a - // secret key can never steal a legitimate key's name/value slot. - for _, k := range keys { - if keyRes := pipeline.Scan(k); len(keyRes.Findings) == 0 { - newMap[k] = nil - } - } - for _, k := range keys { - item := val[k] - sanitizedKey := k - keyRes := pipeline.Scan(k) - keyNeedsSanitization := len(keyRes.Findings) > 0 - if len(keyRes.Findings) > 0 { - findings = append(findings, keyRes.Findings...) - if keyRes.Sanitized != "" { - sanitizedKey = keyRes.Sanitized - } - } - targetKey := sanitizedKey - if !keyNeedsSanitization { - targetKey = k - } - if _, exists := newMap[targetKey]; exists && keyNeedsSanitization { - for i := 1; ; i++ { - cand := fmt.Sprintf("%s_%d", sanitizedKey, i) - if _, exists := newMap[cand]; !exists { - targetKey = cand - break - } - } - } - if strVal, ok := item.(string); ok { - valRes := pipeline.Scan(strVal) - if len(valRes.Findings) > 0 { - findings = append(findings, valRes.Findings...) - strVal = valRes.Sanitized - } - if sensitiveJSONKeyRegex.MatchString(sanitizedKey) && len(strVal) >= 8 && !isAlreadyMasked(strVal) { - masked := security.Mask(strVal) - findings = append(findings, security.Finding{ - Scanner: "secret_redactor", - Name: "json_field", - Severity: "high", - Detail: fmt.Sprintf("Redacted json_field (%d chars) -> %s", len(strVal), masked), - }) - strVal = masked - } - newMap[targetKey] = strVal - continue - } - newVal, f := sanitizeJSONStructure(item, pipeline) - if len(f) > 0 { - findings = append(findings, f...) - } - newMap[targetKey] = newVal - } - return newMap, findings - case []any: - newSlice := make([]any, len(val)) - for i, item := range val { - newVal, f := sanitizeJSONStructure(item, pipeline) - if len(f) > 0 { - findings = append(findings, f...) - } - newSlice[i] = newVal - } - return newSlice, findings - case json.Number: - res := pipeline.Scan(val.String()) - if len(res.Findings) > 0 { - findings = append(findings, res.Findings...) - if res.Sanitized != "" { - return res.Sanitized, findings - } - return "", findings - } - return val, nil - default: - return val, nil +// writeFailure records a sanitized-output write error. At the quiet progress +// level the path is withheld because it can carry an agent-chosen name +// (ADR 0163); non-quiet callers name it. +func writeFailure(quiet bool, relPath string, writeErr error, unwritable *int) error { + *unwritable++ + if quiet { + return fmt.Errorf("could not write sanitized output file") } -} - -func isAlreadyMasked(value string) bool { - return value == "***" || strings.HasSuffix(value, "...") && len(value) == 7 + return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) } // injectTraceID appends the FULLSEND_TRACE_ID to the sandbox .env file. diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index be2d2ce06e..e25c839fbb 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -319,9 +319,9 @@ func TestScanOutputFiles_JSONLCrossValuePrivateKeyRemainsValid(t *testing.T) { 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) + got, findings, err := security.SanitizeJSONLines(content, pipeline) require.NoError(t, err) - assert.Positive(t, findings) + assert.NotEmpty(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") @@ -334,11 +334,10 @@ func TestSanitizeJSONLinesFailsClosedForPrivateKeyAcrossRecords(t *testing.T) { 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) + got, findings, err := security.SanitizeJSONLines(content, pipeline) require.NoError(t, err) - assert.Positive(t, findings) - require.NotEmpty(t, details) - assert.Equal(t, "private_key", details[0].Name) + require.NotEmpty(t, findings) + assert.Equal(t, "private_key", findings[0].Name) lines := strings.Split(strings.TrimSuffix(string(got), "\n"), "\n") require.Len(t, lines, 3) for _, line := range lines { @@ -352,11 +351,10 @@ func TestSanitizeJSONLinesFailsClosedForRawMultilinePEM(t *testing.T) { 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) + got, findings, err := security.SanitizeJSONLines(content, pipeline) require.NoError(t, err) - assert.Positive(t, findings) - require.NotEmpty(t, details) - assert.Equal(t, "private_key", details[0].Name) + require.NotEmpty(t, findings) + assert.Equal(t, "private_key", findings[0].Name) lines := strings.Split(strings.TrimSuffix(string(got), "\n"), "\n") require.Len(t, lines, 3) for _, line := range lines { @@ -385,19 +383,20 @@ func TestScanOutputFiles_JSONLRawMultilinePEMRemainsValid(t *testing.T) { } } -func TestSanitizeJSONLines_DuplicateKeyRecordWithStructuralFindingsFailsClosed(t *testing.T) { +func TestSanitizeJSONLines_DuplicateKeyRecordRedactsEscapedSecret(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. + // Raw text scanning doesn't match the unicode escapes and map decoding drops the + // earlier duplicate, so only a token-preserving walk finds and removes it. content := []byte("{\"a\":\"first\",\"a\":\"second\",\"password\":\"\\u0073\\u0065\\u0063\\u0072\\u0065\\u0074_password_1234\"}\n") - got, findings, details, err := sanitizeJSONLines(content, pipeline) + got, findings, err := security.SanitizeJSONLines(content, pipeline) require.NoError(t, err) - assert.Positive(t, findings) - require.NotEmpty(t, details) + assert.NotEmpty(t, findings) line := strings.TrimSpace(string(got)) assert.True(t, json.Valid([]byte(line))) - assert.Contains(t, line, "output removed") assert.NotContains(t, line, "password_1234") + assert.Contains(t, line, `"a":"first"`, "an earlier duplicate value must survive redaction") + assert.Contains(t, line, `"a":"second"`, "the second duplicate value must survive redaction") } func TestSanitizeJSONLines_BackstopNoStructuralFindingsPreservesLineCount(t *testing.T) { @@ -408,10 +407,9 @@ func TestSanitizeJSONLines_BackstopNoStructuralFindingsPreservesLineCount(t *tes pipeline := security.OutputPipeline() content := []byte("{\"field1\":\"foo\",\"field2\":\"bar\"}\n{\"field3\":\"second record\"}\n") - got, findings, details, err := sanitizeJSONLines(content, pipeline) + got, findings, err := security.SanitizeJSONLines(content, pipeline) require.NoError(t, err) - assert.Positive(t, findings) - require.NotEmpty(t, details) + require.NotEmpty(t, findings) 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) @@ -420,18 +418,20 @@ func TestSanitizeJSONLines_BackstopNoStructuralFindingsPreservesLineCount(t *tes assert.NotContains(t, lines[0], secretVal) } -func TestSanitizeJSONLines_NeedsRewriteWithBackstopPrivateKeyFailsClosed(t *testing.T) { +func TestSanitizeJSONLines_SingleRecordPrivateKeyRedactedInPlace(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) + got, findings, err := security.SanitizeJSONLines(content, pipeline) require.NoError(t, err) - assert.Positive(t, findings) - require.NotEmpty(t, details) + assert.NotEmpty(t, findings) line := strings.TrimSpace(string(got)) assert.True(t, json.Valid([]byte(line))) - assert.Contains(t, line, "output removed") + assert.Equal(t, 1, strings.Count(string(got), "\n"), "one record must stay one record") + assert.NotContains(t, line, "ghp_FAKEtesttoken") + assert.NotContains(t, line, "PRIVATE KEY-----") + assert.Contains(t, line, "[REDACTED PRIVATE KEY]", "a key confined to one record is redacted in place, not failed closed") } func TestScanOutputFiles_QuietJSONFallbackDoesNotPrintPath(t *testing.T) { @@ -467,6 +467,31 @@ func TestScanOutputFiles_QuietJSONWriteFailureIsFatal(t *testing.T) { assert.EqualError(t, err, "could not write sanitized output file") } +// TestScanOutputFiles_ContinuesRedactingAfterWriteFailure pins that one +// unwritable file does not stop the walk: every other file is still redacted, +// and the run fails closed with the collected error afterwards. +func TestScanOutputFiles_ContinuesRedactingAfterWriteFailure(t *testing.T) { + dir := t.TempDir() + first := filepath.Join(dir, "a-secret.txt") + second := filepath.Join(dir, "b-secret.txt") + const secret = "ghp_FAKEtesttoken000000000000000000000000" + require.NoError(t, os.WriteFile(first, []byte("Token: "+secret), 0o644)) + require.NoError(t, os.WriteFile(second, []byte("Token: "+secret), 0o644)) + + err := scanOutputFilesWithWriter(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(path string, data []byte, mode os.FileMode) error { + if path == first { + return os.ErrPermission + } + return os.WriteFile(path, data, mode) + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "could not write sanitized a-secret.txt") + + got, readErr := os.ReadFile(second) + require.NoError(t, readErr) + assert.NotContains(t, string(got), secret, "files after a write failure must still be redacted") +} + func TestScanOutputFiles_BackstopDoesNotRemaskExistingMask(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "agent-result.json") @@ -497,9 +522,8 @@ func TestSanitizeJSONStructure_CleanKeyWinsSanitizedCollision(t *testing.T) { "ghp_FAKEtesttoken000000000000000000000000": "secretkeyval", sanitized: "plainval", } - input["ghp_FAKEtesttoken000000000000000000000000"] = "secretkeyval" for range 20 { - got, findings := sanitizeJSONStructure(input, pipeline) + got, findings := security.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") @@ -527,6 +551,8 @@ func TestScanOutputFiles_CleanJSON(t *testing.T) { func TestScanOutputFiles_NumericRuntimeSecretRedacted(t *testing.T) { const secretNum = "123456789012" + security.ResetRuntimeSecretsForTest() + t.Cleanup(security.ResetRuntimeSecretsForTest) require.True(t, security.RegisterRuntimeSecret(secretNum)) dir := t.TempDir() @@ -572,7 +598,7 @@ func TestHasDuplicateJSONKeys(t *testing.T) { } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.want, hasDuplicateJSONKeys([]byte(tc.json))) + assert.Equal(t, tc.want, security.HasDuplicateJSONKeys([]byte(tc.json))) }) } } diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go new file mode 100644 index 0000000000..ad609bbfdc --- /dev/null +++ b/internal/security/jsonsanitize.go @@ -0,0 +1,608 @@ +package security + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "regexp" + "sort" + "strconv" +) + +// JSON output that cannot be redacted without corrupting its structure is +// replaced with one of these valid JSON markers so downstream parsers (jq, the +// retro and eval tooling) keep working while no secret reaches the artifact. +const ( + failClosedInvalidJSON = `{"error":"output removed because redaction would invalidate JSON"}` + failClosedCrossRecordJSON = `{"error":"output removed because output contained a cross-record secret"}` +) + +// sensitiveJSONKeyRe matches object keys whose values are masked even when the +// value itself does not match a secret pattern. +var sensitiveJSONKeyRe = regexp.MustCompile(`(?i)(?:key|token|secret|password|credential|auth)`) + +// redactedJSONKey replaces an object key that sanitization removed entirely +// (a key made only of bidi overrides or other invisible characters, for +// example). Such a key must never be restored as-is. +const redactedJSONKey = "redacted" + +// SanitizeJSONDocument structurally sanitizes a single JSON document so that +// redaction never changes its syntax. It returns the bytes to write and the +// findings that justified a rewrite; no findings means the document is clean +// and the caller must leave it untouched. A document that is not valid JSON is +// returned unchanged with no findings so the caller can fall back to a text +// scan. +func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { + trimmed := bytes.TrimSpace(doc) + if len(trimmed) == 0 || !json.Valid(trimmed) { + return doc, nil, nil + } + if HasDuplicateJSONKeys(trimmed) { + return sanitizeDuplicateKeyDocument(trimmed, doc, p) + } + + dec := json.NewDecoder(bytes.NewReader(trimmed)) + dec.UseNumber() + var value any + if err := dec.Decode(&value); err != nil { + // json.Valid accepted the text, so this is a decoder limit rather than + // a syntax error. Keep the bytes and let the caller text-scan it. + return doc, nil, nil + } + var trailing any + if err := dec.Decode(&trailing); !errors.Is(err, io.EOF) { + return doc, nil, nil + } + + sanitized, findings := SanitizeJSONStructure(value, p) + multiline := bytes.Contains(bytes.TrimRight(doc, "\r\n"), []byte("\n")) + encoded, err := encodeJSONDocument(sanitized, multiline) + if err != nil { + return nil, findings, err + } + if len(findings) == 0 { + // A secret can appear only once the decoded leaves are re-serialized, + // for example a runtime secret that spans two adjacent values. + out, backstop := backstopSerializedJSON(encoded, doc, p) + return preserveTrailingNewline(out, doc), backstop, nil + } + out, backstop := backstopSerializedJSON(encoded, encoded, p) + return preserveTrailingNewline(out, doc), append(findings, backstop...), nil +} + +// sanitizeDuplicateKeyDocument sanitizes a document that contains duplicate +// object keys. Decoding it into a map would drop the earlier occurrences, so +// every key and value is scanned through a token-preserving walk instead. +func sanitizeDuplicateKeyDocument(trimmed, doc []byte, p *Pipeline) ([]byte, []Finding, error) { + rebuilt, findings, err := rewriteJSONTokens(trimmed, p) + if err != nil { + return nil, nil, err + } + if len(findings) == 0 { + // Nothing in the decoded leaves matched, so scan the raw text for + // patterns that only exist in the serialized form, such as a JSON + // field whose value is not otherwise recognizable. + res := p.Scan(string(trimmed)) + if len(res.Findings) == 0 { + return doc, nil, nil + } + if res.Sanitized == "" || !json.Valid([]byte(res.Sanitized)) { + return preserveTrailingNewline([]byte(failClosedInvalidJSON), doc), res.Findings, nil + } + return preserveTrailingNewline([]byte(res.Sanitized), doc), res.Findings, nil + } + out, backstop := backstopSerializedJSON(rebuilt, rebuilt, p) + return preserveTrailingNewline(out, doc), append(findings, backstop...), nil +} + +// preserveTrailingNewline drops the newline json.Encoder always appends and +// restores the document's own trailing newline, so a rewrite never changes the +// file's line framing. +func preserveTrailingNewline(encoded, doc []byte) []byte { + encoded = bytes.TrimRight(encoded, "\n") + switch { + case bytes.HasSuffix(doc, []byte("\r\n")): + return append(encoded, '\r', '\n') + case bytes.HasSuffix(doc, []byte("\n")): + return append(encoded, '\n') + default: + return encoded + } +} + +// backstopSerializedJSON scans serialized JSON for secrets that only become +// visible once the parsed form is written back out. Such a match no longer +// maps to a single leaf, so it is applied only when the redacted text is still +// valid JSON; otherwise the document fails closed with a valid marker. +// clean is returned unchanged when the scan finds nothing. +func backstopSerializedJSON(serialized, clean []byte, p *Pipeline) ([]byte, []Finding) { + res := p.Scan(string(serialized)) + if len(res.Findings) == 0 { + return clean, nil + } + for _, finding := range res.Findings { + // A private-key block spanning values cannot be masked in place + // without breaking the surrounding JSON. + if finding.Name == "private_key" { + return []byte(failClosedInvalidJSON), res.Findings + } + } + if res.Sanitized == "" || !json.Valid([]byte(res.Sanitized)) { + return []byte(failClosedInvalidJSON), res.Findings + } + return []byte(res.Sanitized), res.Findings +} + +// SanitizeJSONLines sanitizes newline-delimited JSON one record at a time, +// preserving the record framing so every line stays independently parseable. +// A secret that spans a record boundary cannot be redacted without rewriting +// that framing, so the records it covers are replaced with valid fail-closed +// markers and every other record is left as sanitized. +func SanitizeJSONLines(content []byte, p *Pipeline) ([]byte, []Finding, error) { + var ( + out bytes.Buffer + findings []Finding + spans []recordSpan + ) + for len(content) > 0 { + line := content + newline := bytes.IndexByte(content, '\n') + hasNewline := newline >= 0 + if hasNewline { + line = content[:newline] + content = content[newline+1:] + } else { + content = nil + } + // Keep CRLF framing byte-for-byte for records that are not rewritten. + carriageReturn := len(line) > 0 && line[len(line)-1] == '\r' + if carriageReturn { + line = line[:len(line)-1] + } + trimmed := bytes.TrimSpace(line) + start := out.Len() + switch { + case len(trimmed) == 0: + out.Write(line) + case json.Valid(trimmed): + record, recordFindings, err := SanitizeJSONDocument(trimmed, p) + if err != nil { + return nil, findings, fmt.Errorf("could not sanitize JSONL record: %w", err) + } + findings = append(findings, recordFindings...) + if len(recordFindings) > 0 { + out.Write(record) + } else { + out.Write(line) + } + spans = append(spans, recordSpan{start: start, end: out.Len()}) + default: + res := p.Scan(string(line)) + if len(res.Findings) > 0 { + findings = append(findings, res.Findings...) + out.WriteString(res.Sanitized) + } else { + out.Write(line) + } + spans = append(spans, recordSpan{start: start, end: out.Len()}) + } + if carriageReturn { + out.WriteByte('\r') + } + if hasNewline { + out.WriteByte('\n') + } + } + + rebuilt := out.Bytes() + stream := p.Scan(string(rebuilt)) + if len(stream.Findings) == 0 { + return rebuilt, findings, nil + } + // Every finding a single record could account for was handled above, so + // what remains spans a record boundary. + findings = append(findings, stream.Findings...) + return failClosedRecordSpans(rebuilt, spans, stream), findings, nil +} + +// recordSpan is the byte range of one non-empty JSONL record in the rebuilt +// stream, excluding its trailing newline. +type recordSpan struct { + start, end int +} + +// failClosedRecordSpans replaces every record that intersects the region the +// whole-stream scan rewrote with a valid fail-closed marker. Records outside +// that region are copied through untouched, so a single cross-record match +// never discards unrelated records. +func failClosedRecordSpans(stream []byte, spans []recordSpan, scan ScanResult) []byte { + sanitized := []byte(scan.Sanitized) + // Only reuse the redacted stream when redaction left the same number of + // independently parseable records. A match that consumed the JSON framing + // between two records would otherwise silently drop them. + if len(sanitized) > 0 && validJSONLines(sanitized, len(spans)) { + return sanitized + } + start, end := changedRegion(stream, sanitized) + if start >= end { + // The scan reported a finding but nothing in the bytes changed, so it + // cannot be localized: fail closed for every record. + start, end = 0, len(stream) + } + var out bytes.Buffer + cursor := 0 + for _, span := range spans { + if span.end <= start || span.start >= end { + continue + } + out.Write(stream[cursor:span.start]) + out.WriteString(failClosedCrossRecordJSON) + cursor = span.end + } + out.Write(stream[cursor:]) + return out.Bytes() +} + +// changedRegion returns the half-open byte range that differs between a and b. +// It is approximate for length-changing edits, which is enough to find the +// records a cross-record match covers. +func changedRegion(a, b []byte) (int, int) { + limit := min(len(a), len(b)) + start := 0 + for start < limit && a[start] == b[start] { + start++ + } + end := 0 + for end < limit-start && a[len(a)-1-end] == b[len(b)-1-end] { + end++ + } + return start, len(a) - end +} + +// validJSONLines reports whether data holds exactly want non-empty lines, each +// valid JSON. +func validJSONLines(data []byte, want int) bool { + count := 0 + for _, line := range bytes.Split(data, []byte("\n")) { + trimmed := bytes.TrimSpace(line) + if len(trimmed) == 0 { + continue + } + if !json.Valid(trimmed) { + return false + } + count++ + } + return count == want +} + +// rewriteJSONTokens walks every token in doc, sanitizes each object key and +// scalar value, and renders a valid JSON document. Unlike map decoding it +// keeps duplicate keys and every occurrence, so a secret in an earlier, +// overwritten value is still found and redacted. +func rewriteJSONTokens(doc []byte, p *Pipeline) ([]byte, []Finding, error) { + dec := json.NewDecoder(bytes.NewReader(doc)) + dec.UseNumber() + var ( + buf bytes.Buffer + findings []Finding + ) + if err := writeSanitizedJSONValue(dec, &buf, p, &findings, ""); err != nil { + return nil, nil, fmt.Errorf("could not tokenize JSON: %w", err) + } + if _, err := dec.Token(); !errors.Is(err, io.EOF) { + return nil, nil, fmt.Errorf("unexpected trailing JSON content") + } + return buf.Bytes(), findings, nil +} + +// writeSanitizedJSONValue writes one JSON value to buf, sanitizing object keys +// and scalar leaves as it goes. memberKey is the enclosing object key when the +// value is an object member, so sensitive-key masking still applies; it is +// empty for array elements and the top-level value. +func writeSanitizedJSONValue(dec *json.Decoder, buf *bytes.Buffer, p *Pipeline, findings *[]Finding, memberKey string) error { + tok, err := dec.Token() + if err != nil { + return err + } + switch t := tok.(type) { + case json.Delim: + return writeSanitizedJSONContainer(dec, buf, p, findings, t) + case string: + sanitized, stringFindings := sanitizeJSONString(t, memberKey, p) + *findings = append(*findings, stringFindings...) + return writeJSONString(buf, sanitized) + case json.Number: + literal := t.String() + res := p.Scan(literal) + if len(res.Findings) == 0 { + buf.WriteString(literal) + return nil + } + *findings = append(*findings, res.Findings...) + // A redacted number is no longer a number literal, so write the + // replacement as a JSON string to keep the document valid. + return writeJSONString(buf, res.Sanitized) + case bool: + buf.WriteString(strconv.FormatBool(t)) + return nil + case nil: + buf.WriteString("null") + return nil + default: + return fmt.Errorf("unexpected JSON token %T", tok) + } +} + +// writeSanitizedJSONContainer writes the members of an object or array, +// preserving member order and duplicate keys. +func writeSanitizedJSONContainer(dec *json.Decoder, buf *bytes.Buffer, p *Pipeline, findings *[]Finding, delim json.Delim) error { + switch delim { + case '{': + buf.WriteByte('{') + first := true + for dec.More() { + keyTok, err := dec.Token() + if err != nil { + return err + } + key, ok := keyTok.(string) + if !ok { + return fmt.Errorf("JSON object key is %T, want string", keyTok) + } + sanitizedKey, keyFindings := sanitizeJSONKey(key, p) + *findings = append(*findings, keyFindings...) + if !first { + buf.WriteByte(',') + } + if err := writeJSONString(buf, sanitizedKey); err != nil { + return err + } + buf.WriteByte(':') + if err := writeSanitizedJSONValue(dec, buf, p, findings, sanitizedKey); err != nil { + return err + } + first = false + } + if _, err := dec.Token(); err != nil { // consume '}' + return err + } + buf.WriteByte('}') + return nil + case '[': + buf.WriteByte('[') + first := true + for dec.More() { + if !first { + buf.WriteByte(',') + } + if err := writeSanitizedJSONValue(dec, buf, p, findings, ""); err != nil { + return err + } + first = false + } + if _, err := dec.Token(); err != nil { // consume ']' + return err + } + buf.WriteByte(']') + return nil + default: + return fmt.Errorf("unexpected JSON delimiter %q", delim.String()) + } +} + +// writeJSONString appends s to buf as a JSON string literal without escaping +// HTML characters, so legitimate markup survives sanitization. +func writeJSONString(buf *bytes.Buffer, s string) error { + var encoded bytes.Buffer + enc := json.NewEncoder(&encoded) + enc.SetEscapeHTML(false) + if err := enc.Encode(s); err != nil { + return err + } + buf.Write(bytes.TrimSuffix(encoded.Bytes(), []byte("\n"))) + return nil +} + +// encodeJSONDocument renders v as JSON, indented when the original document was +// multi-line so the rewritten file keeps its shape. +func encodeJSONDocument(v any, multiline bool) ([]byte, error) { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if multiline { + enc.SetIndent("", " ") + } + if err := enc.Encode(v); err != nil { + return nil, fmt.Errorf("could not encode sanitized JSON: %w", err) + } + return buf.Bytes(), nil +} + +// SanitizeJSONStructure recursively visits all keys and scalar values in parsed +// JSON data, scans each one with the pipeline, and returns the sanitized value +// together with every finding. The result is always structurally valid JSON. +func SanitizeJSONStructure(v any, p *Pipeline) (any, []Finding) { + switch val := v.(type) { + case string: + res := p.Scan(val) + if len(res.Findings) > 0 { + // An empty sanitized value means everything was removed; that is a + // valid replacement for a string leaf. + return res.Sanitized, res.Findings + } + return val, nil + case map[string]any: + newMap := make(map[string]any, len(val)) + keys := make([]string, 0, len(val)) + for k := range val { + keys = append(keys, k) + } + sort.Strings(keys) + // Reserve clean original names before assigning sanitized names so a + // secret key can never steal a legitimate key's name/value slot. + for _, k := range keys { + if keyRes := p.Scan(k); len(keyRes.Findings) == 0 { + newMap[k] = nil + } + } + var findings []Finding + for _, k := range keys { + item := val[k] + keyRes := p.Scan(k) + keyNeedsSanitization := len(keyRes.Findings) > 0 + sanitizedKey := k + if keyNeedsSanitization { + findings = append(findings, keyRes.Findings...) + sanitizedKey = keyRes.Sanitized + if sanitizedKey == "" { + // The whole key was removable characters; never restore it. + sanitizedKey = redactedJSONKey + } + } + targetKey := sanitizedKey + if !keyNeedsSanitization { + targetKey = k + } + if _, exists := newMap[targetKey]; exists && keyNeedsSanitization { + for i := 1; ; i++ { + cand := fmt.Sprintf("%s_%d", sanitizedKey, i) + if _, exists := newMap[cand]; !exists { + targetKey = cand + break + } + } + } + if strVal, ok := item.(string); ok { + out, stringFindings := sanitizeJSONString(strVal, sanitizedKey, p) + findings = append(findings, stringFindings...) + newMap[targetKey] = out + continue + } + newVal, f := SanitizeJSONStructure(item, p) + findings = append(findings, f...) + newMap[targetKey] = newVal + } + return newMap, findings + case []any: + newSlice := make([]any, len(val)) + var findings []Finding + for i, item := range val { + newVal, f := SanitizeJSONStructure(item, p) + findings = append(findings, f...) + newSlice[i] = newVal + } + return newSlice, findings + case json.Number: + res := p.Scan(val.String()) + if len(res.Findings) > 0 { + if res.Sanitized == "" { + return "", res.Findings + } + return res.Sanitized, res.Findings + } + return val, nil + default: + return val, nil + } +} + +// sanitizeJSONKey sanitizes one object key. A key whose sanitized value is +// empty was removed entirely, so it is replaced with a placeholder rather than +// kept as-is. +func sanitizeJSONKey(key string, p *Pipeline) (string, []Finding) { + res := p.Scan(key) + if len(res.Findings) == 0 { + return key, nil + } + sanitized := res.Sanitized + if sanitized == "" { + sanitized = redactedJSONKey + } + return sanitized, res.Findings +} + +// sanitizeJSONString sanitizes one string leaf. memberKey is the enclosing +// object key, used to mask values whose key name marks them as sensitive even +// when the value itself matches no secret pattern. +func sanitizeJSONString(value, memberKey string, p *Pipeline) (string, []Finding) { + res := p.Scan(value) + out := value + var findings []Finding + if len(res.Findings) > 0 { + findings = append(findings, res.Findings...) + out = res.Sanitized + } + if memberKey != "" && sensitiveJSONKeyRe.MatchString(memberKey) && len(out) >= 8 && !isAlreadyMasked(out) { + masked := Mask(out) + findings = append(findings, Finding{ + Scanner: "secret_redactor", + Name: "json_field", + Severity: "high", + Detail: fmt.Sprintf("Redacted json_field (%d chars) -> %s", len(out), masked), + }) + out = masked + } + return out, findings +} + +// HasDuplicateJSONKeys parses content token by token and reports whether any +// JSON object within the payload contains duplicate keys. +func HasDuplicateJSONKeys(content []byte) bool { + dec := json.NewDecoder(bytes.NewReader(content)) + dec.UseNumber() + var stack []*jsonContainerFrame + for { + tok, err := dec.Token() + if err != nil { + return false + } + switch t := tok.(type) { + case json.Delim: + switch t { + case '{': + stack = append(stack, &jsonContainerFrame{ + isObject: true, + expectingKey: true, + keys: make(map[string]bool), + }) + case '[': + stack = append(stack, &jsonContainerFrame{isObject: false}) + case '}', ']': + if len(stack) > 0 { + stack = stack[:len(stack)-1] + } + if len(stack) > 0 && stack[len(stack)-1].isObject { + stack[len(stack)-1].expectingKey = true + } + } + case string: + if len(stack) > 0 && stack[len(stack)-1].isObject { + top := stack[len(stack)-1] + if top.expectingKey { + if top.keys[t] { + return true + } + top.keys[t] = true + top.expectingKey = false + } else { + top.expectingKey = true + } + } + default: + if len(stack) > 0 && stack[len(stack)-1].isObject { + stack[len(stack)-1].expectingKey = true + } + } + } +} + +// jsonContainerFrame tracks one open object or array while scanning for +// duplicate keys. +type jsonContainerFrame struct { + isObject bool + expectingKey bool + keys map[string]bool +} diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go new file mode 100644 index 0000000000..cc97269f58 --- /dev/null +++ b/internal/security/jsonsanitize_test.go @@ -0,0 +1,272 @@ +package security + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestSanitizeJSONDocument_DuplicateKeyEarlierOccurrenceRedacted pins that a +// secret in an earlier, overwritten duplicate-key occurrence is still found. +// Map decoding drops that occurrence, so only a token-preserving walk sees it. +func TestSanitizeJSONDocument_DuplicateKeyEarlierOccurrenceRedacted(t *testing.T) { + p := OutputPipeline() + // \u0067 decodes to "g"; the raw text never contains "ghp_". + escapedSecret := `\u0067hp_FAKEtesttoken000000000000000000000000` + doc := []byte(`{"note":"` + escapedSecret + `","note":"clean"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized duplicate-key JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + assert.NotContains(t, string(out), `\u0067hp_`) + assert.Contains(t, string(out), `"note":"clean"`, "the surviving duplicate value must be preserved") +} + +// TestSanitizeJSONLines_CrossRecordRuntimeSecretFailsClosed pins that a +// runtime secret spanning two individually valid records is not discarded. +func TestSanitizeJSONLines_CrossRecordRuntimeSecretFailsClosed(t *testing.T) { + ResetRuntimeSecretsForTest() + t.Cleanup(ResetRuntimeSecretsForTest) + const secret = `one"}` + "\n" + `{"key` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + content := []byte("{\"key_one\":\"one\"}\n{\"key_two\":\"two\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), secret, "the cross-record secret must not survive") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 2, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONDocument_BackstopRedactsSecondRuntimeSecret pins that a +// runtime secret exposed only by serializing the parsed document is still +// redacted when another runtime secret was already found in a leaf. +func TestSanitizeJSONDocument_BackstopRedactsSecondRuntimeSecret(t *testing.T) { + ResetRuntimeSecretsForTest() + t.Cleanup(ResetRuntimeSecretsForTest) + const leafSecret = "leafonlysecretvalue" + const serializedSecret = `","field2":"` + require.True(t, RegisterRuntimeSecret(leafSecret)) + require.True(t, RegisterRuntimeSecret(serializedSecret)) + + p := OutputPipeline() + doc := []byte(`{"field1":"leafonlysecretvalue","field2":"bar"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), leafSecret) + assert.NotContains(t, string(out), serializedSecret) +} + +// TestSanitizeJSONStructure_KeyRemovedEntirelyIsReplaced pins that a JSON key +// made only of removable characters never survives sanitization. +func TestSanitizeJSONStructure_KeyRemovedEntirelyIsReplaced(t *testing.T) { + p := OutputPipeline() + for name, key := range map[string]string{ + "null byte": "\x00", + "bidi override": "\u202e", + } { + t.Run(name, func(t *testing.T) { + got, findings := SanitizeJSONStructure(map[string]any{key: "value"}, p) + require.NotEmpty(t, findings) + result := got.(map[string]any) + require.Len(t, result, 1) + for gotKey := range result { + assert.NotContains(t, gotKey, key) + assert.Equal(t, redactedJSONKey, gotKey) + } + assert.Equal(t, "value", result[redactedJSONKey]) + }) + } +} + +// TestSanitizeJSONLines_SingleRecordPEMKeepsCleanRecords pins that a private +// key confined to one record is redacted in place instead of replacing every +// record in the file. +func TestSanitizeJSONLines_SingleRecordPEMKeepsCleanRecords(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + content := []byte( + "{\"event\":\"clean-before\"}\n" + + "{\"tool\":\"read\",\"text\":\"" + begin + "\\nMIIEpAIBAAKCAQEA0123456789abcdef\\n" + end + "\"}\n" + + "{\"event\":\"clean-after\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + assert.Equal(t, `{"event":"clean-before"}`, lines[0], "clean records must be untouched") + assert.Equal(t, `{"event":"clean-after"}`, lines[2], "clean records must be untouched") + assert.True(t, json.Valid([]byte(lines[1]))) + assert.NotContains(t, lines[1], "BEGIN RSA") + assert.NotContains(t, lines[1], "MIIEpAIBAAKCAQEA") +} + +// TestSanitizeJSONDocument_AlreadyMaskedValueNotRemasked pins that the +// serialized backstop leaves an existing mask placeholder intact. +func TestSanitizeJSONDocument_AlreadyMaskedValueNotRemasked(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"body":"Guard against null values with token_usage = metrics.get(\"token_usage\") or {}"}`) + + first, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.Len(t, findings, 1, "one secret must produce one finding") + assert.Contains(t, string(first), "metr...", "the informative prefix must be retained") + + second, findings, err := SanitizeJSONDocument(first, p) + require.NoError(t, err) + assert.Empty(t, findings, "rescanning a sanitized document must be idempotent") + assert.Equal(t, first, second) +} + +// TestSanitizeJSONDocument_DuplicateKeyNestedContainers covers the +// token-preserving walk across nested objects, arrays, every scalar type, and +// an escaped duplicate key whose value is a container. +func TestSanitizeJSONDocument_DuplicateKeyNestedContainers(t *testing.T) { + p := OutputPipeline() + escapedSecret := `\u0067hp_FAKEtesttoken000000000000000000000000` + doc := []byte(`{"outer":[{"id":1,"id":2,"opts":{"flag":true,"none":null,"ratio":1.5}},` + + `{"token":"` + escapedSecret + `","token":["clean"]}],"tail":false}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + + var decoded any + require.NoError(t, json.Unmarshal(out, &decoded)) + outer := decoded.(map[string]any)["outer"].([]any) + second := outer[1].(map[string]any) + // The duplicate-key walk keeps the later occurrence, which is the array. + assert.Equal(t, []any{"clean"}, second["token"]) + assert.Equal(t, false, decoded.(map[string]any)["tail"]) +} + +// TestSanitizeJSONStructure_ScalarAndContainerCoverage exercises every scalar +// branch and nested collection of the structural walker. +func TestSanitizeJSONStructure_ScalarAndContainerCoverage(t *testing.T) { + ResetRuntimeSecretsForTest() + t.Cleanup(ResetRuntimeSecretsForTest) + const numericSecret = "123456789012" + require.True(t, RegisterRuntimeSecret(numericSecret)) + + p := OutputPipeline() + input := map[string]any{ + "list": []any{"plain", json.Number("42"), json.Number(numericSecret), true, nil}, + "nested": map[string]any{"deep": []any{map[string]any{"value": "plain"}}}, + "counter": json.Number("7"), + } + got, findings := SanitizeJSONStructure(input, p) + require.NotEmpty(t, findings) + + encoded, err := encodeJSONDocument(got, false) + require.NoError(t, err) + assert.True(t, json.Valid(encoded)) + assert.NotContains(t, string(encoded), numericSecret) + assert.Contains(t, string(encoded), "42", "clean numbers must keep their precision") + assert.Contains(t, string(encoded), `"counter":7`) +} + +// TestSanitizeJSONDocument_LeavesUnsupportedInputAlone pins the fallback +// contract for documents the structural path cannot handle. +func TestSanitizeJSONDocument_LeavesUnsupportedInputAlone(t *testing.T) { + p := OutputPipeline() + for name, doc := range map[string]string{ + "not json": `{"unterminated": `, + "plain text": "just prose", + "empty": "", + "trailing value": `{"a":1}{"b":2}`, + } { + t.Run(name, func(t *testing.T) { + out, findings, err := SanitizeJSONDocument([]byte(doc), p) + require.NoError(t, err) + assert.Empty(t, findings) + assert.Equal(t, doc, string(out), "an unsupported document must be returned unchanged") + }) + } +} + +// TestSanitizeJSONLines_NonJSONRecordsRedacted pins the text fallback for +// records that are not valid JSON. +func TestSanitizeJSONLines_NonJSONRecordsRedacted(t *testing.T) { + p := OutputPipeline() + content := []byte("plain Token: ghp_FAKEtesttoken000000000000000000000000\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + assert.Equal(t, 1, strings.Count(string(out), "\n"), "line framing must be preserved") +} + +// TestSanitizeJSONLines_PreservesCRLFFraming pins that CRLF records keep their +// carriage returns across a rewrite. +func TestSanitizeJSONLines_PreservesCRLFFraming(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"event\":\"clean\"}\r\n{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\r\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.Equal(t, 2, strings.Count(string(out), "\r\n"), "CRLF framing must be preserved") + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONDocument_CleanDuplicateKeyDocumentUnchanged pins that a +// duplicate-key document with nothing to redact is left byte-for-byte intact. +func TestSanitizeJSONDocument_CleanDuplicateKeyDocumentUnchanged(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"a": 1, "a": 2}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + assert.Empty(t, findings) + assert.Equal(t, string(doc), string(out), "a clean duplicate-key document must not be reformatted") +} + +// TestSanitizeJSONDocument_DuplicateKeyRawTextFinding covers a duplicate-key +// document whose only match exists in the serialized form: the leaves are +// individually clean, so the raw-text scan finds and redacts it. +func TestSanitizeJSONDocument_DuplicateKeyRawTextFinding(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"password": "secretvalue123", "dup": 1, "dup": 2}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "secretvalue123") +} + +// TestSanitizeJSONDocument_DuplicateKeyWithSecretKey covers a duplicate-key +// document whose keys themselves carry a secret. +func TestSanitizeJSONDocument_DuplicateKeyWithSecretKey(t *testing.T) { + p := OutputPipeline() + const secret = "ghp_FAKEtesttoken000000000000000000000000" + doc := []byte(`{"` + secret + `": 1, "` + secret + `": 2}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), secret) +} diff --git a/internal/security/redactor.go b/internal/security/redactor.go index 42ef309553..15e3da021a 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -207,21 +207,18 @@ func (s *SecretRedactor) Scan(text string) ScanResult { if len(secret) == 0 { continue } + // A captured value that is already a mask placeholder is the + // product of an earlier redaction pass, not a new leak. Re-masking + // it would discard the informative prefix for no security gain, + // and it lets the serialized-JSON backstop run on every document + // without degrading prior redactions. + if isAlreadyMasked(secret) { + continue + } masked := Mask(secret) if originalLen < minLen { continue } - if p.name != "json_field" && end < len(current) && (current[end] == '"' || current[end] == '\'') { - numBackslashes := 0 - for k := len(secret) - 1; k >= 0 && secret[k] == '\\'; k-- { - numBackslashes++ - } - if numBackslashes%2 == 1 { - // The quote is escaped in the source. Keep the escaping - // backslash outside the redacted span. - masked += "\\" - } - } result.Findings = append(result.Findings, Finding{ Scanner: "secret_redactor", Name: p.name, @@ -254,6 +251,12 @@ func Mask(value string) string { return prefix + "..." } +// isAlreadyMasked reports whether value is already a redaction placeholder +// produced by Mask. +func isAlreadyMasked(value string) bool { + return value == "***" || len(value) == 7 && strings.HasSuffix(value, "...") +} + func defaultPrefixPatterns() []secretPattern { patterns := []struct { name string From de2f0950b5c70d95326edae58da68440681e7824 Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 19 Nov 2026 12:16:15 -0500 Subject: [PATCH 17/51] fix(security): fail closed on JSON secrets that span framing The JSON output sanitizer scanned either the re-encoded document or the original bytes, but never both with the original member order. Decoding into a map re-encodes keys in sorted order, so a private-key block split across members (a "z_begin", "m_body", "a_end" shape) matched in the original text yet disappeared from the re-encoded form. With no leaf findings the original bytes were then returned untouched, leaving the key material in the artifact. Three related defects came from the same split: - The token walk used for duplicate-key documents wrote sanitized keys without collision handling, so a masked key could take over an existing clean member's name and a downstream decoder kept only one value. - JSONL stream redaction localized cross-record matches to a single first-to-last region, discarding clean records between two disjoint matches. - Unit tests for the security helpers lived in package cli, forcing the map-path helpers to stay exported. SanitizeJSONDocument now always uses the token-preserving walk, which keeps member order and duplicate keys, and redactJSONOutput scans the bytes that are actually written. A match that only exists across JSON framing therefore stays visible and fails closed with a valid marker instead of being written out. Member names are resolved after the whole object is read: clean names are reserved first, sanitized collisions become _, and repeats of the same original duplicate key keep one name. Cross-record JSONL redaction is decided per record, so only the records a match covers are replaced. The map path (SanitizeJSONStructure, HasDuplicateJSONKeys, sanitizeDuplicateKeyDocument, encodeJSONDocument) is removed; its tests moved to internal/security/jsonsanitize_test.go and now exercise documents. Regression tests in internal/security/jsonsanitize_test.go: - TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersFailsClosed - TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed - TestSanitizeJSONDocument_CrossMemberPrivateKeyWithLeafSecretFailsClosed - TestSanitizeJSONDocument_DuplicateKeySanitizedKeyCollision - TestSanitizeJSONLines_DisjointCrossRecordMatchesKeepCleanRecord Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 22 +- internal/cli/scan_output_telemetry_test.go | 42 -- internal/security/jsonsanitize.go | 401 ++++++-------------- internal/security/jsonsanitize_test.go | 316 +++++++++++++-- 4 files changed, 412 insertions(+), 369 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 8ec41547bb..be5f7b0bc5 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -617,18 +617,22 @@ origins and warnings are documented in `scanOutputFiles` runs the output pipeline (Unicode normalization, then secret redaction) over every file under `output/` except the skips above and `security/findings.jsonl`. Valid JSON is sanitized structurally so redaction -never changes its syntax: object keys and scalar leaves are scanned -individually, and a document with duplicate keys goes through a -token-preserving walk so every decoded occurrence is scanned, including an -earlier value that map decoding would drop. `.jsonl`/`.ndjson` files are -sanitized one record at a time to preserve the record framing; a secret that -spans records cannot be redacted without rewriting that framing, so only the -records it covers are replaced. +never changes its syntax: every object key and scalar leaf is scanned +individually through a token-preserving walk that keeps member order and +duplicate keys, so an earlier value that map decoding would drop is still +scanned, and a secret spanning JSON framing stays visible in the rewritten +bytes. A sanitized key that would collide with a different member is +disambiguated (`_`). The bytes actually written are scanned as well, so +a secret that only exists in the serialized form is still caught. +`.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the +record framing; a secret that spans records cannot be redacted without +rewriting that framing, so only the records it covers are replaced. Some content cannot be redacted in place. A JSON document or JSONL record is replaced with a valid fail-closed marker instead — never with corrupted -syntax — when a private-key block or a cross-record match spans JSON -framing, or when a text redaction would leave invalid JSON. Markers look +syntax — when a secret spans JSON framing (such as a private-key block split +across members), when a match spans record boundaries, or when a text +redaction would leave the document invalid. Markers look like `{"error":"output removed because …"}` and are logged as findings in `security/findings.jsonl`. diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index e25c839fbb..3028be1037 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -515,23 +515,6 @@ 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", - } - for range 20 { - got, findings := security.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) { @@ -577,28 +560,3 @@ func TestScanOutputFiles_NumericRuntimeSecretRedacted(t *testing.T) { require.Len(t, lines, 1) assert.True(t, json.Valid([]byte(lines[0]))) } - -func TestHasDuplicateJSONKeys(t *testing.T) { - tests := []struct { - name string - json string - want bool - }{ - {"no duplicates", `{"a": 1, "b": 2}`, false}, - {"duplicate top-level", `{"a": 1, "a": 2}`, true}, - {"nested duplicate", `{"parent": {"x": 1, "x": 2}}`, true}, - {"nested no duplicate", `{"p1": {"x": 1}, "p2": {"x": 1}}`, false}, - {"array with duplicate in object", `[{"k": 1, "k": 2}]`, true}, - {"array with separate objects", `[{"k": 1}, {"k": 2}]`, false}, - {"value matches key name", `{"a": "a", "b": "a"}`, false}, - {"array values inside object", `{"a": [1, 2], "b": 3}`, false}, - {"out-of-range number before duplicate keys", `{"large": 1e1000, "dup": 1, "dup": 2}`, true}, - {"out-of-range number without duplicates", `{"large": 1e1000, "no_dup": 1}`, false}, - {"malformed json", `{"a": `, false}, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.want, security.HasDuplicateJSONKeys([]byte(tc.json))) - }) - } -} diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index ad609bbfdc..f2c35b173d 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -7,7 +7,6 @@ import ( "fmt" "io" "regexp" - "sort" "strconv" ) @@ -34,67 +33,32 @@ const redactedJSONKey = "redacted" // and the caller must leave it untouched. A document that is not valid JSON is // returned unchanged with no findings so the caller can fall back to a text // scan. +// +// The document is rewritten by a token-preserving walk rather than decoded into +// a map and re-encoded: that keeps member order and duplicate keys, so a +// secret that spans JSON framing is still visible in the rewritten bytes. func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { trimmed := bytes.TrimSpace(doc) if len(trimmed) == 0 || !json.Valid(trimmed) { return doc, nil, nil } - if HasDuplicateJSONKeys(trimmed) { - return sanitizeDuplicateKeyDocument(trimmed, doc, p) - } - - dec := json.NewDecoder(bytes.NewReader(trimmed)) - dec.UseNumber() - var value any - if err := dec.Decode(&value); err != nil { - // json.Valid accepted the text, so this is a decoder limit rather than - // a syntax error. Keep the bytes and let the caller text-scan it. - return doc, nil, nil - } - var trailing any - if err := dec.Decode(&trailing); !errors.Is(err, io.EOF) { - return doc, nil, nil - } - - sanitized, findings := SanitizeJSONStructure(value, p) - multiline := bytes.Contains(bytes.TrimRight(doc, "\r\n"), []byte("\n")) - encoded, err := encodeJSONDocument(sanitized, multiline) - if err != nil { - return nil, findings, err - } - if len(findings) == 0 { - // A secret can appear only once the decoded leaves are re-serialized, - // for example a runtime secret that spans two adjacent values. - out, backstop := backstopSerializedJSON(encoded, doc, p) - return preserveTrailingNewline(out, doc), backstop, nil - } - out, backstop := backstopSerializedJSON(encoded, encoded, p) - return preserveTrailingNewline(out, doc), append(findings, backstop...), nil -} - -// sanitizeDuplicateKeyDocument sanitizes a document that contains duplicate -// object keys. Decoding it into a map would drop the earlier occurrences, so -// every key and value is scanned through a token-preserving walk instead. -func sanitizeDuplicateKeyDocument(trimmed, doc []byte, p *Pipeline) ([]byte, []Finding, error) { rebuilt, findings, err := rewriteJSONTokens(trimmed, p) if err != nil { - return nil, nil, err - } - if len(findings) == 0 { - // Nothing in the decoded leaves matched, so scan the raw text for - // patterns that only exist in the serialized form, such as a JSON - // field whose value is not otherwise recognizable. - res := p.Scan(string(trimmed)) - if len(res.Findings) == 0 { - return doc, nil, nil - } - if res.Sanitized == "" || !json.Valid([]byte(res.Sanitized)) { - return preserveTrailingNewline([]byte(failClosedInvalidJSON), doc), res.Findings, nil - } - return preserveTrailingNewline([]byte(res.Sanitized), doc), res.Findings, nil - } - out, backstop := backstopSerializedJSON(rebuilt, rebuilt, p) - return preserveTrailingNewline(out, doc), append(findings, backstop...), nil + // json.Valid accepted the text and the walk uses the same scanner, so + // this is a decoder limit rather than a syntax error. Return the error + // so the caller fails closed instead of writing unscanned bytes. + return nil, nil, fmt.Errorf("could not sanitize JSON document: %w", err) + } + out := doc + if len(findings) > 0 { + out = rebuilt + } + // Scan the bytes that will actually be written. The walk above already + // scanned every decoded key and leaf, so a match here spans JSON framing + // (for example a PEM block split across members) and cannot be mapped back + // to a single leaf. + sanitizedOut, outputFindings := redactJSONOutput(out, p) + return preserveTrailingNewline(sanitizedOut, doc), append(findings, outputFindings...), nil } // preserveTrailingNewline drops the newline json.Encoder always appends and @@ -112,13 +76,13 @@ func preserveTrailingNewline(encoded, doc []byte) []byte { } } -// backstopSerializedJSON scans serialized JSON for secrets that only become -// visible once the parsed form is written back out. Such a match no longer -// maps to a single leaf, so it is applied only when the redacted text is still -// valid JSON; otherwise the document fails closed with a valid marker. -// clean is returned unchanged when the scan finds nothing. -func backstopSerializedJSON(serialized, clean []byte, p *Pipeline) ([]byte, []Finding) { - res := p.Scan(string(serialized)) +// redactJSONOutput scans the bytes about to be written for secrets that only +// appear in the serialized form. Such a match does not map to a single leaf, so +// it is applied only when the redacted text is still valid JSON; otherwise the +// document fails closed with a valid marker. clean is returned unchanged when +// the scan finds nothing. +func redactJSONOutput(clean []byte, p *Pipeline) ([]byte, []Finding) { + res := p.Scan(string(clean)) if len(res.Findings) == 0 { return clean, nil } @@ -213,30 +177,32 @@ type recordSpan struct { start, end int } -// failClosedRecordSpans replaces every record that intersects the region the -// whole-stream scan rewrote with a valid fail-closed marker. Records outside -// that region are copied through untouched, so a single cross-record match -// never discards unrelated records. +// failClosedRecordSpans replaces the records a whole-stream redaction changed +// with a valid fail-closed marker. Records the redaction did not touch are +// copied through unchanged, so two disjoint cross-record matches never discard +// the clean records between them. +// +// The per-record pass has already handled every match a single record could +// account for, so a remaining match spans a record boundary. Redaction masks +// every occurrence of a match, so a record that still appears byte-for-byte in +// the sanitized stream cannot carry one of the secrets just removed. func failClosedRecordSpans(stream []byte, spans []recordSpan, scan ScanResult) []byte { sanitized := []byte(scan.Sanitized) - // Only reuse the redacted stream when redaction left the same number of - // independently parseable records. A match that consumed the JSON framing - // between two records would otherwise silently drop them. - if len(sanitized) > 0 && validJSONLines(sanitized, len(spans)) { - return sanitized - } - start, end := changedRegion(stream, sanitized) - if start >= end { - // The scan reported a finding but nothing in the bytes changed, so it - // cannot be localized: fail closed for every record. - start, end = 0, len(stream) - } + var out bytes.Buffer cursor := 0 + searchFrom := 0 for _, span := range spans { - if span.end <= start || span.start >= end { + record := stream[span.start:span.end] + if idx := bytes.Index(sanitized[searchFrom:], record); idx >= 0 { + searchFrom += idx + len(record) + out.Write(stream[cursor:span.end]) + cursor = span.end continue } + // The record is not present verbatim, so a match covered part of it (or + // the scan reported a finding without changing bytes, which cannot be + // localized at all). Either way it must not be written as-is. out.Write(stream[cursor:span.start]) out.WriteString(failClosedCrossRecordJSON) cursor = span.end @@ -245,43 +211,11 @@ func failClosedRecordSpans(stream []byte, spans []recordSpan, scan ScanResult) [ return out.Bytes() } -// changedRegion returns the half-open byte range that differs between a and b. -// It is approximate for length-changing edits, which is enough to find the -// records a cross-record match covers. -func changedRegion(a, b []byte) (int, int) { - limit := min(len(a), len(b)) - start := 0 - for start < limit && a[start] == b[start] { - start++ - } - end := 0 - for end < limit-start && a[len(a)-1-end] == b[len(b)-1-end] { - end++ - } - return start, len(a) - end -} - -// validJSONLines reports whether data holds exactly want non-empty lines, each -// valid JSON. -func validJSONLines(data []byte, want int) bool { - count := 0 - for _, line := range bytes.Split(data, []byte("\n")) { - trimmed := bytes.TrimSpace(line) - if len(trimmed) == 0 { - continue - } - if !json.Valid(trimmed) { - return false - } - count++ - } - return count == want -} - // rewriteJSONTokens walks every token in doc, sanitizes each object key and // scalar value, and renders a valid JSON document. Unlike map decoding it -// keeps duplicate keys and every occurrence, so a secret in an earlier, -// overwritten value is still found and redacted. +// keeps member order and duplicate keys, so a secret in an earlier, overwritten +// value is still found, and a secret spanning JSON framing stays visible in the +// rewritten bytes. func rewriteJSONTokens(doc []byte, p *Pipeline) ([]byte, []Finding, error) { dec := json.NewDecoder(bytes.NewReader(doc)) dec.UseNumber() @@ -336,13 +270,21 @@ func writeSanitizedJSONValue(dec *json.Decoder, buf *bytes.Buffer, p *Pipeline, } } +// jsonMember is one object member whose value has been rendered but whose name +// is not final yet. Names are resolved once the whole object has been read so a +// sanitized name can never collide with a clean key that appears later. +type jsonMember struct { + originalKey string + sanitizedKey string + rendered []byte +} + // writeSanitizedJSONContainer writes the members of an object or array, // preserving member order and duplicate keys. func writeSanitizedJSONContainer(dec *json.Decoder, buf *bytes.Buffer, p *Pipeline, findings *[]Finding, delim json.Delim) error { switch delim { case '{': - buf.WriteByte('{') - first := true + var members []jsonMember for dec.More() { keyTok, err := dec.Token() if err != nil { @@ -354,21 +296,31 @@ func writeSanitizedJSONContainer(dec *json.Decoder, buf *bytes.Buffer, p *Pipeli } sanitizedKey, keyFindings := sanitizeJSONKey(key, p) *findings = append(*findings, keyFindings...) - if !first { - buf.WriteByte(',') - } - if err := writeJSONString(buf, sanitizedKey); err != nil { + var rendered bytes.Buffer + if err := writeSanitizedJSONValue(dec, &rendered, p, findings, sanitizedKey); err != nil { return err } - buf.WriteByte(':') - if err := writeSanitizedJSONValue(dec, buf, p, findings, sanitizedKey); err != nil { - return err - } - first = false + members = append(members, jsonMember{ + originalKey: key, + sanitizedKey: sanitizedKey, + rendered: rendered.Bytes(), + }) } if _, err := dec.Token(); err != nil { // consume '}' return err } + assignJSONMemberNames(members) + buf.WriteByte('{') + for i, m := range members { + if i > 0 { + buf.WriteByte(',') + } + if err := writeJSONString(buf, m.sanitizedKey); err != nil { + return err + } + buf.WriteByte(':') + buf.Write(m.rendered) + } buf.WriteByte('}') return nil case '[': @@ -393,6 +345,43 @@ func writeSanitizedJSONContainer(dec *json.Decoder, buf *bytes.Buffer, p *Pipeli } } +// assignJSONMemberNames resolves the member names of one object. Clean keys keep +// their names, and a sanitized name that would collide with a different key is +// disambiguated. Repeats of the same original duplicate key keep sharing one +// name, so intentional duplicate keys survive sanitization. +func assignJSONMemberNames(members []jsonMember) { + claimed := make(map[string]string, len(members)) + for _, m := range members { + if m.sanitizedKey == m.originalKey { + claimed[m.sanitizedKey] = m.originalKey + } + } + renamed := make(map[string]string, len(members)) + for i := range members { + m := &members[i] + if m.sanitizedKey == m.originalKey { + continue + } + if target, ok := renamed[m.originalKey]; ok { + m.sanitizedKey = target + continue + } + target := m.sanitizedKey + if owner, taken := claimed[target]; taken && owner != m.originalKey { + for n := 1; ; n++ { + cand := fmt.Sprintf("%s_%d", m.sanitizedKey, n) + if _, exists := claimed[cand]; !exists { + target = cand + break + } + } + } + renamed[m.originalKey] = target + claimed[target] = m.originalKey + m.sanitizedKey = target + } +} + // writeJSONString appends s to buf as a JSON string literal without escaping // HTML characters, so legitimate markup survives sanitization. func writeJSONString(buf *bytes.Buffer, s string) error { @@ -406,109 +395,6 @@ func writeJSONString(buf *bytes.Buffer, s string) error { return nil } -// encodeJSONDocument renders v as JSON, indented when the original document was -// multi-line so the rewritten file keeps its shape. -func encodeJSONDocument(v any, multiline bool) ([]byte, error) { - var buf bytes.Buffer - enc := json.NewEncoder(&buf) - enc.SetEscapeHTML(false) - if multiline { - enc.SetIndent("", " ") - } - if err := enc.Encode(v); err != nil { - return nil, fmt.Errorf("could not encode sanitized JSON: %w", err) - } - return buf.Bytes(), nil -} - -// SanitizeJSONStructure recursively visits all keys and scalar values in parsed -// JSON data, scans each one with the pipeline, and returns the sanitized value -// together with every finding. The result is always structurally valid JSON. -func SanitizeJSONStructure(v any, p *Pipeline) (any, []Finding) { - switch val := v.(type) { - case string: - res := p.Scan(val) - if len(res.Findings) > 0 { - // An empty sanitized value means everything was removed; that is a - // valid replacement for a string leaf. - return res.Sanitized, res.Findings - } - return val, nil - case map[string]any: - newMap := make(map[string]any, len(val)) - keys := make([]string, 0, len(val)) - for k := range val { - keys = append(keys, k) - } - sort.Strings(keys) - // Reserve clean original names before assigning sanitized names so a - // secret key can never steal a legitimate key's name/value slot. - for _, k := range keys { - if keyRes := p.Scan(k); len(keyRes.Findings) == 0 { - newMap[k] = nil - } - } - var findings []Finding - for _, k := range keys { - item := val[k] - keyRes := p.Scan(k) - keyNeedsSanitization := len(keyRes.Findings) > 0 - sanitizedKey := k - if keyNeedsSanitization { - findings = append(findings, keyRes.Findings...) - sanitizedKey = keyRes.Sanitized - if sanitizedKey == "" { - // The whole key was removable characters; never restore it. - sanitizedKey = redactedJSONKey - } - } - targetKey := sanitizedKey - if !keyNeedsSanitization { - targetKey = k - } - if _, exists := newMap[targetKey]; exists && keyNeedsSanitization { - for i := 1; ; i++ { - cand := fmt.Sprintf("%s_%d", sanitizedKey, i) - if _, exists := newMap[cand]; !exists { - targetKey = cand - break - } - } - } - if strVal, ok := item.(string); ok { - out, stringFindings := sanitizeJSONString(strVal, sanitizedKey, p) - findings = append(findings, stringFindings...) - newMap[targetKey] = out - continue - } - newVal, f := SanitizeJSONStructure(item, p) - findings = append(findings, f...) - newMap[targetKey] = newVal - } - return newMap, findings - case []any: - newSlice := make([]any, len(val)) - var findings []Finding - for i, item := range val { - newVal, f := SanitizeJSONStructure(item, p) - findings = append(findings, f...) - newSlice[i] = newVal - } - return newSlice, findings - case json.Number: - res := p.Scan(val.String()) - if len(res.Findings) > 0 { - if res.Sanitized == "" { - return "", res.Findings - } - return res.Sanitized, res.Findings - } - return val, nil - default: - return val, nil - } -} - // sanitizeJSONKey sanitizes one object key. A key whose sanitized value is // empty was removed entirely, so it is replaced with a placeholder rather than // kept as-is. @@ -547,62 +433,3 @@ func sanitizeJSONString(value, memberKey string, p *Pipeline) (string, []Finding } return out, findings } - -// HasDuplicateJSONKeys parses content token by token and reports whether any -// JSON object within the payload contains duplicate keys. -func HasDuplicateJSONKeys(content []byte) bool { - dec := json.NewDecoder(bytes.NewReader(content)) - dec.UseNumber() - var stack []*jsonContainerFrame - for { - tok, err := dec.Token() - if err != nil { - return false - } - switch t := tok.(type) { - case json.Delim: - switch t { - case '{': - stack = append(stack, &jsonContainerFrame{ - isObject: true, - expectingKey: true, - keys: make(map[string]bool), - }) - case '[': - stack = append(stack, &jsonContainerFrame{isObject: false}) - case '}', ']': - if len(stack) > 0 { - stack = stack[:len(stack)-1] - } - if len(stack) > 0 && stack[len(stack)-1].isObject { - stack[len(stack)-1].expectingKey = true - } - } - case string: - if len(stack) > 0 && stack[len(stack)-1].isObject { - top := stack[len(stack)-1] - if top.expectingKey { - if top.keys[t] { - return true - } - top.keys[t] = true - top.expectingKey = false - } else { - top.expectingKey = true - } - } - default: - if len(stack) > 0 && stack[len(stack)-1].isObject { - stack[len(stack)-1].expectingKey = true - } - } - } -} - -// jsonContainerFrame tracks one open object or array while scanning for -// duplicate keys. -type jsonContainerFrame struct { - isObject bool - expectingKey bool - keys map[string]bool -} diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index cc97269f58..f58b431854 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -27,6 +27,107 @@ func TestSanitizeJSONDocument_DuplicateKeyEarlierOccurrenceRedacted(t *testing.T assert.Contains(t, string(out), `"note":"clean"`, "the surviving duplicate value must be preserved") } +// TestSanitizeJSONDocument_DuplicateKeysSurviveRewrite pins that the +// token-preserving walk keeps duplicate keys and their order when another +// member forces a rewrite. +func TestSanitizeJSONDocument_DuplicateKeysSurviveRewrite(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"a":1,"a":2,"token":"ghp_FAKEtesttoken000000000000000000000000"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.Contains(t, string(out), `"a":1,"a":2`, "duplicate members must keep their order") + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersFailsClosed pins that a +// private key spread over several members is detected in the bytes that are +// actually written. Scanning only the re-encoded form missed it: encoding a map +// sorts keys, and with the END marker sorted before the BEGIN marker the +// pattern no longer matched the original key material. +func TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersFailsClosed(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + // Reverse the members' sort order so a map re-encode would emit END before + // BEGIN and hide the block from a serialized scan. + doc := []byte(`{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "a framing-spanning private key must produce a finding") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "BEGIN RSA") + assert.NotContains(t, string(out), "MIIEpAIBAAKCAQEA") + assert.Contains(t, string(out), "output removed", "an unmappable match must fail closed") +} + +// TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed pins that a +// document with no leaf findings is still scanned in its written form. A +// runtime secret spanning two member boundaries is visible only in the raw +// bytes, and the previous no-findings path returned those bytes untouched. +func TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed(t *testing.T) { + ResetRuntimeSecretsForTest() + t.Cleanup(ResetRuntimeSecretsForTest) + const secret = `","field2":"` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + doc := []byte(`{"field1":"foo","field2":"bar"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "a framing-spanning secret must produce a finding") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), secret) +} + +// TestSanitizeJSONDocument_CrossMemberPrivateKeyWithLeafSecretFailsClosed pins +// that a leaf secret and a framing-spanning private key in the same document +// are both handled: the rewrite keeps member order, so the framing-spanning +// block is still visible in the rewritten bytes. +func TestSanitizeJSONDocument_CrossMemberPrivateKeyWithLeafSecretFailsClosed(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + doc := []byte(`{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `",` + + `"token":"ghp_FAKEtesttoken000000000000000000000000"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + assert.NotContains(t, string(out), "PRIVATE KEY-----") +} + +// TestSanitizeJSONDocument_DuplicateKeySanitizedKeyCollision pins that a +// sanitized key never steals the name of an existing clean member, and that +// intentional duplicate keys still survive. +func TestSanitizeJSONDocument_DuplicateKeySanitizedKeyCollision(t *testing.T) { + ResetRuntimeSecretsForTest() + t.Cleanup(ResetRuntimeSecretsForTest) + const secret = "abcdefghijk" + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + doc := []byte(`{"` + secret + `":1,"***":2,"d":0,"d":1}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), secret) + + var decoded map[string]any + require.NoError(t, json.Unmarshal(out, &decoded)) + assert.Equal(t, float64(2), decoded["***"], "the clean key must keep its own value") + assert.Equal(t, float64(1), decoded["***_1"], "the sanitized key must be disambiguated") + assert.Equal(t, 2, strings.Count(string(out), `"d":`), "intentional duplicate keys must survive") +} + // TestSanitizeJSONLines_CrossRecordRuntimeSecretFailsClosed pins that a // runtime secret spanning two individually valid records is not discarded. func TestSanitizeJSONLines_CrossRecordRuntimeSecretFailsClosed(t *testing.T) { @@ -51,9 +152,44 @@ func TestSanitizeJSONLines_CrossRecordRuntimeSecretFailsClosed(t *testing.T) { } } +// TestSanitizeJSONLines_DisjointCrossRecordMatchesKeepCleanRecord pins that +// only the records a cross-record match touches are replaced. A single +// first-to-last changed region used to swallow every record between two +// disjoint matches. +func TestSanitizeJSONLines_DisjointCrossRecordMatchesKeepCleanRecord(t *testing.T) { + ResetRuntimeSecretsForTest() + t.Cleanup(ResetRuntimeSecretsForTest) + const first = `one"}` + "\n" + `{"b` + const second = `three"}` + "\n" + `{"d` + require.True(t, RegisterRuntimeSecret(first)) + require.True(t, RegisterRuntimeSecret(second)) + + p := OutputPipeline() + content := []byte( + "{\"a\":\"one\"}\n" + + "{\"b\":\"two\"}\n" + + "{\"clean\":\"middle\"}\n" + + "{\"c\":\"three\"}\n" + + "{\"d\":\"four\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), first) + assert.NotContains(t, string(out), second) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 5, "record count must not change") + assert.Equal(t, `{"clean":"middle"}`, lines[2], "the clean record between two matches must survive") + for _, i := range []int{0, 1, 3, 4} { + assert.True(t, json.Valid([]byte(lines[i])), "each replaced record must stay valid JSON: %s", lines[i]) + assert.Contains(t, lines[i], "output removed") + } +} + // TestSanitizeJSONDocument_BackstopRedactsSecondRuntimeSecret pins that a // runtime secret exposed only by serializing the parsed document is still -// redacted when another runtime secret was already found in a leaf. +// handled when another runtime secret was already found in a leaf. func TestSanitizeJSONDocument_BackstopRedactsSecondRuntimeSecret(t *testing.T) { ResetRuntimeSecretsForTest() t.Cleanup(ResetRuntimeSecretsForTest) @@ -73,24 +209,28 @@ func TestSanitizeJSONDocument_BackstopRedactsSecondRuntimeSecret(t *testing.T) { assert.NotContains(t, string(out), serializedSecret) } -// TestSanitizeJSONStructure_KeyRemovedEntirelyIsReplaced pins that a JSON key +// TestSanitizeJSONDocument_KeyRemovedEntirelyIsReplaced pins that a JSON key // made only of removable characters never survives sanitization. -func TestSanitizeJSONStructure_KeyRemovedEntirelyIsReplaced(t *testing.T) { +func TestSanitizeJSONDocument_KeyRemovedEntirelyIsReplaced(t *testing.T) { p := OutputPipeline() for name, key := range map[string]string{ "null byte": "\x00", "bidi override": "\u202e", } { t.Run(name, func(t *testing.T) { - got, findings := SanitizeJSONStructure(map[string]any{key: "value"}, p) + doc, err := json.Marshal(map[string]string{key: "value"}) + require.NoError(t, err) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) require.NotEmpty(t, findings) - result := got.(map[string]any) - require.Len(t, result, 1) - for gotKey := range result { - assert.NotContains(t, gotKey, key) - assert.Equal(t, redactedJSONKey, gotKey) - } - assert.Equal(t, "value", result[redactedJSONKey]) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), `\u0000`) + assert.NotContains(t, string(out), `\u202e`) + + var decoded map[string]string + require.NoError(t, json.Unmarshal(out, &decoded)) + assert.Equal(t, "value", decoded[redactedJSONKey]) }) } } @@ -120,8 +260,8 @@ func TestSanitizeJSONLines_SingleRecordPEMKeepsCleanRecords(t *testing.T) { assert.NotContains(t, lines[1], "MIIEpAIBAAKCAQEA") } -// TestSanitizeJSONDocument_AlreadyMaskedValueNotRemasked pins that the -// serialized backstop leaves an existing mask placeholder intact. +// TestSanitizeJSONDocument_AlreadyMaskedValueNotRemasked pins that rescanning a +// document leaves an existing mask placeholder intact. func TestSanitizeJSONDocument_AlreadyMaskedValueNotRemasked(t *testing.T) { p := OutputPipeline() doc := []byte(`{"body":"Guard against null values with token_usage = metrics.get(\"token_usage\") or {}"}`) @@ -161,29 +301,48 @@ func TestSanitizeJSONDocument_DuplicateKeyNestedContainers(t *testing.T) { assert.Equal(t, false, decoded.(map[string]any)["tail"]) } -// TestSanitizeJSONStructure_ScalarAndContainerCoverage exercises every scalar -// branch and nested collection of the structural walker. -func TestSanitizeJSONStructure_ScalarAndContainerCoverage(t *testing.T) { +// TestSanitizeJSONDocument_ScalarAndContainerCoverage exercises every scalar +// branch and nested collection of the walker. +func TestSanitizeJSONDocument_ScalarAndContainerCoverage(t *testing.T) { ResetRuntimeSecretsForTest() t.Cleanup(ResetRuntimeSecretsForTest) const numericSecret = "123456789012" require.True(t, RegisterRuntimeSecret(numericSecret)) p := OutputPipeline() - input := map[string]any{ - "list": []any{"plain", json.Number("42"), json.Number(numericSecret), true, nil}, - "nested": map[string]any{"deep": []any{map[string]any{"value": "plain"}}}, - "counter": json.Number("7"), - } - got, findings := SanitizeJSONStructure(input, p) - require.NotEmpty(t, findings) + doc := []byte(`{"list":["plain",42,` + numericSecret + `,true,null],` + + `"nested":{"deep":[{"value":"plain"}]},"counter":7}`) - encoded, err := encodeJSONDocument(got, false) + out, findings, err := SanitizeJSONDocument(doc, p) require.NoError(t, err) - assert.True(t, json.Valid(encoded)) - assert.NotContains(t, string(encoded), numericSecret) - assert.Contains(t, string(encoded), "42", "clean numbers must keep their precision") - assert.Contains(t, string(encoded), `"counter":7`) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), numericSecret) + assert.Contains(t, string(out), "42", "clean numbers must keep their precision") + assert.Contains(t, string(out), `"counter":7`) +} + +// TestSanitizeJSONDocument_CleanKeyWinsSanitizedCollision pins that a secret key +// whose mask collides with an existing clean member never steals that member's +// name or value. +func TestSanitizeJSONDocument_CleanKeyWinsSanitizedCollision(t *testing.T) { + const secret = "ghp_FAKEtesttoken000000000000000000000000" + const masked = "ghp_..." + p := OutputPipeline() + doc := []byte(`{"` + secret + `":"secretkeyval","` + masked + `":"plainval"}`) + + for range 20 { + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + + var decoded map[string]string + require.NoError(t, json.Unmarshal(out, &decoded)) + assert.Equal(t, "plainval", decoded[masked], "clean key must retain its name and value") + assert.Len(t, decoded, 2) + assert.NotContains(t, string(out), secret) + } } // TestSanitizeJSONDocument_LeavesUnsupportedInputAlone pins the fallback @@ -218,6 +377,79 @@ func TestSanitizeJSONLines_NonJSONRecordsRedacted(t *testing.T) { assert.Equal(t, 1, strings.Count(string(out), "\n"), "line framing must be preserved") } +// TestSanitizeJSONLines_PreservesBlankAndCleanRecords pins that blank lines and +// clean non-JSON records survive a stream that also contains a secret. +func TestSanitizeJSONLines_PreservesBlankAndCleanRecords(t *testing.T) { + p := OutputPipeline() + content := []byte("plain prose without secrets\n" + + "\n" + + "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "blank lines and record count must be preserved") + assert.Equal(t, "plain prose without secrets", lines[0]) + assert.Empty(t, lines[1]) + assert.NotContains(t, lines[2], "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONDocument_TextRedactionThatBreaksJSONFailsClosed pins that a +// framing-spanning secret whose in-place redaction would leave invalid JSON is +// replaced with a valid marker instead of corrupted syntax. +func TestSanitizeJSONDocument_TextRedactionThatBreaksJSONFailsClosed(t *testing.T) { + ResetRuntimeSecretsForTest() + t.Cleanup(ResetRuntimeSecretsForTest) + // Spans the closing quote, comma and next key, so masking it breaks the + // document. + const secret = `"v1","k2"` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + doc := []byte(`{"k1":"v1","k2":"v2"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), secret) + assert.Contains(t, string(out), "output removed") +} + +// TestSanitizeJSONDocument_TopLevelScalars pins that scalar documents are +// handled without inventing structure. +func TestSanitizeJSONDocument_TopLevelScalars(t *testing.T) { + p := OutputPipeline() + for name, doc := range map[string]string{ + "number": "42", + "true": "true", + "null": "null", + } { + t.Run(name, func(t *testing.T) { + out, findings, err := SanitizeJSONDocument([]byte(doc), p) + require.NoError(t, err) + assert.Empty(t, findings) + assert.Equal(t, doc, string(out)) + }) + } +} + +// TestSanitizeJSONLines_LastRecordWithoutNewline pins that a final record +// without a trailing newline is still sanitized and keeps its framing. +func TestSanitizeJSONLines_LastRecordWithoutNewline(t *testing.T) { + p := OutputPipeline() + content := []byte(`{"token":"ghp_FAKEtesttoken000000000000000000000000"}`) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + assert.False(t, strings.HasSuffix(string(out), "\n"), "no newline must be invented") + assert.True(t, json.Valid(out), "the record must stay valid JSON: %s", out) +} + // TestSanitizeJSONLines_PreservesCRLFFraming pins that CRLF records keep their // carriage returns across a rewrite. func TestSanitizeJSONLines_PreservesCRLFFraming(t *testing.T) { @@ -231,6 +463,28 @@ func TestSanitizeJSONLines_PreservesCRLFFraming(t *testing.T) { assert.NotContains(t, string(out), "ghp_FAKEtesttoken") } +// TestSanitizeJSONDocument_TrailingNewlinePreserved pins that a rewritten +// document keeps the file's own line framing. +func TestSanitizeJSONDocument_TrailingNewlinePreserved(t *testing.T) { + p := OutputPipeline() + for name, doc := range map[string]string{ + "lf": "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\n", + "crlf": "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\r\n", + "none": "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}", + } { + t.Run(name, func(t *testing.T) { + out, findings, err := SanitizeJSONDocument([]byte(doc), p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") + + want := map[string]string{"lf": "\n", "crlf": "\r\n", "none": ""}[name] + assert.True(t, strings.HasSuffix(string(out), "}"+want), "trailing framing must be preserved: %q", out) + assert.Equal(t, strings.Count(doc, "\n"), strings.Count(string(out), "\n")) + }) + } +} + // TestSanitizeJSONDocument_CleanDuplicateKeyDocumentUnchanged pins that a // duplicate-key document with nothing to redact is left byte-for-byte intact. func TestSanitizeJSONDocument_CleanDuplicateKeyDocumentUnchanged(t *testing.T) { @@ -243,9 +497,9 @@ func TestSanitizeJSONDocument_CleanDuplicateKeyDocumentUnchanged(t *testing.T) { assert.Equal(t, string(doc), string(out), "a clean duplicate-key document must not be reformatted") } -// TestSanitizeJSONDocument_DuplicateKeyRawTextFinding covers a duplicate-key -// document whose only match exists in the serialized form: the leaves are -// individually clean, so the raw-text scan finds and redacts it. +// TestSanitizeJSONDocument_DuplicateKeyRawTextFinding covers a document whose +// match exists in the serialized form: the leaves are individually clean, so +// the raw-text scan finds and redacts it. func TestSanitizeJSONDocument_DuplicateKeyRawTextFinding(t *testing.T) { p := OutputPipeline() doc := []byte(`{"password": "secretvalue123", "dup": 1, "dup": 2}`) From a0a4cf2cf588adabcb82415661db454c324fde94 Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 19 Nov 2026 12:45:36 -0500 Subject: [PATCH 18/51] fix(security): localize JSONL redaction unambiguously The cross-record fail-closed path found the records a match covered by searching the redacted stream for each record's bytes. A repeated record broke that: a later untouched copy stood in for the copy the match covered, so the covered record was written back in its original form. With the match spanning two records whose text also occurs later, the written output reassembles the registered secret verbatim. Localization now requires every record to be distinct; when any record text repeats, the whole stream fails closed. A surviving copy must also be a whole newline-delimited record rather than a substring of a longer one. The check is package-private and covered directly by TestLineBounded. Sanitizing a document had a related gap: a private-key block spanning members was invisible once a sensitive-named member (key_start, say) was masked to a json_field placeholder, which removed the BEGIN marker and left the body and END marker behind. The block is now detected with the structural private-key pattern on the original framing, before masking, and the document fails closed. The six JSONL tests that only exercise the security package moved from internal/cli/scan_output_telemetry_test.go to jsonsanitize_test.go and follow the TestSanitizeJSONLines_ naming convention. Regression tests: - TestSanitizeJSONLines_RepeatedRecordsFailsClosed - TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch - TestSanitizeJSONDocument_SensitiveBeginMemberFailsClosed Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 8 +- internal/cli/scan_output_telemetry_test.go | 99 --------- internal/security/jsonsanitize.go | 89 +++++++- internal/security/jsonsanitize_test.go | 220 ++++++++++++++++++++ 4 files changed, 311 insertions(+), 105 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index be5f7b0bc5..fd3b4383bd 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -623,10 +623,14 @@ duplicate keys, so an earlier value that map decoding would drop is still scanned, and a secret spanning JSON framing stays visible in the rewritten bytes. A sanitized key that would collide with a different member is disambiguated (`_`). The bytes actually written are scanned as well, so -a secret that only exists in the serialized form is still caught. +a secret that only exists in the serialized form is still caught, and a +private-key block spanning members is detected in the original framing before +masking a member value can hide its BEGIN marker. `.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the record framing; a secret that spans records cannot be redacted without -rewriting that framing, so only the records it covers are replaced. +rewriting that framing, so only the records it covers are replaced. When those +records cannot be identified unambiguously — their contents also appear +elsewhere in the stream — every record fails closed. Some content cannot be redacted in place. A JSON document or JSONL record is replaced with a valid fail-closed marker instead — never with corrupted diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 3028be1037..7b7ce21f74 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -316,54 +316,6 @@ 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 := security.SanitizeJSONLines(content, pipeline) - require.NoError(t, err) - assert.NotEmpty(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, err := security.SanitizeJSONLines(content, pipeline) - require.NoError(t, err) - require.NotEmpty(t, findings) - assert.Equal(t, "private_key", findings[0].Name) - lines := strings.Split(strings.TrimSuffix(string(got), "\n"), "\n") - require.Len(t, lines, 3) - for _, line := range lines { - assert.True(t, json.Valid([]byte(line))) - assert.Contains(t, line, "output removed") - } -} - -func TestSanitizeJSONLinesFailsClosedForRawMultilinePEM(t *testing.T) { - pipeline := security.OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" - content := []byte(fmt.Sprintf("%s\nMIIEpAIBAAKCAQEA0123456789abcdefghijklmnop\n%s\n", begin, end)) - got, findings, err := security.SanitizeJSONLines(content, pipeline) - require.NoError(t, err) - require.NotEmpty(t, findings) - assert.Equal(t, "private_key", findings[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") @@ -383,57 +335,6 @@ func TestScanOutputFiles_JSONLRawMultilinePEMRemainsValid(t *testing.T) { } } -func TestSanitizeJSONLines_DuplicateKeyRecordRedactsEscapedSecret(t *testing.T) { - pipeline := security.OutputPipeline() - // A secret encoded with JSON Unicode escapes in a record that also has duplicate keys. - // Raw text scanning doesn't match the unicode escapes and map decoding drops the - // earlier duplicate, so only a token-preserving walk finds and removes it. - content := []byte("{\"a\":\"first\",\"a\":\"second\",\"password\":\"\\u0073\\u0065\\u0063\\u0072\\u0065\\u0074_password_1234\"}\n") - got, findings, err := security.SanitizeJSONLines(content, pipeline) - require.NoError(t, err) - assert.NotEmpty(t, findings) - line := strings.TrimSpace(string(got)) - assert.True(t, json.Valid([]byte(line))) - assert.NotContains(t, line, "password_1234") - assert.Contains(t, line, `"a":"first"`, "an earlier duplicate value must survive redaction") - assert.Contains(t, line, `"a":"second"`, "the second duplicate value must survive redaction") -} - -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, err := security.SanitizeJSONLines(content, pipeline) - require.NoError(t, err) - require.NotEmpty(t, findings) - 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_SingleRecordPrivateKeyRedactedInPlace(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, err := security.SanitizeJSONLines(content, pipeline) - require.NoError(t, err) - assert.NotEmpty(t, findings) - line := strings.TrimSpace(string(got)) - assert.True(t, json.Valid([]byte(line))) - assert.Equal(t, 1, strings.Count(string(got), "\n"), "one record must stay one record") - assert.NotContains(t, line, "ghp_FAKEtesttoken") - assert.NotContains(t, line, "PRIVATE KEY-----") - assert.Contains(t, line, "[REDACTED PRIVATE KEY]", "a key confined to one record is redacted in place, not failed closed") -} - func TestScanOutputFiles_QuietJSONFallbackDoesNotPrintPath(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "agent-chosen-secret-name.json") diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index f2c35b173d..4719afc5f2 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -52,6 +52,19 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { out := doc if len(findings) > 0 { out = rebuilt + // Masking a member value can hide a private-key block that spans + // members: a sensitive member name masks the BEGIN marker, leaving the + // key body and END marker behind in a form the rewritten scan can no + // longer recognize. Detect the block in the original framing first. + if bytes.Contains(trimmed, []byte("BEGIN")) && len(privateKeyFindings(findings)) == 0 && privateKeyRe.Match(trimmed) { + return preserveTrailingNewline([]byte(failClosedInvalidJSON), doc), + append(findings, Finding{ + Scanner: "secret_redactor", + Name: "private_key", + Severity: "critical", + Detail: "Private key block spans JSON framing and cannot be localized; output removed", + }), nil + } } // Scan the bytes that will actually be written. The walk above already // scanned every decoded key and leaf, so a match here spans JSON framing @@ -61,6 +74,29 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { return preserveTrailingNewline(sanitizedOut, doc), append(findings, outputFindings...), nil } +// privateKeyRe is the structural private-key pattern. A block that spans JSON +// framing has to be detected on the raw document: running the whole pipeline +// first lets a sensitive-named member mask the BEGIN marker and hide it. +var privateKeyRe = func() *regexp.Regexp { + for _, pattern := range defaultStructuralPatterns() { + if pattern.name == "private_key" { + return pattern.regex + } + } + panic("private_key structural pattern is missing") +}() + +// privateKeyFindings returns the private-key findings in findings. +func privateKeyFindings(findings []Finding) []Finding { + var pk []Finding + for _, finding := range findings { + if finding.Name == "private_key" { + pk = append(pk, finding) + } + } + return pk +} + // preserveTrailingNewline drops the newline json.Encoder always appends and // restores the document's own trailing newline, so a rewrite never changes the // file's line framing. @@ -183,18 +219,33 @@ type recordSpan struct { // the clean records between them. // // The per-record pass has already handled every match a single record could -// account for, so a remaining match spans a record boundary. Redaction masks -// every occurrence of a match, so a record that still appears byte-for-byte in -// the sanitized stream cannot carry one of the secrets just removed. +// account for, so a remaining match spans a record boundary. Locating the +// records it covers means finding each record's bytes again in the redacted +// stream, which is only trustworthy when every record is distinct: with a +// repeated record, a later untouched copy can stand in for the copy a match +// covered, and the original bytes — carrying part of the secret — would be +// written back. When that happens the whole stream fails closed. func failClosedRecordSpans(stream []byte, spans []recordSpan, scan ScanResult) []byte { sanitized := []byte(scan.Sanitized) + seen := make(map[string]struct{}, len(spans)) + for _, span := range spans { + record := string(stream[span.start:span.end]) + if _, ok := seen[record]; ok { + return replaceRecordSpans(stream, spans) + } + seen[record] = struct{}{} + } + var out bytes.Buffer cursor := 0 searchFrom := 0 for _, span := range spans { record := stream[span.start:span.end] - if idx := bytes.Index(sanitized[searchFrom:], record); idx >= 0 { + idx := bytes.Index(sanitized[searchFrom:], record) + // A surviving copy must be a whole record, not a substring of a longer + // record that happens to contain the same bytes. + if idx >= 0 && lineBounded(sanitized, searchFrom+idx, searchFrom+idx+len(record)) { searchFrom += idx + len(record) out.Write(stream[cursor:span.end]) cursor = span.end @@ -211,6 +262,36 @@ func failClosedRecordSpans(stream []byte, spans []recordSpan, scan ScanResult) [ return out.Bytes() } +// replaceRecordSpans replaces every record with a valid marker when the +// records a match covers cannot be identified unambiguously. +func replaceRecordSpans(stream []byte, spans []recordSpan) []byte { + var out bytes.Buffer + cursor := 0 + for _, span := range spans { + out.Write(stream[cursor:span.start]) + out.WriteString(failClosedCrossRecordJSON) + cursor = span.end + } + out.Write(stream[cursor:]) + return out.Bytes() +} + +// lineBounded reports whether data[start:end] is a whole newline-delimited +// line. +func lineBounded(data []byte, start, end int) bool { + if start > 0 && data[start-1] != '\n' { + return false + } + switch { + case end == len(data), data[end] == '\n': + return true + case data[end] == '\r': + return end+1 < len(data) && data[end+1] == '\n' + default: + return false + } +} + // rewriteJSONTokens walks every token in doc, sanitizes each object key and // scalar value, and renders a valid JSON document. Unlike map decoding it // keeps member order and duplicate keys, so a secret in an earlier, overwritten diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index f58b431854..c7b37a5c86 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -2,6 +2,7 @@ package security import ( "encoding/json" + "fmt" "strings" "testing" @@ -345,6 +346,225 @@ func TestSanitizeJSONDocument_CleanKeyWinsSanitizedCollision(t *testing.T) { } } +// TestSanitizeJSONLines_RepeatedRecordsFailsClosed pins that a cross-record +// match is not localized by a substring search a repeated record can fool. A +// later untouched copy must never stand in for a covered record: keeping the +// original bytes would write the spanning secret back out. +func TestSanitizeJSONLines_RepeatedRecordsFailsClosed(t *testing.T) { + ResetRuntimeSecretsForTest() + t.Cleanup(ResetRuntimeSecretsForTest) + const secret = `aaa"}` + "\n" + `{"v":"bbb` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + content := []byte( + "{\"v\":\"aaa\"}\n" + // first half of the match + "{\"v\":\"bbb\"}\n" + // second half of the match + "{\"v\":\"aaa\"}\n" + // untouched duplicate of record 1 + "{\"v\":\"ccc\"}\n" + + "{\"v\":\"bbb\"}\n") // untouched duplicate of record 2 + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), secret, "the spanning secret must not be reassembled") + assert.NotContains(t, string(out), `{"v":"aaa"}`, "ambiguous localization must fail closed") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 5, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch pins the +// inverse misattribution: a clean record that also appears later must not be +// kept in place of the covered copy, and the later clean copy must not be +// dropped for it. +func TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + content := []byte( + "[\"" + begin + "\"]\n" + + "{\"value\":\"middle\"}\n" + + "[\"" + end + "\"]\n" + + "{\"value\":\"middle\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), begin) + assert.NotContains(t, string(out), end) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONDocument_SensitiveBeginMemberFailsClosed pins that masking a +// member value cannot hide a private-key block that spans members. A +// sensitive-named member holding only the BEGIN marker is masked as a +// json_field, which leaves the body and END marker behind; the block must be +// detected in the original framing and fail closed. +func TestSanitizeJSONDocument_SensitiveBeginMemberFailsClosed(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + doc := []byte(`{"key_start":"` + begin + `","payload":"MIIEpAIBAAKCAQEA0123456789abcdef","tail":"` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEpAIBAAKCAQEA", "the key body must not survive") + assert.NotContains(t, string(out), "END RSA") + assert.Contains(t, string(out), "output removed") +} + +// TestSanitizeJSONLines_CleanDuplicateKeyRecordPreserved pins that a clean +// duplicate-key record survives while another record is rewritten. +func TestSanitizeJSONLines_CleanDuplicateKeyRecordPreserved(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"a\":1,\"a\":2}\n{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.NotEmpty(t, findings) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 2) + assert.Equal(t, `{"a":1,"a":2}`, lines[0], "clean duplicate-key record must remain unchanged") + assert.True(t, json.Valid([]byte(lines[1]))) + assert.NotContains(t, lines[1], "ghp_FAKEtesttoken") +} + +// TestSanitizeJSONLines_PrivateKeyAcrossRecordsFailsClosed pins that a PEM +// block split over three records replaces all three. +func TestSanitizeJSONLines_PrivateKeyAcrossRecordsFailsClosed(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + content := []byte(fmt.Sprintf("[%q]\n[%q]\n[%q]\n", begin, "MIIEpAIBAAKCAQEA0123456789abcdefghijklmnop", end)) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.Equal(t, "private_key", findings[0].Name) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3) + for _, line := range lines { + assert.True(t, json.Valid([]byte(line))) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONLines_RawMultilinePEMFailsClosed pins the same for a PEM +// block written as raw lines rather than JSON values. +func TestSanitizeJSONLines_RawMultilinePEMFailsClosed(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + content := []byte(fmt.Sprintf("%s\nMIIEpAIBAAKCAQEA0123456789abcdefghijklmnop\n%s\n", begin, end)) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.Equal(t, "private_key", findings[0].Name) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3) + for _, line := range lines { + assert.True(t, json.Valid([]byte(line))) + assert.Contains(t, line, "output removed") + assert.NotContains(t, line, "MIIEpAIBAAKCAQEA") + } +} + +// TestSanitizeJSONLines_DuplicateKeyEscapedSecretRedacted pins that an escaped +// secret in a record with duplicate keys is found by the token walk. +func TestSanitizeJSONLines_DuplicateKeyEscapedSecretRedacted(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"a\":\"first\",\"a\":\"second\",\"password\":\"\\u0073\\u0065\\u0063\\u0072\\u0065\\u0074_password_1234\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.NotEmpty(t, findings) + line := strings.TrimSpace(string(out)) + assert.True(t, json.Valid([]byte(line))) + assert.NotContains(t, line, "password_1234") + assert.Contains(t, line, `"a":"first"`, "an earlier duplicate value must survive redaction") + assert.Contains(t, line, `"a":"second"`, "the second duplicate value must survive redaction") +} + +// TestSanitizeJSONLines_FramingSecretPreservesLineCount pins that a secret +// spanning one record's own framing is redacted without adding or removing +// lines. +func TestSanitizeJSONLines_FramingSecretPreservesLineCount(t *testing.T) { + ResetRuntimeSecretsForTest() + t.Cleanup(ResetRuntimeSecretsForTest) + const secret = `","field2":"` + require.True(t, RegisterRuntimeSecret(secret)) + + p := OutputPipeline() + content := []byte("{\"field1\":\"foo\",\"field2\":\"bar\"}\n{\"field3\":\"second record\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.Equal(t, 2, strings.Count(string(out), "\n"), "line count must remain exactly 2") + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 2) + assert.True(t, json.Valid([]byte(lines[0]))) + assert.True(t, json.Valid([]byte(lines[1]))) + assert.NotContains(t, lines[0], secret) +} + +// TestSanitizeJSONLines_SingleRecordPrivateKeyRedactedInPlace pins that a key +// confined to one record is redacted rather than failed closed. +func TestSanitizeJSONLines_SingleRecordPrivateKeyRedactedInPlace(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + content := []byte(fmt.Sprintf("{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\",\"pem\":\"%s\\n%s\"}\n", begin, end)) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.NotEmpty(t, findings) + line := strings.TrimSpace(string(out)) + assert.True(t, json.Valid([]byte(line))) + assert.Equal(t, 1, strings.Count(string(out), "\n"), "one record must stay one record") + assert.NotContains(t, line, "ghp_FAKEtesttoken") + assert.NotContains(t, line, "PRIVATE KEY-----") + assert.Contains(t, line, "[REDACTED PRIVATE KEY]", "a key confined to one record is redacted in place") +} + +// TestLineBounded pins the record-boundary check used to decide whether a +// surviving record copy is a whole record. +func TestLineBounded(t *testing.T) { + data := []byte("a\nbb\r\nccc\nlast") + tests := []struct { + name string + start, end int + want bool + }{ + {"whole first line", 0, 1, true}, + {"whole crlf line", 2, 4, true}, + {"whole middle line", 6, 9, true}, + {"last line without newline", 10, 14, true}, + {"starts mid-line", 1, 4, false}, + {"ends mid-line", 6, 8, false}, + {"lone carriage return", 9, 10, false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, lineBounded(data, tc.start, tc.end)) + }) + } +} + // TestSanitizeJSONDocument_LeavesUnsupportedInputAlone pins the fallback // contract for documents the structural path cannot handle. func TestSanitizeJSONDocument_LeavesUnsupportedInputAlone(t *testing.T) { From 8a0dbf75996a24691950ee10b7c9c43c957f7e5c Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 19 Nov 2026 13:12:23 -0500 Subject: [PATCH 19/51] fix(security): detect cross-record private keys before masking The private-key guards judged the document as a whole. A single handled block exempted every other block: with one complete PEM in a leaf string and a second block split across a sensitive-named key_start, payload and tail, the leaf finding skipped the original-framing check and the second key's body and END marker survived. The check now compares the number of blocks in the original framing with the number the leaf scan handled, so only blocks that were actually redacted are exempt. SanitizeJSONLines had the same gap one level up: its whole-stream scan ran on the already-sanitized records, so a cross-record block whose BEGIN marker sat in a sensitive-named member was masked before the scan could see it, and the body and END marker records were written unchanged. Cross-record blocks are now detected on the original stream, and the records they intersect are replaced. Offsets come from the regex match, so localization is exact and no search is involved. Regression tests: - TestSanitizeJSONDocument_LeafAndSplitPrivateKeysFailClosed - TestSanitizeJSONLines_SensitiveBeginRecordFailsClosed (LF, CRLF and no trailing newline) Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 8 +- internal/security/jsonsanitize.go | 82 ++++++++++++++++++++- internal/security/jsonsanitize_test.go | 63 +++++++++++++++- 3 files changed, 146 insertions(+), 7 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index fd3b4383bd..f755d7573f 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -628,9 +628,11 @@ private-key block spanning members is detected in the original framing before masking a member value can hide its BEGIN marker. `.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the record framing; a secret that spans records cannot be redacted without -rewriting that framing, so only the records it covers are replaced. When those -records cannot be identified unambiguously — their contents also appear -elsewhere in the stream — every record fails closed. +rewriting that framing, so only the records it covers are replaced. A +private-key block spanning records is detected on the original stream, before +per-record masking can remove its BEGIN marker. When the covered records +cannot be identified unambiguously — their contents also appear elsewhere in +the stream — every record fails closed. Some content cannot be redacted in place. A JSON document or JSONL record is replaced with a valid fail-closed marker instead — never with corrupted diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 4719afc5f2..5397cccdbc 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -55,8 +55,10 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { // Masking a member value can hide a private-key block that spans // members: a sensitive member name masks the BEGIN marker, leaving the // key body and END marker behind in a form the rewritten scan can no - // longer recognize. Detect the block in the original framing first. - if bytes.Contains(trimmed, []byte("BEGIN")) && len(privateKeyFindings(findings)) == 0 && privateKeyRe.Match(trimmed) { + // longer recognize. Every block the leaf scan did not account for + // individually means the original framing must be checked. + unhandled := len(privateKeyRe.FindAllIndex(trimmed, -1)) - len(privateKeyFindings(findings)) + if bytes.Contains(trimmed, []byte("BEGIN")) && unhandled > 0 { return preserveTrailingNewline([]byte(failClosedInvalidJSON), doc), append(findings, Finding{ Scanner: "secret_redactor", @@ -141,11 +143,17 @@ func redactJSONOutput(clean []byte, p *Pipeline) ([]byte, []Finding) { // that framing, so the records it covers are replaced with valid fail-closed // markers and every other record is left as sanitized. func SanitizeJSONLines(content []byte, p *Pipeline) ([]byte, []Finding, error) { + // A private-key block that spans records has to be detected on the original + // framing: per-record masking of a sensitive member removes the BEGIN + // marker, after which neither the record scan nor the whole-stream scan can + // recognize the block. + content, crossRecordFindings := failClosedCrossRecordPrivateKeys(content) var ( out bytes.Buffer findings []Finding spans []recordSpan ) + findings = append(findings, crossRecordFindings...) for len(content) > 0 { line := content newline := bytes.IndexByte(content, '\n') @@ -213,6 +221,76 @@ type recordSpan struct { start, end int } +// failClosedCrossRecordPrivateKeys replaces every record covered by a +// private-key block that crosses record boundaries with a valid marker. Match +// offsets come straight from the original stream, so localization is exact. +func failClosedCrossRecordPrivateKeys(content []byte) ([]byte, []Finding) { + matches := privateKeyRe.FindAllIndex(content, -1) + if len(matches) == 0 { + return content, nil + } + spans := jsonLineSpans(content) + if len(spans) == 0 { + return content, nil + } + covered := make([]bool, len(spans)) + var findings []Finding + for _, match := range matches { + if bytes.IndexByte(content[match[0]:match[1]], '\n') < 0 { + continue + } + findings = append(findings, Finding{ + Scanner: "secret_redactor", + Name: "private_key", + Severity: "critical", + Detail: "Private key block spans records and cannot be localized; output removed", + }) + for i, span := range spans { + if span.end > match[0] && span.start < match[1] { + covered[i] = true + } + } + } + if len(findings) == 0 { + return content, nil + } + var out bytes.Buffer + cursor := 0 + for i, span := range spans { + if !covered[i] { + continue + } + out.Write(content[cursor:span.start]) + out.WriteString(failClosedCrossRecordJSON) + cursor = span.end + } + out.Write(content[cursor:]) + return out.Bytes(), findings +} + +// jsonLineSpans returns the byte range of every non-empty line in content, +// excluding its trailing CR/LF framing. +func jsonLineSpans(content []byte) []recordSpan { + var spans []recordSpan + for start := 0; start < len(content); { + end := bytes.IndexByte(content[start:], '\n') + if end < 0 { + end = len(content) + } else { + end += start + } + lineEnd := end + if lineEnd > start && content[lineEnd-1] == '\r' { + lineEnd-- + } + if len(bytes.TrimSpace(content[start:lineEnd])) > 0 { + spans = append(spans, recordSpan{start: start, end: lineEnd}) + } + start = end + 1 + } + return spans +} + // failClosedRecordSpans replaces the records a whole-stream redaction changed // with a valid fail-closed marker. Records the redaction did not touch are // copied through unchanged, so two disjoint cross-record matches never discard diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index c7b37a5c86..392180ed56 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -400,10 +400,11 @@ func TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch(t *testing. lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") require.Len(t, lines, 4, "record count must not change") - for _, line := range lines { - assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + for _, line := range lines[:3] { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) assert.Contains(t, line, "output removed") } + assert.Equal(t, `{"value":"middle"}`, lines[3], "the repeated clean record outside the match must survive") } // TestSanitizeJSONDocument_SensitiveBeginMemberFailsClosed pins that masking a @@ -565,6 +566,64 @@ func TestLineBounded(t *testing.T) { } } +// TestSanitizeJSONDocument_LeafAndSplitPrivateKeysFailClosed pins that a +// handled leaf block does not exempt a second, framing-spanning block in the +// same document. +func TestSanitizeJSONDocument_LeafAndSplitPrivateKeysFailClosed(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + doc := []byte(`{"note":"` + begin + `\nMIIEleafkeymaterial\n` + end + `",` + + `"key_start":"` + begin + `","payload":"MIIEspanningkeymaterial","tail":"` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial") + assert.NotContains(t, string(out), "MIIEleafkeymaterial") + assert.Contains(t, string(out), "output removed") +} + +// TestSanitizeJSONLines_SensitiveBeginRecordFailsClosed pins that a +// cross-record private key is detected on the original stream, before masking +// a sensitive-named member removes its BEGIN marker. +func TestSanitizeJSONLines_SensitiveBeginRecordFailsClosed(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + records := []string{ + "{\"key_start\":\"" + begin + "\"}", + "{\"payload\":\"MIIEspanningkeymaterial\"}", + "{\"tail\":\"" + end + "\"}", + } + for name, tc := range map[string]struct { + sep string + trailer string + }{ + "lf": {sep: "\n", trailer: "\n"}, + "crlf": {sep: "\r\n", trailer: "\r\n"}, + "no trailing newline": {sep: "\n", trailer: ""}, + } { + t.Run(name, func(t *testing.T) { + content := []byte(strings.Join(records, tc.sep) + tc.trailer) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial") + assert.NotContains(t, string(out), "END RSA") + + lines := strings.Split(strings.TrimSuffix(strings.TrimSuffix(string(out), "\n"), "\r"), tc.sep) + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } + }) + } +} + // TestSanitizeJSONDocument_LeavesUnsupportedInputAlone pins the fallback // contract for documents the structural path cannot handle. func TestSanitizeJSONDocument_LeavesUnsupportedInputAlone(t *testing.T) { From bb35a97f6b4332ba475f14649724bbbf79245568 Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 19 Nov 2026 14:07:34 -0500 Subject: [PATCH 20/51] fix(security): detect framing-spanning keys from decoded text The previous guard compared private-key blocks matched in the raw document bytes with the blocks the leaf scan found in decoded values. Those counts are not comparable: a leaf block whose marker is written with \u escapes matches after decoding but not in the raw bytes, so it cancelled out a separate block that really did span members, and that block's body and END marker were written out after sensitive-member masking removed its BEGIN marker. Private-key detection now runs over an order-preserving decoded view: the token walk appends every decoded key and string leaf, so a block split across members is contiguous there and one contained in a single leaf is counted against that leaf. Any block the view sees but no single leaf contains fails the document closed. The JSONL precheck had the same blind spot: it matched literal markers in the original record bytes, so an escaped BEGIN marker in a sensitive-named member was masked per record and the payload and END records survived. It now builds a decoded view per record, keeps each record's range in that view, and replaces every record a spanning match intersects. Regression tests: - TestSanitizeJSONDocument_EscapedLeafBlockDoesNotExemptSplitBlock - TestSanitizeJSONLines_EscapedBeginRecordFailsClosed Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 9 +- internal/security/jsonsanitize.go | 130 +++++++++++++++----- internal/security/jsonsanitize_test.go | 45 +++++++ 3 files changed, 147 insertions(+), 37 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index f755d7573f..c8654744cf 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -624,13 +624,14 @@ scanned, and a secret spanning JSON framing stays visible in the rewritten bytes. A sanitized key that would collide with a different member is disambiguated (`_`). The bytes actually written are scanned as well, so a secret that only exists in the serialized form is still caught, and a -private-key block spanning members is detected in the original framing before -masking a member value can hide its BEGIN marker. +private-key block spanning members is detected in a decoded view of the document +before masking a member value can hide its BEGIN marker. `.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the record framing; a secret that spans records cannot be redacted without rewriting that framing, so only the records it covers are replaced. A -private-key block spanning records is detected on the original stream, before -per-record masking can remove its BEGIN marker. When the covered records +private-key block spanning records is detected in a decoded view of the stream, +before per-record masking can remove its BEGIN marker, so a marker written with +\u escapes is still recognized. When the covered records cannot be identified unambiguously — their contents also appear elsewhere in the stream — every record fails closed. diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 5397cccdbc..0dec93fb37 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -42,7 +42,7 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { if len(trimmed) == 0 || !json.Valid(trimmed) { return doc, nil, nil } - rebuilt, findings, err := rewriteJSONTokens(trimmed, p) + rebuilt, findings, prov, err := rewriteJSONTokens(trimmed, p) if err != nil { // json.Valid accepted the text and the walk uses the same scanner, so // this is a decoder limit rather than a syntax error. Return the error @@ -55,10 +55,9 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { // Masking a member value can hide a private-key block that spans // members: a sensitive member name masks the BEGIN marker, leaving the // key body and END marker behind in a form the rewritten scan can no - // longer recognize. Every block the leaf scan did not account for - // individually means the original framing must be checked. - unhandled := len(privateKeyRe.FindAllIndex(trimmed, -1)) - len(privateKeyFindings(findings)) - if bytes.Contains(trimmed, []byte("BEGIN")) && unhandled > 0 { + // longer recognize. The decoded view knows whether every block was + // contained in one key or leaf. + if prov.spanningBlocks() > 0 { return preserveTrailingNewline([]byte(failClosedInvalidJSON), doc), append(findings, Finding{ Scanner: "secret_redactor", @@ -88,15 +87,28 @@ var privateKeyRe = func() *regexp.Regexp { panic("private_key structural pattern is missing") }() -// privateKeyFindings returns the private-key findings in findings. -func privateKeyFindings(findings []Finding) []Finding { - var pk []Finding - for _, finding := range findings { - if finding.Name == "private_key" { - pk = append(pk, finding) - } - } - return pk +// jsonProvenance accumulates an order-preserving view of the decoded strings +// in a document so a private-key block that spans members can be detected after +// JSON decoding. The raw bytes are not usable for this: a member may encode a +// marker with \u escapes, and masking a sensitive member removes the BEGIN +// marker before the rewritten document is scanned. +type jsonProvenance struct { + decoded bytes.Buffer + leafCount int +} + +// addString appends one decoded key or string leaf to the view and counts the +// private-key blocks it fully contains. +func (v *jsonProvenance) addString(s string) { + v.leafCount += len(privateKeyRe.FindAllIndex([]byte(s), -1)) + v.decoded.WriteString(s) + v.decoded.WriteByte('\n') +} + +// spanningBlocks reports how many private-key blocks exist in the decoded view +// that no single key or leaf contains. +func (v *jsonProvenance) spanningBlocks() int { + return len(privateKeyRe.FindAllIndex(v.decoded.Bytes(), -1)) - v.leafCount } // preserveTrailingNewline drops the newline json.Encoder always appends and @@ -225,18 +237,41 @@ type recordSpan struct { // private-key block that crosses record boundaries with a valid marker. Match // offsets come straight from the original stream, so localization is exact. func failClosedCrossRecordPrivateKeys(content []byte) ([]byte, []Finding) { - matches := privateKeyRe.FindAllIndex(content, -1) - if len(matches) == 0 { - return content, nil - } spans := jsonLineSpans(content) if len(spans) == 0 { return content, nil } + // Match in a decoded, order-preserving view so a marker written with + // \u escapes is still recognized, and keep each record's range in that + // view so a match maps back to the records it covers. + var ( + view bytes.Buffer + viewSpans []recordSpan + ) + for _, span := range spans { + start := view.Len() + line := content[span.start:span.end] + if trimmed := bytes.TrimSpace(line); json.Valid(trimmed) { + writeDecodedJSONView(&view, trimmed) + } else { + view.Write(line) + } + view.WriteByte('\n') + viewSpans = append(viewSpans, recordSpan{start: start, end: view.Len() - 1}) + } + matches := privateKeyRe.FindAllIndex(view.Bytes(), -1) covered := make([]bool, len(spans)) var findings []Finding for _, match := range matches { - if bytes.IndexByte(content[match[0]:match[1]], '\n') < 0 { + var hit []int + for i, span := range viewSpans { + if span.end > match[0] && span.start < match[1] { + hit = append(hit, i) + } + } + // A block confined to one record is handled by that record's own + // sanitization. + if len(hit) < 2 { continue } findings = append(findings, Finding{ @@ -245,10 +280,8 @@ func failClosedCrossRecordPrivateKeys(content []byte) ([]byte, []Finding) { Severity: "critical", Detail: "Private key block spans records and cannot be localized; output removed", }) - for i, span := range spans { - if span.end > match[0] && span.start < match[1] { - covered[i] = true - } + for _, i := range hit { + covered[i] = true } } if len(findings) == 0 { @@ -268,6 +301,34 @@ func failClosedCrossRecordPrivateKeys(content []byte) ([]byte, []Finding) { return out.Bytes(), findings } +// writeDecodedJSONView appends every decoded object key and string leaf of doc +// to buf in document order, one per line, so a value split across members is +// still visible as one contiguous run of text. +func writeDecodedJSONView(buf *bytes.Buffer, doc []byte) { + dec := json.NewDecoder(bytes.NewReader(doc)) + dec.UseNumber() + var walk func() + walk = func() { + tok, err := dec.Token() + if err != nil { + return + } + switch t := tok.(type) { + case json.Delim: + if t == '{' || t == '[' { + for dec.More() { + walk() + } + _, _ = dec.Token() // consume the closing delimiter + } + case string: + buf.WriteString(t) + buf.WriteByte('\n') + } + } + walk() +} + // jsonLineSpans returns the byte range of every non-empty line in content, // excluding its trailing CR/LF framing. func jsonLineSpans(content []byte) []recordSpan { @@ -375,35 +436,37 @@ func lineBounded(data []byte, start, end int) bool { // keeps member order and duplicate keys, so a secret in an earlier, overwritten // value is still found, and a secret spanning JSON framing stays visible in the // rewritten bytes. -func rewriteJSONTokens(doc []byte, p *Pipeline) ([]byte, []Finding, error) { +func rewriteJSONTokens(doc []byte, p *Pipeline) ([]byte, []Finding, *jsonProvenance, error) { dec := json.NewDecoder(bytes.NewReader(doc)) dec.UseNumber() var ( buf bytes.Buffer findings []Finding ) - if err := writeSanitizedJSONValue(dec, &buf, p, &findings, ""); err != nil { - return nil, nil, fmt.Errorf("could not tokenize JSON: %w", err) + prov := &jsonProvenance{} + if err := writeSanitizedJSONValue(dec, &buf, p, &findings, prov, ""); err != nil { + return nil, nil, nil, fmt.Errorf("could not tokenize JSON: %w", err) } if _, err := dec.Token(); !errors.Is(err, io.EOF) { - return nil, nil, fmt.Errorf("unexpected trailing JSON content") + return nil, nil, nil, fmt.Errorf("unexpected trailing JSON content") } - return buf.Bytes(), findings, nil + return buf.Bytes(), findings, prov, nil } // writeSanitizedJSONValue writes one JSON value to buf, sanitizing object keys // and scalar leaves as it goes. memberKey is the enclosing object key when the // value is an object member, so sensitive-key masking still applies; it is // empty for array elements and the top-level value. -func writeSanitizedJSONValue(dec *json.Decoder, buf *bytes.Buffer, p *Pipeline, findings *[]Finding, memberKey string) error { +func writeSanitizedJSONValue(dec *json.Decoder, buf *bytes.Buffer, p *Pipeline, findings *[]Finding, prov *jsonProvenance, memberKey string) error { tok, err := dec.Token() if err != nil { return err } switch t := tok.(type) { case json.Delim: - return writeSanitizedJSONContainer(dec, buf, p, findings, t) + return writeSanitizedJSONContainer(dec, buf, p, findings, prov, t) case string: + prov.addString(t) sanitized, stringFindings := sanitizeJSONString(t, memberKey, p) *findings = append(*findings, stringFindings...) return writeJSONString(buf, sanitized) @@ -440,7 +503,7 @@ type jsonMember struct { // writeSanitizedJSONContainer writes the members of an object or array, // preserving member order and duplicate keys. -func writeSanitizedJSONContainer(dec *json.Decoder, buf *bytes.Buffer, p *Pipeline, findings *[]Finding, delim json.Delim) error { +func writeSanitizedJSONContainer(dec *json.Decoder, buf *bytes.Buffer, p *Pipeline, findings *[]Finding, prov *jsonProvenance, delim json.Delim) error { switch delim { case '{': var members []jsonMember @@ -453,10 +516,11 @@ func writeSanitizedJSONContainer(dec *json.Decoder, buf *bytes.Buffer, p *Pipeli if !ok { return fmt.Errorf("JSON object key is %T, want string", keyTok) } + prov.addString(key) sanitizedKey, keyFindings := sanitizeJSONKey(key, p) *findings = append(*findings, keyFindings...) var rendered bytes.Buffer - if err := writeSanitizedJSONValue(dec, &rendered, p, findings, sanitizedKey); err != nil { + if err := writeSanitizedJSONValue(dec, &rendered, p, findings, prov, sanitizedKey); err != nil { return err } members = append(members, jsonMember{ @@ -489,7 +553,7 @@ func writeSanitizedJSONContainer(dec *json.Decoder, buf *bytes.Buffer, p *Pipeli if !first { buf.WriteByte(',') } - if err := writeSanitizedJSONValue(dec, buf, p, findings, ""); err != nil { + if err := writeSanitizedJSONValue(dec, buf, p, findings, prov, ""); err != nil { return err } first = false diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 392180ed56..bc099fa7ed 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -624,6 +624,51 @@ func TestSanitizeJSONLines_SensitiveBeginRecordFailsClosed(t *testing.T) { } } +// TestSanitizeJSONDocument_EscapedLeafBlockDoesNotExemptSplitBlock pins that an +// escaped-marker leaf block cannot stand in for a separate block that spans +// members: the escaped block is visible only after JSON decoding, so raw-byte +// and decoded finding counts are not comparable. +func TestSanitizeJSONDocument_EscapedLeafBlockDoesNotExemptSplitBlock(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + escapedBegin := `\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + doc := []byte(`{"note":"` + escapedBegin + `\nMIIEleafkeymaterial\n` + end + `",` + + `"key_start":"` + begin + `","payload":"MIIEspanningkeymaterial","tail":"` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial", "the spanning block must not survive") + assert.NotContains(t, string(out), "MIIEleafkeymaterial", "the escaped leaf block must be redacted") + assert.Contains(t, string(out), "output removed") +} + +// TestSanitizeJSONLines_EscapedBeginRecordFailsClosed pins that a cross-record +// block is recognized even when its BEGIN marker is written with \u escapes in +// the original record bytes. +func TestSanitizeJSONLines_EscapedBeginRecordFailsClosed(t *testing.T) { + p := OutputPipeline() + end := "-----END RSA" + " PRIVATE KEY-----" + content := []byte(`{"key_start":"\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + `"}` + "\n" + + `{"payload":"MIIEspanningkeymaterial"}` + "\n" + + `{"tail":"` + end + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial") + assert.NotContains(t, string(out), "END RSA") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + // TestSanitizeJSONDocument_LeavesUnsupportedInputAlone pins the fallback // contract for documents the structural path cannot handle. func TestSanitizeJSONDocument_LeavesUnsupportedInputAlone(t *testing.T) { From 8e382edcfc318b0bc5cdd431e00fe8b6f5e4817b Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 19 Nov 2026 14:11:41 -0500 Subject: [PATCH 21/51] fix(cli): keep the audit trail when the output scan fails MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The post-agent output scan returned straight out of runAgent on failure, so a run whose sanitized output could not be written skipped the sandbox findings download and the audit hash-chain verification — exactly the runs whose audit trail matters most. The collection now lives in collectPostScanSecurityArtifacts, which runs after a failed scan too and returns the scan error (wrapped) joined with any chain error. preserveTrailingNewline also stripped only \n before appending the source framing, so a CRLF document came back with a duplicated carriage return ({...}\r\r\n) on both the unchanged and the rewritten path. It now strips the whole CRLF pair before restoring the document's own ending. Regression tests: - TestCollectPostScanSecurityArtifactsRunsOnScanFailure - TestSanitizeJSONDocument_CRLFNoStrayCarriageReturn Signed-off-by: anevans --- internal/cli/run.go | 75 ++++++++++++++++---------- internal/cli/run_postscan_test.go | 35 ++++++++++++ internal/security/jsonsanitize.go | 2 +- internal/security/jsonsanitize_test.go | 18 +++++++ 4 files changed, 101 insertions(+), 29 deletions(-) create mode 100644 internal/cli/run_postscan_test.go diff --git a/internal/cli/run.go b/internal/cli/run.go index 4274387852..096c29caa5 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -3484,34 +3484,14 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // 9f. Post-agent output scan — redact secrets from extracted output. if h.SecurityEnabled() { printer.StepStart("Running post-agent output scan") - if err := scanOutputFiles(runDir, securityTraceID, progressVerbosity, printer); err != nil { - printer.StepFail(failureLine("Output scan failed", err, progressVerbosity)) - return fmt.Errorf("post-agent output scan failed: %w", err) + scanErr := scanOutputFiles(runDir, securityTraceID, progressVerbosity, printer) + if scanErr != nil { + printer.StepFail(failureLine("Output scan failed", scanErr, progressVerbosity)) } - - // Extract sandbox-side security findings for audit trail. - findingsDir := filepath.Join(runDir, "security") - if err := os.MkdirAll(findingsDir, 0o755); err == nil { - remoteFindingsDir := sandbox.SandboxWorkspace + "/.security/" - if dlErr := sandbox.Download(sandboxName, remoteFindingsDir, findingsDir); dlErr != nil { - printer.StepInfo("No sandbox security findings to extract") - } else { - printer.StepDone("Security findings extracted") - } - } - - findingsJSONL := filepath.Join(runDir, "security", "findings.jsonl") - if _, statErr := os.Stat(findingsJSONL); statErr == nil { - cv, verifyErr := security.VerifyChain(findingsJSONL) - if verifyErr != nil { - printer.StepWarn(failureLine("Audit log verification error", verifyErr, progressVerbosity)) - } else if !cv.Valid { - line, chainErr := auditChainFailure(cv.BrokenMsg, progressVerbosity) - printer.StepFail(line) - return chainErr - } else if cv.Entries > 0 { - printer.StepDone(fmt.Sprintf("Audit log integrity verified (%d entries)", cv.Entries)) - } + // Collect the sandbox audit trail even when the scan failed: those runs + // are the ones where it matters most. + if err := collectPostScanSecurityArtifacts(runDir, sandboxName, printer, progressVerbosity, scanErr); err != nil { + return err } } @@ -7248,7 +7228,46 @@ func writeFailure(quiet bool, relPath string, writeErr error, unwritable *int) e return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) } -// injectTraceID appends the FULLSEND_TRACE_ID to the sandbox .env file. +// downloadSandboxFindings extracts the sandbox-side findings directory. It is a +// variable so tests can observe the ordering contract of +// collectPostScanSecurityArtifacts without a sandbox. +var downloadSandboxFindings = sandbox.Download + +// collectPostScanSecurityArtifacts extracts the sandbox-side security findings +// and verifies the audit hash chain. scanErr is the outcome of the host output +// scan; it is returned after the audit trail has been collected, so a failed +// scan never skips the artifacts that explain the failure. +func collectPostScanSecurityArtifacts(runDir, sandboxName string, printer *ui.Printer, progressVerbosity string, scanErr error) error { + findingsDir := filepath.Join(runDir, "security") + if err := os.MkdirAll(findingsDir, 0o755); err == nil { + remoteFindingsDir := sandbox.SandboxWorkspace + "/.security/" + if dlErr := downloadSandboxFindings(sandboxName, remoteFindingsDir, findingsDir); dlErr != nil { + printer.StepInfo("No sandbox security findings to extract") + } else { + printer.StepDone("Security findings extracted") + } + } + var chainErr error + findingsJSONL := filepath.Join(runDir, "security", "findings.jsonl") + if _, statErr := os.Stat(findingsJSONL); statErr == nil { + cv, verifyErr := security.VerifyChain(findingsJSONL) + switch { + case verifyErr != nil: + printer.StepWarn(failureLine("Audit log verification error", verifyErr, progressVerbosity)) + case !cv.Valid: + line, err := auditChainFailure(cv.BrokenMsg, progressVerbosity) + printer.StepFail(line) + chainErr = err + case cv.Entries > 0: + printer.StepDone(fmt.Sprintf("Audit log integrity verified (%d entries)", cv.Entries)) + } + } + if scanErr != nil { + scanErr = fmt.Errorf("post-agent output scan failed: %w", scanErr) + } + return errors.Join(scanErr, chainErr) +} + func injectTraceID(sandboxName, traceID string) error { if !security.IsShellSafeTraceID(traceID) { return fmt.Errorf("invalid trace ID format: %q", traceID) diff --git a/internal/cli/run_postscan_test.go b/internal/cli/run_postscan_test.go new file mode 100644 index 0000000000..453026d259 --- /dev/null +++ b/internal/cli/run_postscan_test.go @@ -0,0 +1,35 @@ +package cli + +import ( + "bytes" + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// TestCollectPostScanSecurityArtifactsRunsOnScanFailure pins that a failed host +// output scan still extracts the sandbox audit trail and still reports the scan +// failure. +func TestCollectPostScanSecurityArtifactsRunsOnScanFailure(t *testing.T) { + runDir := t.TempDir() + var downloaded bool + original := downloadSandboxFindings + downloadSandboxFindings = func(_, _, _ string) error { + downloaded = true + return nil + } + t.Cleanup(func() { downloadSandboxFindings = original }) + + var buf bytes.Buffer + scanErr := errors.New("could not write sanitized output file") + err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), "", scanErr) + + require.Error(t, err) + assert.True(t, downloaded, "sandbox findings must be extracted even when the scan failed") + assert.Contains(t, err.Error(), "post-agent output scan failed") + assert.Contains(t, buf.String(), "Security findings extracted") +} diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 0dec93fb37..5cc3348aa4 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -115,7 +115,7 @@ func (v *jsonProvenance) spanningBlocks() int { // restores the document's own trailing newline, so a rewrite never changes the // file's line framing. func preserveTrailingNewline(encoded, doc []byte) []byte { - encoded = bytes.TrimRight(encoded, "\n") + encoded = bytes.TrimRight(encoded, "\r\n") switch { case bytes.HasSuffix(doc, []byte("\r\n")): return append(encoded, '\r', '\n') diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index bc099fa7ed..71ac61dc28 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -669,6 +669,24 @@ func TestSanitizeJSONLines_EscapedBeginRecordFailsClosed(t *testing.T) { } } +// TestSanitizeJSONDocument_CRLFNoStrayCarriageReturn pins that trailing CRLF +// framing is reproduced exactly, without a duplicated carriage return, on the +// unchanged and rewritten paths. +func TestSanitizeJSONDocument_CRLFNoStrayCarriageReturn(t *testing.T) { + p := OutputPipeline() + for name, doc := range map[string]string{ + "clean": "{\"a\":\"x\"}\r\n", + "secret": "{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\r\n", + } { + t.Run(name, func(t *testing.T) { + out, _, err := SanitizeJSONDocument([]byte(doc), p) + require.NoError(t, err) + assert.NotContains(t, string(out), "\r\r", "no stray carriage return") + assert.True(t, strings.HasSuffix(string(out), "}\r\n"), "CRLF framing must be preserved: %q", out) + }) + } +} + // TestSanitizeJSONDocument_LeavesUnsupportedInputAlone pins the fallback // contract for documents the structural path cannot handle. func TestSanitizeJSONDocument_LeavesUnsupportedInputAlone(t *testing.T) { From e372d373ad043d00f0cfd45e7eb83e84df8557bb Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 19 Nov 2026 14:43:03 -0500 Subject: [PATCH 22/51] fix(security): check decoded private keys on every document The framing-spanning private-key check ran only when a leaf had already produced a finding. A block split across members or array elements with \u-escaped markers produces no leaf finding, because no leaf holds a complete BEGIN..END pair, so the check was skipped and the document was returned unchanged: the serialized scan cannot match escaped markers either. The decoded-view check now runs unconditionally. The view is also normalized with the same Unicode normalizer the leaf scan uses, so a marker obfuscated with a zero-width or bidi character is matched the same way the per-leaf scan matches it, rather than being invisible to both. Regression tests: - TestSanitizeJSONDocument_EscapedMarkersAcrossMembersFailsClosed - TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersFailsClosed Signed-off-by: anevans --- internal/security/jsonsanitize.go | 35 +++++++++++++++----------- internal/security/jsonsanitize_test.go | 35 ++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 15 deletions(-) diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 5cc3348aa4..20ad3b670d 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -52,20 +52,19 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { out := doc if len(findings) > 0 { out = rebuilt - // Masking a member value can hide a private-key block that spans - // members: a sensitive member name masks the BEGIN marker, leaving the - // key body and END marker behind in a form the rewritten scan can no - // longer recognize. The decoded view knows whether every block was - // contained in one key or leaf. - if prov.spanningBlocks() > 0 { - return preserveTrailingNewline([]byte(failClosedInvalidJSON), doc), - append(findings, Finding{ - Scanner: "secret_redactor", - Name: "private_key", - Severity: "critical", - Detail: "Private key block spans JSON framing and cannot be localized; output removed", - }), nil - } + } + // A block that spans members is invisible to both the leaf scan and the + // written-bytes scan once a member is masked, and its markers may be + // \u-escaped in the raw bytes. The decoded view is the only place it is + // visible, so it is consulted whether or not a leaf produced a finding. + if prov.spanningBlocks() > 0 { + return preserveTrailingNewline([]byte(failClosedInvalidJSON), doc), + append(findings, Finding{ + Scanner: "secret_redactor", + Name: "private_key", + Severity: "critical", + Detail: "Private key block spans JSON framing and cannot be localized; output removed", + }), nil } // Scan the bytes that will actually be written. The walk above already // scanned every decoded key and leaf, so a match here spans JSON framing @@ -97,9 +96,15 @@ type jsonProvenance struct { leafCount int } +// decodedViewNormalizer normalizes decoded JSON text before it is matched for +// framing-spanning secrets, so a marker obfuscated with zero-width or bidi +// characters is normalized exactly as the per-leaf scan normalizes it. +var decodedViewNormalizer = NewUnicodeNormalizer() + // addString appends one decoded key or string leaf to the view and counts the // private-key blocks it fully contains. func (v *jsonProvenance) addString(s string) { + s = decodedViewNormalizer.Scan(s).Sanitized v.leafCount += len(privateKeyRe.FindAllIndex([]byte(s), -1)) v.decoded.WriteString(s) v.decoded.WriteByte('\n') @@ -322,7 +327,7 @@ func writeDecodedJSONView(buf *bytes.Buffer, doc []byte) { _, _ = dec.Token() // consume the closing delimiter } case string: - buf.WriteString(t) + buf.WriteString(decodedViewNormalizer.Scan(t).Sanitized) buf.WriteByte('\n') } } diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 71ac61dc28..6fc8a47add 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -687,6 +687,41 @@ func TestSanitizeJSONDocument_CRLFNoStrayCarriageReturn(t *testing.T) { } } +// TestSanitizeJSONDocument_EscapedMarkersAcrossMembersFailsClosed pins that a +// block spanning members is detected even when no leaf produces a finding and +// the markers are \u-escaped in the raw bytes. +func TestSanitizeJSONDocument_EscapedMarkersAcrossMembersFailsClosed(t *testing.T) { + p := OutputPipeline() + end := "-----END RSA" + " PRIVATE KEY-----" + doc := []byte(`["\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + + `","MIIEspanningkeymaterial","` + end + `"]`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial") + assert.Contains(t, string(out), "output removed") +} + +// TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersFailsClosed pins that +// the decoded view applies the same Unicode normalization as the leaf scan, so +// a marker obfuscated with a zero-width character cannot hide a spanning block. +func TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersFailsClosed(t *testing.T) { + p := OutputPipeline() + end := "-----END RSA" + " PRIVATE KEY-----" + // U+200B inside the BEGIN marker: not a PEM block in any single form. + doc := []byte(`{"begin":"-----\u200bBEGIN RSA` + " PRIVATE KEY-----\"" + + `,"payload":"MIIEspanningkeymaterial","end":"` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial") + assert.Contains(t, string(out), "output removed") +} + // TestSanitizeJSONDocument_LeavesUnsupportedInputAlone pins the fallback // contract for documents the structural path cannot handle. func TestSanitizeJSONDocument_LeavesUnsupportedInputAlone(t *testing.T) { From 72dc4c38497dea2733673957527a8a9ef4de8a28 Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 19 Nov 2026 14:57:47 -0500 Subject: [PATCH 23/51] fix(security): bound JSONL localization and drop unredacted leftovers Three defects in the new fail-closed paths: spanningBlocks compared the number of blocks in the decoded view with the number contained in a single leaf. A lazy match can start at one leaf's BEGIN and end at another leaf's END, and that match then cancelled out a complete leaf block: a document with an unterminated BEGIN and key body in one member plus a complete block in the next reported no spanning block and was written unchanged. Containment is now judged per match against the leaf ranges. failClosedRecordSpans replaced every record in a JSONL stream as soon as any two records were identical, even when the change was nowhere near them. Identical records are common in transcripts, so a single cross-record finding discarded the whole file. The ambiguity now only applies inside the changed region, and only to a record that repeats there; records outside it are copied through, and a repeating record becomes a marker only when it is covered. A file whose sanitized content could not be written kept its unredacted bytes on disk, and artifacts are uploaded even when a run fails, so the secret could still ship. The file is now replaced with a valid fail-closed marker (or removed if that fails) before the error is recorded. The contributor and user guides are corrected to match: the walk skips any directory named security, and an unwritable file is replaced by a marker. Regression tests: - TestSanitizeJSONDocument_UnterminatedBeginBeforeCompleteBlockFailsClosed - TestSanitizeJSONLines_RepeatedRecordsFailsClosed (now also pins that duplicates outside the change survive) - TestScanOutputFiles_WriteFailureRemovesUnredactedBytes Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 8 ++- .../user/run-artifacts-and-private-data.md | 3 +- internal/cli/run.go | 17 +++-- internal/cli/scan_output_telemetry_test.go | 20 ++++++ internal/security/jsonsanitize.go | 67 ++++++++++++++----- internal/security/jsonsanitize_test.go | 28 ++++++-- 6 files changed, 116 insertions(+), 27 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index c8654744cf..5e48963d6a 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -615,8 +615,9 @@ origins and warnings are documented in ### The post-run output scan `scanOutputFiles` runs the output pipeline (Unicode normalization, then secret -redaction) over every file under `output/` except the skips above and -`security/findings.jsonl`. Valid JSON is sanitized structurally so redaction +redaction) over every file under `output/` except the skips above, any +directory named `security` (which holds `findings.jsonl`), and the telemetry +JSONL. Valid JSON is sanitized structurally so redaction never changes its syntax: every object key and scalar leaf is scanned individually through a token-preserving walk that keeps member order and duplicate keys, so an earlier value that map decoding would drop is still @@ -645,7 +646,8 @@ like `{"error":"output removed because …"}` and are logged as findings in A sanitized file that cannot be written does not stop the walk: every remaining file is still scanned and redacted, and the run fails closed -afterwards with all write errors joined. In `quiet` mode the affected paths +afterwards with all write errors joined. The file itself is replaced with a +fail-closed marker so the unredacted bytes never reach the uploaded artifact. In `quiet` mode the affected paths are counted, not named (ADR 0163). ## Agent rule layering diff --git a/docs/guides/user/run-artifacts-and-private-data.md b/docs/guides/user/run-artifacts-and-private-data.md index 752ba15233..4b36f99115 100644 --- a/docs/guides/user/run-artifacts-and-private-data.md +++ b/docs/guides/user/run-artifacts-and-private-data.md @@ -347,7 +347,8 @@ download the artifact until it expires. The output scan masks secret literals; it does not remove personal data, customer names or other private business text. When a secret cannot be masked without breaking a file's JSON structure, the affected JSON document or JSONL record is replaced with a JSON -error marker, and a sanitized file that cannot be written fails the run. +error marker, a file whose redacted content cannot be written is replaced by +such a marker, and the run itself fails. `fullsend run` leaves `output/` untouched. At the end of the job, `fullsend prepare-artifacts` builds a filtered copy at the level you set, and diff --git a/internal/cli/run.go b/internal/cli/run.go index 096c29caa5..26b1a5597b 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7131,7 +7131,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri }) } if writeErr := writeFile(path, out, 0o644); writeErr != nil { - writeErrs = append(writeErrs, writeFailure(quiet, relPath, writeErr, &unwritable)) + writeErrs = append(writeErrs, writeFailure(quiet, path, relPath, writeErr, &unwritable)) } } return nil @@ -7157,7 +7157,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri }) } if writeErr := writeFile(path, out, 0o644); writeErr != nil { - writeErrs = append(writeErrs, writeFailure(quiet, relPath, writeErr, &unwritable)) + writeErrs = append(writeErrs, writeFailure(quiet, path, relPath, writeErr, &unwritable)) } } return nil @@ -7191,7 +7191,7 @@ 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 { - writeErrs = append(writeErrs, writeFailure(quiet, relPath, writeErr, &unwritable)) + writeErrs = append(writeErrs, writeFailure(quiet, path, relPath, writeErr, &unwritable)) } } return nil @@ -7220,14 +7220,23 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri // writeFailure records a sanitized-output write error. At the quiet progress // level the path is withheld because it can carry an agent-chosen name // (ADR 0163); non-quiet callers name it. -func writeFailure(quiet bool, relPath string, writeErr error, unwritable *int) error { +func writeFailure(quiet bool, path, relPath string, writeErr error, unwritable *int) error { *unwritable++ + // The unredacted bytes must not reach the uploaded artifact, so replace the + // file with a valid fail-closed marker; remove it if even that fails. + if err := os.WriteFile(path, []byte(unwritableOutputMarker), 0o644); err != nil { + _ = os.Remove(path) + } if quiet { return fmt.Errorf("could not write sanitized output file") } return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) } +// unwritableOutputMarker replaces a file whose sanitized content could not be +// written. It is valid JSON so downstream parsers keep working. +const unwritableOutputMarker = `{"error":"output removed because it could not be redacted"}` + // downloadSandboxFindings extracts the sandbox-side findings directory. It is a // variable so tests can observe the ordering contract of // collectPostScanSecurityArtifacts without a sandbox. diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 7b7ce21f74..2740987fc1 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -461,3 +461,23 @@ func TestScanOutputFiles_NumericRuntimeSecretRedacted(t *testing.T) { require.Len(t, lines, 1) assert.True(t, json.Valid([]byte(lines[0]))) } + +// TestScanOutputFiles_WriteFailureRemovesUnredactedBytes pins that a file whose +// sanitized content cannot be written is replaced with a fail-closed marker, so +// the unredacted bytes cannot reach the uploaded artifact. +func TestScanOutputFiles_WriteFailureRemovesUnredactedBytes(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "secret.txt") + const secret = "ghp_FAKEtesttoken000000000000000000000000" + require.NoError(t, os.WriteFile(path, []byte("Token: "+secret), 0o644)) + + err := scanOutputFilesWithWriter(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { + return os.ErrPermission + }) + require.Error(t, err) + + got, readErr := os.ReadFile(path) + require.NoError(t, readErr) + assert.NotContains(t, string(got), secret, "the unredacted bytes must not survive a write failure") + assert.JSONEq(t, `{"error":"output removed because it could not be redacted"}`, string(got)) +} diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 20ad3b670d..8379e067f0 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -92,8 +92,8 @@ var privateKeyRe = func() *regexp.Regexp { // marker with \u escapes, and masking a sensitive member removes the BEGIN // marker before the rewritten document is scanned. type jsonProvenance struct { - decoded bytes.Buffer - leafCount int + decoded bytes.Buffer + ranges []recordSpan } // decodedViewNormalizer normalizes decoded JSON text before it is matched for @@ -105,15 +105,31 @@ var decodedViewNormalizer = NewUnicodeNormalizer() // private-key blocks it fully contains. func (v *jsonProvenance) addString(s string) { s = decodedViewNormalizer.Scan(s).Sanitized - v.leafCount += len(privateKeyRe.FindAllIndex([]byte(s), -1)) + start := v.decoded.Len() v.decoded.WriteString(s) v.decoded.WriteByte('\n') + v.ranges = append(v.ranges, recordSpan{start: start, end: v.decoded.Len() - 1}) } -// spanningBlocks reports how many private-key blocks exist in the decoded view -// that no single key or leaf contains. +// spanningBlocks reports how many private-key blocks in the decoded view are +// not contained in a single key or leaf. Containment is checked per match: a +// lazy pattern can start at one leaf's BEGIN and end at another leaf's END, and +// counting differences would let that match cancel out a complete leaf block. func (v *jsonProvenance) spanningBlocks() int { - return len(privateKeyRe.FindAllIndex(v.decoded.Bytes(), -1)) - v.leafCount + count := 0 + for _, match := range privateKeyRe.FindAllIndex(v.decoded.Bytes(), -1) { + contained := false + for _, r := range v.ranges { + if r.start <= match[0] && match[1] <= r.end { + contained = true + break + } + } + if !contained { + count++ + } + } + return count } // preserveTrailingNewline drops the newline json.Encoder always appends and @@ -372,13 +388,12 @@ func jsonLineSpans(content []byte) []recordSpan { func failClosedRecordSpans(stream []byte, spans []recordSpan, scan ScanResult) []byte { sanitized := []byte(scan.Sanitized) - seen := make(map[string]struct{}, len(spans)) + // Changes are confined to the region that differs between the stream and + // the redacted stream, so records outside it were not touched. + start, end := changedRegion(stream, sanitized) + counts := make(map[string]int, len(spans)) for _, span := range spans { - record := string(stream[span.start:span.end]) - if _, ok := seen[record]; ok { - return replaceRecordSpans(stream, spans) - } - seen[record] = struct{}{} + counts[string(stream[span.start:span.end])]++ } var out bytes.Buffer @@ -386,10 +401,16 @@ func failClosedRecordSpans(stream []byte, spans []recordSpan, scan ScanResult) [ searchFrom := 0 for _, span := range spans { record := stream[span.start:span.end] + if span.end <= start || span.start >= end { + // Outside the changed region: the bytes are untouched. + out.Write(stream[cursor:span.end]) + cursor = span.end + continue + } idx := bytes.Index(sanitized[searchFrom:], record) - // A surviving copy must be a whole record, not a substring of a longer - // record that happens to contain the same bytes. - if idx >= 0 && lineBounded(sanitized, searchFrom+idx, searchFrom+idx+len(record)) { + // A surviving copy must be a whole record, and it must be the only copy: + // otherwise a later untouched duplicate can stand in for a covered one. + if counts[string(record)] == 1 && idx >= 0 && lineBounded(sanitized, searchFrom+idx, searchFrom+idx+len(record)) { searchFrom += idx + len(record) out.Write(stream[cursor:span.end]) cursor = span.end @@ -406,6 +427,22 @@ func failClosedRecordSpans(stream []byte, spans []recordSpan, scan ScanResult) [ return out.Bytes() } +// changedRegion returns the half-open byte range that differs between a and b. +// It is approximate for length-changing edits, which is enough: it is used as an +// upper bound on the bytes a redaction touched. +func changedRegion(a, b []byte) (int, int) { + limit := min(len(a), len(b)) + start := 0 + for start < limit && a[start] == b[start] { + start++ + } + end := 0 + for end < limit-start && a[len(a)-1-end] == b[len(b)-1-end] { + end++ + } + return start, len(a) - end +} + // replaceRecordSpans replaces every record with a valid marker when the // records a match covers cannot be identified unambiguously. func replaceRecordSpans(stream []byte, spans []recordSpan) []byte { diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 6fc8a47add..53dd32554a 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -349,7 +349,8 @@ func TestSanitizeJSONDocument_CleanKeyWinsSanitizedCollision(t *testing.T) { // TestSanitizeJSONLines_RepeatedRecordsFailsClosed pins that a cross-record // match is not localized by a substring search a repeated record can fool. A // later untouched copy must never stand in for a covered record: keeping the -// original bytes would write the spanning secret back out. +// original bytes would write the spanning secret back out. Duplicates outside +// the changed region are still preserved. func TestSanitizeJSONLines_RepeatedRecordsFailsClosed(t *testing.T) { ResetRuntimeSecretsForTest() t.Cleanup(ResetRuntimeSecretsForTest) @@ -368,14 +369,16 @@ func TestSanitizeJSONLines_RepeatedRecordsFailsClosed(t *testing.T) { require.NoError(t, err) require.NotEmpty(t, findings) assert.NotContains(t, string(out), secret, "the spanning secret must not be reassembled") - assert.NotContains(t, string(out), `{"v":"aaa"}`, "ambiguous localization must fail closed") lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") require.Len(t, lines, 5, "record count must not change") - for _, line := range lines { - assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + for _, line := range lines[:2] { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) assert.Contains(t, line, "output removed") } + assert.Equal(t, `{"v":"aaa"}`, lines[2], "an untouched duplicate outside the change must survive") + assert.Equal(t, `{"v":"ccc"}`, lines[3]) + assert.Equal(t, `{"v":"bbb"}`, lines[4], "an untouched duplicate outside the change must survive") } // TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch pins the @@ -722,6 +725,23 @@ func TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersFailsClosed(t *testi assert.Contains(t, string(out), "output removed") } +// TestSanitizeJSONDocument_UnterminatedBeginBeforeCompleteBlockFailsClosed pins +// that a lazy match starting at one leaf's BEGIN and ending at another leaf's +// END cannot cancel out a complete leaf block: containment is judged per match. +func TestSanitizeJSONDocument_UnterminatedBeginBeforeCompleteBlockFailsClosed(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + doc := []byte(`{"a":"` + begin + `\nMIIEfirstkeymaterial","b":"` + begin + `\nZZZZZZZZ\n` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEfirstkeymaterial", "the unterminated block must not survive") + assert.Contains(t, string(out), "output removed") +} + // TestSanitizeJSONDocument_LeavesUnsupportedInputAlone pins the fallback // contract for documents the structural path cannot handle. func TestSanitizeJSONDocument_LeavesUnsupportedInputAlone(t *testing.T) { From 477e59e041e20bb59d711cd3e9cce1fb0bb55843 Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 19 Nov 2026 15:59:06 -0500 Subject: [PATCH 24/51] refactor(security): state the per-record JSONL fail-closed contract 72dc4c384 bounded JSONL localization to the changed region, but two places still described the superseded whole-stream contract: - failClosedRecordSpans' doc comment ended "When that happens the whole stream fails closed." - docs/contributing/runtime-implementation.md said "every record fails closed" when the covered records could not be identified unambiguously. replaceRecordSpans implemented that old all-or-nothing contract and has had no caller since 72dc4c384, so the helper suggested a path that no longer exists and the contributor doc promised behaviour the code does not have. Delete the helper and describe what the code does: inside the changed region a record is kept only when its bytes are unique in the stream and reappear as a whole newline-delimited record in the redacted stream, because a repeated record could otherwise let an untouched copy stand in for the covered one; records outside the changed region, duplicates included, are copied through. No behaviour change: the pinned tests TestSanitizeJSONLines_RepeatedRecordsFailsClosed, TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch and TestSanitizeJSONLines_DisjointCrossRecordMatchesKeepCleanRecord already assert exactly this. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 9 ++++--- internal/security/jsonsanitize.go | 30 +++++++-------------- 2 files changed, 16 insertions(+), 23 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 5e48963d6a..d901f7f104 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -632,9 +632,12 @@ record framing; a secret that spans records cannot be redacted without rewriting that framing, so only the records it covers are replaced. A private-key block spanning records is detected in a decoded view of the stream, before per-record masking can remove its BEGIN marker, so a marker written with -\u escapes is still recognized. When the covered records -cannot be identified unambiguously — their contents also appear elsewhere in -the stream — every record fails closed. +\u escapes is still recognized. Localization inside the changed region is +conservative but per record: a record is kept only when its bytes are unique in +the stream and reappear as a whole line in the redacted stream, because a +repeated record could otherwise let an untouched copy stand in for the covered +one. Records outside the changed region, duplicates included, are copied through +unchanged. Some content cannot be redacted in place. A JSON document or JSONL record is replaced with a valid fail-closed marker instead — never with corrupted diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 8379e067f0..abfd0527b8 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -379,12 +379,16 @@ func jsonLineSpans(content []byte) []recordSpan { // the clean records between them. // // The per-record pass has already handled every match a single record could -// account for, so a remaining match spans a record boundary. Locating the -// records it covers means finding each record's bytes again in the redacted -// stream, which is only trustworthy when every record is distinct: with a -// repeated record, a later untouched copy can stand in for the copy a match -// covered, and the original bytes — carrying part of the secret — would be -// written back. When that happens the whole stream fails closed. +// account for, so a remaining match spans a record boundary. Localization is +// conservative but per record, not all-or-nothing: inside the changed region a +// record is kept only when its bytes are unique in the stream and reappear as a +// whole newline-delimited record in the redacted stream. Locating a covered +// record means finding its bytes again in the redacted stream, which is only +// trustworthy when the record is distinct: with a repeated record, a later +// untouched copy can stand in for the copy a match covered, and the original +// bytes — carrying part of the secret — would be written back. Such a record is +// replaced. Records outside the changed region are copied through, duplicates +// included. func failClosedRecordSpans(stream []byte, spans []recordSpan, scan ScanResult) []byte { sanitized := []byte(scan.Sanitized) @@ -443,20 +447,6 @@ func changedRegion(a, b []byte) (int, int) { return start, len(a) - end } -// replaceRecordSpans replaces every record with a valid marker when the -// records a match covers cannot be identified unambiguously. -func replaceRecordSpans(stream []byte, spans []recordSpan) []byte { - var out bytes.Buffer - cursor := 0 - for _, span := range spans { - out.Write(stream[cursor:span.start]) - out.WriteString(failClosedCrossRecordJSON) - cursor = span.end - } - out.Write(stream[cursor:]) - return out.Bytes() -} - // lineBounded reports whether data[start:end] is a whole newline-delimited // line. func lineBounded(data []byte, start, end int) bool { From 6dca727901f36df2eb022712c80c34b1cf615618 Mon Sep 17 00:00:00 2001 From: anevans Date: Fri, 20 Nov 2026 09:41:41 -0500 Subject: [PATCH 25/51] fix(#5705): localize spanning private keys and gate json_field minimums in runes Review follow-up on #9699. A private-key block whose BEGIN and END markers sit in different JSON members now masks only the members the match covers instead of replacing the whole document. A review that quotes the header in one finding and the footer in another therefore keeps its verdict, and the run no longer loses a replaced result silently: the file-level case is announced as a ::error:: workflow annotation. The cross-member case gets its own fail-closed marker, so the alert states what actually happened. The json_field minimum is now a rune-counted gate applied after the delimiter-escape trim and before the mask is computed, restoring the character semantics of the {8,} quantifier it replaced. The env_assignment, auth_header and db_connection_password cases leave that switch because their patterns already enforce their own minimum. Signed-off-by: anevans --- internal/cli/run.go | 19 +- internal/cli/scan_output_telemetry_test.go | 63 ++++- internal/security/jsonsanitize.go | 264 ++++++++++++++++----- internal/security/jsonsanitize_test.go | 152 ++++++++---- internal/security/redactor.go | 34 +-- internal/security/scanner_test.go | 12 + 6 files changed, 415 insertions(+), 129 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index dd3cef25c2..2ae4e1591b 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7146,6 +7146,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri Phase: "host_output", Finding: f, }) } + alertOnOutputRemoval(printer, out) if writeErr := writeFile(path, out, 0o644); writeErr != nil { writeErrs = append(writeErrs, writeFailure(quiet, path, relPath, writeErr, &unwritable)) } @@ -7172,6 +7173,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri Phase: "host_output", Finding: f, }) } + alertOnOutputRemoval(printer, out) if writeErr := writeFile(path, out, 0o644); writeErr != nil { writeErrs = append(writeErrs, writeFailure(quiet, path, relPath, writeErr, &unwritable)) } @@ -7204,8 +7206,9 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri 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"}` + out = security.OutputRemovalTextJSONMarker } + alertOnOutputRemoval(printer, []byte(out)) if writeErr := writeFile(path, []byte(out), 0o644); writeErr != nil { writeErrs = append(writeErrs, writeFailure(quiet, path, relPath, writeErr, &unwritable)) } @@ -7233,6 +7236,20 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri return nil } +// alertOnOutputRemoval emits a workflow annotation when an output file was +// replaced whole by a fail-closed marker. Everything the agent wrote into that +// file is gone, and a lost review that only shows up as one scan line is the +// silent failure #5705 set out to fix. Only the marker's fixed reason reaches +// the annotation: a file path or a matched value could carry agent-chosen text +// (ADR 0163). +func alertOnOutputRemoval(printer *ui.Printer, sanitized []byte) { + reason, removed := security.OutputRemoval(sanitized) + if !removed || os.Getenv("GITHUB_ACTIONS") != "true" { + return + } + printer.Raw("::error::Output file replaced with a fail-closed marker: " + reason + "\n") +} + // writeFailure records a sanitized-output write error. At the quiet progress // level the path is withheld because it can carry an agent-chosen name // (ADR 0163); non-quiet callers name it. diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 2740987fc1..cfe186e1d1 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -120,7 +120,8 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { 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. + // must still be written as valid JSON, with the masked members carrying + // neither marker. jsonFile8 := filepath.Join(dir, "private_key_and_password.json") validJSON8 := `["see -----BEGIN RSA` + ` PRIVATE KEY----- marker", {"note": "and -----END RSA` + ` PRIVATE KEY----- marker", "password": "a-long-sensitive-value"}]` require.NoError(t, os.WriteFile(jsonFile8, []byte(validJSON8), 0o644)) @@ -133,7 +134,8 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { // 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. + // Structural scanning must not let such a cross-value match corrupt JSON, + // and must mask only the members it covers rather than drop the document. jsonFile7 := filepath.Join(dir, "private_key_markers.json") validJSON7 := `["see -----BEGIN RSA` + ` PRIVATE KEY----- marker", {"note": "and -----END RSA` + ` PRIVATE KEY----- marker"}]` require.NoError(t, os.WriteFile(jsonFile7, []byte(validJSON7), 0o644)) @@ -233,15 +235,19 @@ 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", "cross-value private-key marker must fail closed") + assert.NotContains(t, string(content7), "PRIVATE KEY-----", "both marker members must be masked") + assert.NotContains(t, string(content7), "output removed", "the document must be kept, not dropped") content8, err := os.ReadFile(jsonFile8) require.NoError(t, err) assert.True(t, json.Valid(content8), "backstop handling must preserve valid JSON") - assert.Contains(t, string(content8), "output removed", "cross-value backstop match must fail closed") + assert.NotContains(t, string(content8), "PRIVATE KEY-----", + "masking a password member must not hide the private-key markers") + assert.NotContains(t, string(content8), "output removed", "the document must be kept, not dropped") content9, err := os.ReadFile(jsonFile9) require.NoError(t, err) assert.True(t, json.Valid(content9)) - assert.Contains(t, string(content9), "output removed", "split PEM-like material must fail closed") + assert.NotContains(t, string(content9), "PRIVATE KEY-----", "split PEM-like material must be masked") + assert.NotContains(t, string(content9), "BASE64_KEY_MATERIAL_REDACTED") // jq is the parser implicated by the original incident; exercise it when // available, while keeping the Go validity assertions portable. @@ -313,7 +319,9 @@ func TestScanOutputFiles_JSONLCrossValuePrivateKeyRemainsValid(t *testing.T) { 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") + assert.NotContains(t, line, "PRIVATE KEY-----", "the members carrying the markers must be masked") + assert.NotContains(t, line, "KEY_MATERIAL_BASE64_VALUE_1234567890") + assert.NotContains(t, line, "output removed", "the record must be kept, not dropped") } func TestScanOutputFiles_JSONLRawMultilinePEMRemainsValid(t *testing.T) { @@ -335,6 +343,49 @@ func TestScanOutputFiles_JSONLRawMultilinePEMRemainsValid(t *testing.T) { } } +// TestScanOutputFiles_EmitsAnnotationWhenOutputIsRemoved pins that a whole-file +// fail-closed replacement is announced as a workflow annotation. A review lost to +// redaction must not pass silently: the run still exits 0, so the annotation is +// the only signal an operator gets (#5705). +func TestScanOutputFiles_EmitsAnnotationWhenOutputIsRemoved(t *testing.T) { + const secret = `"v1","k2"` + require.True(t, security.RegisterRuntimeSecret(secret)) + t.Cleanup(security.ResetRuntimeSecretsForTest) + + for name, tc := range map[string]struct { + actions string + want string + }{ + "github actions": { + actions: "true", + want: "::error::Output file replaced with a fail-closed marker: redaction would invalidate JSON", + }, + "local run": {actions: "", want: ""}, + } { + t.Run(name, func(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", tc.actions) + dir := t.TempDir() + path := filepath.Join(dir, "agent-result.json") + // The secret spans the closing quote, comma and next key, so it + // cannot be redacted in place without breaking the document. + require.NoError(t, os.WriteFile(path, []byte(`{"k1":"v1","k2":"v2"}`), 0o644)) + + var output bytes.Buffer + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&output))) + + got, err := os.ReadFile(path) + require.NoError(t, err) + assert.True(t, json.Valid(got), "a replaced file must still be valid JSON: %s", got) + assert.NotContains(t, string(got), secret) + if tc.want == "" { + assert.NotContains(t, output.String(), "::error::") + return + } + assert.Contains(t, output.String(), tc.want) + }) + } +} + func TestScanOutputFiles_QuietJSONFallbackDoesNotPrintPath(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "agent-chosen-secret-name.json") diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index abfd0527b8..2856d15c0c 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -8,16 +8,56 @@ import ( "io" "regexp" "strconv" + "unicode/utf8" ) // JSON output that cannot be redacted without corrupting its structure is // replaced with one of these valid JSON markers so downstream parsers (jq, the // retro and eval tooling) keep working while no secret reaches the artifact. +// Each marker names the reason its content was dropped: the CLI turns that +// reason into an operator alert, because a replaced file loses whatever the +// agent wrote into it (#5705). const ( - failClosedInvalidJSON = `{"error":"output removed because redaction would invalidate JSON"}` - failClosedCrossRecordJSON = `{"error":"output removed because output contained a cross-record secret"}` + failClosedInvalidJSON = `{"error":"output removed because redaction would invalidate JSON"}` + failClosedCrossRecordJSON = `{"error":"output removed because output contained a cross-record secret"}` + failClosedSpansMembersJSON = `{"error":"output removed because a private key block spans JSON framing"}` + + // OutputRemovalTextJSONMarker replaces a whole file whose plain-text + // redaction would leave the JSON it started as syntactically broken. The CLI + // writes it on the fallback path for files the structural path cannot + // handle. + OutputRemovalTextJSONMarker = `{"error":"output removed because text redaction would invalidate JSON"}` ) +// privateKeyMask replaces each JSON key and string leaf that carries part of a +// private-key block spanning JSON framing. +const privateKeyMask = "[REDACTED PRIVATE KEY]" + +// outputRemovalMarkers lists every whole-file removal marker with the reason it +// states. +var outputRemovalMarkers = []struct { + document, reason string +}{ + {failClosedInvalidJSON, "redaction would invalidate JSON"}, + {failClosedCrossRecordJSON, "a secret spanned multiple records"}, + {failClosedSpansMembersJSON, "a private key block spans JSON framing"}, + {OutputRemovalTextJSONMarker, "text redaction would invalidate JSON"}, +} + +// OutputRemoval reports whether sanitized is a whole-file removal marker and +// returns the reason it states. A replaced file loses the content the agent +// wrote into it, so callers alert operators rather than let that loss pass +// silently (#5705). +func OutputRemoval(sanitized []byte) (string, bool) { + trimmed := string(bytes.TrimSpace(sanitized)) + for _, marker := range outputRemovalMarkers { + if trimmed == marker.document { + return marker.reason, true + } + } + return "", false +} + // sensitiveJSONKeyRe matches object keys whose values are masked even when the // value itself does not match a secret pattern. var sensitiveJSONKeyRe = regexp.MustCompile(`(?i)(?:key|token|secret|password|credential|auth)`) @@ -42,7 +82,19 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { if len(trimmed) == 0 || !json.Valid(trimmed) { return doc, nil, nil } - rebuilt, findings, prov, err := rewriteJSONTokens(trimmed, p) + // A block that spans members is invisible to both the leaf scan and the + // written-bytes scan once a member is masked, and its markers may be + // \u-escaped in the raw bytes. The decoded view is the only place it is + // visible, so it is consulted before anything is rewritten. + spans := collectJSONLeaves(trimmed).spanningPrivateKeys() + if spans.unmappable > 0 { + // The view is built from the leaves themselves, so localization should + // never fail. If the walks ever disagree, fail closed rather than write + // bytes that may still carry the block. + return preserveTrailingNewline([]byte(failClosedSpansMembersJSON), doc), + []Finding{privateKeySpanFinding(spans.unmappable, false)}, nil + } + rebuilt, findings, err := rewriteJSONTokens(trimmed, p, spans.covered) if err != nil { // json.Valid accepted the text and the walk uses the same scanner, so // this is a decoder limit rather than a syntax error. Return the error @@ -50,21 +102,11 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { return nil, nil, fmt.Errorf("could not sanitize JSON document: %w", err) } out := doc - if len(findings) > 0 { + if len(findings) > 0 || spans.localized > 0 { out = rebuilt } - // A block that spans members is invisible to both the leaf scan and the - // written-bytes scan once a member is masked, and its markers may be - // \u-escaped in the raw bytes. The decoded view is the only place it is - // visible, so it is consulted whether or not a leaf produced a finding. - if prov.spanningBlocks() > 0 { - return preserveTrailingNewline([]byte(failClosedInvalidJSON), doc), - append(findings, Finding{ - Scanner: "secret_redactor", - Name: "private_key", - Severity: "critical", - Detail: "Private key block spans JSON framing and cannot be localized; output removed", - }), nil + if spans.localized > 0 { + findings = append(findings, privateKeySpanFinding(spans.localized, true)) } // Scan the bytes that will actually be written. The walk above already // scanned every decoded key and leaf, so a match here spans JSON framing @@ -74,6 +116,22 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { return preserveTrailingNewline(sanitizedOut, doc), append(findings, outputFindings...), nil } +// privateKeySpanFinding reports the private-key blocks that span JSON framing. +// localized says whether they were masked in the members that carried them or +// the whole document had to be dropped. +func privateKeySpanFinding(blocks int, localized bool) Finding { + detail := fmt.Sprintf("%d private key block(s) span JSON framing; masked the members carrying them", blocks) + if !localized { + detail = "Private key block spans JSON framing and cannot be localized; output removed" + } + return Finding{ + Scanner: "secret_redactor", + Name: "private_key", + Severity: "critical", + Detail: detail, + } +} + // privateKeyRe is the structural private-key pattern. A block that spans JSON // framing has to be detected on the raw document: running the whole pipeline // first lets a sensitive-named member mask the BEGIN marker and hide it. @@ -101,8 +159,8 @@ type jsonProvenance struct { // characters is normalized exactly as the per-leaf scan normalizes it. var decodedViewNormalizer = NewUnicodeNormalizer() -// addString appends one decoded key or string leaf to the view and counts the -// private-key blocks it fully contains. +// addString appends one decoded key or string leaf to the view and records its +// byte range so a match can be mapped back to the leaves that carry it. func (v *jsonProvenance) addString(s string) { s = decodedViewNormalizer.Scan(s).Sanitized start := v.decoded.Len() @@ -111,25 +169,62 @@ func (v *jsonProvenance) addString(s string) { v.ranges = append(v.ranges, recordSpan{start: start, end: v.decoded.Len() - 1}) } -// spanningBlocks reports how many private-key blocks in the decoded view are -// not contained in a single key or leaf. Containment is checked per match: a -// lazy pattern can start at one leaf's BEGIN and end at another leaf's END, and -// counting differences would let that match cancel out a complete leaf block. -func (v *jsonProvenance) spanningBlocks() int { - count := 0 +// privateKeySpans is the result of looking for private-key blocks that span the +// keys and leaves of one document. +type privateKeySpans struct { + // covered holds the indexes of the keys and leaves that carry part of a + // block spanning more than one of them. + covered map[int]bool + // localized counts the blocks that were mapped onto leaves. + localized int + // unmappable counts the blocks that no leaf range covers. + unmappable int +} + +// spanningPrivateKeys finds the private-key blocks in the decoded view that are +// not contained in a single key or leaf, and maps each one onto the leaves it +// covers. Containment is checked per match: a lazy pattern can start at one +// leaf's BEGIN and end at another leaf's END, and counting differences would let +// that match cancel out a complete leaf block. +// +// A block whose markers sit in different members is not proof that key material +// spans them — a review that quotes the header in one finding and the footer in +// another matches too — so the callers mask only the members the match covers +// and leave the rest of the document (a verdict, a summary) intact. +func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { + spans := privateKeySpans{covered: map[int]bool{}} for _, match := range privateKeyRe.FindAllIndex(v.decoded.Bytes(), -1) { - contained := false - for _, r := range v.ranges { - if r.start <= match[0] && match[1] <= r.end { - contained = true - break + if v.leafContaining(match[0], match[1]) >= 0 { + // A block inside one leaf is that leaf's own scan. + continue + } + var hit []int + for i, r := range v.ranges { + if r.start < match[1] && match[0] < r.end { + hit = append(hit, i) } } - if !contained { - count++ + if len(hit) == 0 { + spans.unmappable++ + continue + } + spans.localized++ + for _, i := range hit { + spans.covered[i] = true } } - return count + return spans +} + +// leafContaining returns the index of the leaf that fully contains [start, end), +// or -1 when no single leaf does. +func (v *jsonProvenance) leafContaining(start, end int) int { + for i, r := range v.ranges { + if r.start <= start && end <= r.end { + return i + } + } + return -1 } // preserveTrailingNewline drops the newline json.Encoder always appends and @@ -161,7 +256,7 @@ func redactJSONOutput(clean []byte, p *Pipeline) ([]byte, []Finding) { // A private-key block spanning values cannot be masked in place // without breaking the surrounding JSON. if finding.Name == "private_key" { - return []byte(failClosedInvalidJSON), res.Findings + return []byte(failClosedSpansMembersJSON), res.Findings } } if res.Sanitized == "" || !json.Valid([]byte(res.Sanitized)) { @@ -326,6 +421,15 @@ func failClosedCrossRecordPrivateKeys(content []byte) ([]byte, []Finding) { // to buf in document order, one per line, so a value split across members is // still visible as one contiguous run of text. func writeDecodedJSONView(buf *bytes.Buffer, doc []byte) { + buf.Write(collectJSONLeaves(doc).decoded.Bytes()) +} + +// collectJSONLeaves walks doc and records every decoded object key and string +// leaf, in document order, in a view where a value split across members reads as +// one contiguous run of text. Each leaf's range in that view is kept so a match +// can be mapped back to the members that carry it. +func collectJSONLeaves(doc []byte) *jsonProvenance { + prov := &jsonProvenance{} dec := json.NewDecoder(bytes.NewReader(doc)) dec.UseNumber() var walk func() @@ -343,11 +447,11 @@ func writeDecodedJSONView(buf *bytes.Buffer, doc []byte) { _, _ = dec.Token() // consume the closing delimiter } case string: - buf.WriteString(decodedViewNormalizer.Scan(t).Sanitized) - buf.WriteByte('\n') + prov.addString(t) } } walk() + return prov } // jsonLineSpans returns the byte range of every non-empty line in content, @@ -467,49 +571,70 @@ func lineBounded(data []byte, start, end int) bool { // scalar value, and renders a valid JSON document. Unlike map decoding it // keeps member order and duplicate keys, so a secret in an earlier, overwritten // value is still found, and a secret spanning JSON framing stays visible in the -// rewritten bytes. -func rewriteJSONTokens(doc []byte, p *Pipeline) ([]byte, []Finding, *jsonProvenance, error) { +// rewritten bytes. Keys and leaves whose index is in masked are replaced whole, +// which is how a framing-spanning private key is neutralized member by member. +func rewriteJSONTokens(doc []byte, p *Pipeline, masked map[int]bool) ([]byte, []Finding, error) { dec := json.NewDecoder(bytes.NewReader(doc)) dec.UseNumber() var ( - buf bytes.Buffer - findings []Finding + buf bytes.Buffer + w = &jsonRewrite{pipeline: p, masked: masked} ) - prov := &jsonProvenance{} - if err := writeSanitizedJSONValue(dec, &buf, p, &findings, prov, ""); err != nil { - return nil, nil, nil, fmt.Errorf("could not tokenize JSON: %w", err) + if err := w.writeValue(dec, &buf, ""); err != nil { + return nil, nil, fmt.Errorf("could not tokenize JSON: %w", err) } if _, err := dec.Token(); !errors.Is(err, io.EOF) { - return nil, nil, nil, fmt.Errorf("unexpected trailing JSON content") + return nil, nil, fmt.Errorf("unexpected trailing JSON content") } - return buf.Bytes(), findings, prov, nil + return buf.Bytes(), w.findings, nil +} + +// jsonRewrite is the state one token walk carries: the pipeline, the findings it +// has collected, and the keys and leaves a framing-spanning private key covers. +type jsonRewrite struct { + pipeline *Pipeline + findings []Finding + masked map[int]bool + // index counts the keys and leaves already walked, in document order, so it + // lines up with the ranges in jsonProvenance. + index int +} + +// nextLeaf advances the leaf cursor and reports whether the key or leaf reached +// must be replaced whole because a framing-spanning private key covers it. +func (w *jsonRewrite) nextLeaf() bool { + masked := w.masked[w.index] + w.index++ + return masked } -// writeSanitizedJSONValue writes one JSON value to buf, sanitizing object keys -// and scalar leaves as it goes. memberKey is the enclosing object key when the -// value is an object member, so sensitive-key masking still applies; it is -// empty for array elements and the top-level value. -func writeSanitizedJSONValue(dec *json.Decoder, buf *bytes.Buffer, p *Pipeline, findings *[]Finding, prov *jsonProvenance, memberKey string) error { +// writeValue writes one JSON value to buf, sanitizing object keys and scalar +// leaves as it goes. memberKey is the enclosing object key when the value is an +// object member, so sensitive-key masking still applies; it is empty for array +// elements and the top-level value. +func (w *jsonRewrite) writeValue(dec *json.Decoder, buf *bytes.Buffer, memberKey string) error { tok, err := dec.Token() if err != nil { return err } switch t := tok.(type) { case json.Delim: - return writeSanitizedJSONContainer(dec, buf, p, findings, prov, t) + return w.writeContainer(dec, buf, t) case string: - prov.addString(t) - sanitized, stringFindings := sanitizeJSONString(t, memberKey, p) - *findings = append(*findings, stringFindings...) + if w.nextLeaf() { + return writeJSONString(buf, privateKeyMask) + } + sanitized, stringFindings := sanitizeJSONString(t, memberKey, w.pipeline) + w.findings = append(w.findings, stringFindings...) return writeJSONString(buf, sanitized) case json.Number: literal := t.String() - res := p.Scan(literal) + res := w.pipeline.Scan(literal) if len(res.Findings) == 0 { buf.WriteString(literal) return nil } - *findings = append(*findings, res.Findings...) + w.findings = append(w.findings, res.Findings...) // A redacted number is no longer a number literal, so write the // replacement as a JSON string to keep the document valid. return writeJSONString(buf, res.Sanitized) @@ -533,9 +658,9 @@ type jsonMember struct { rendered []byte } -// writeSanitizedJSONContainer writes the members of an object or array, -// preserving member order and duplicate keys. -func writeSanitizedJSONContainer(dec *json.Decoder, buf *bytes.Buffer, p *Pipeline, findings *[]Finding, prov *jsonProvenance, delim json.Delim) error { +// writeContainer writes the members of an object or array, preserving member +// order and duplicate keys. +func (w *jsonRewrite) writeContainer(dec *json.Decoder, buf *bytes.Buffer, delim json.Delim) error { switch delim { case '{': var members []jsonMember @@ -548,11 +673,19 @@ func writeSanitizedJSONContainer(dec *json.Decoder, buf *bytes.Buffer, p *Pipeli if !ok { return fmt.Errorf("JSON object key is %T, want string", keyTok) } - prov.addString(key) - sanitizedKey, keyFindings := sanitizeJSONKey(key, p) - *findings = append(*findings, keyFindings...) + masked := w.nextLeaf() + sanitizedKey, keyFindings := sanitizeJSONKey(key, w.pipeline) + if masked { + // The whole key goes: it carried part of a private-key block + // that spans members. + sanitizedKey, keyFindings = privateKeyMask, nil + } + w.findings = append(w.findings, keyFindings...) var rendered bytes.Buffer - if err := writeSanitizedJSONValue(dec, &rendered, p, findings, prov, sanitizedKey); err != nil { + // The original key decides whether the value is sensitive: the mask + // that replaced a key must not drag its value into json_field + // masking. + if err := w.writeValue(dec, &rendered, key); err != nil { return err } members = append(members, jsonMember{ @@ -585,7 +718,7 @@ func writeSanitizedJSONContainer(dec *json.Decoder, buf *bytes.Buffer, p *Pipeli if !first { buf.WriteByte(',') } - if err := writeSanitizedJSONValue(dec, buf, p, findings, prov, ""); err != nil { + if err := w.writeValue(dec, buf, ""); err != nil { return err } first = false @@ -676,13 +809,14 @@ func sanitizeJSONString(value, memberKey string, p *Pipeline) (string, []Finding findings = append(findings, res.Findings...) out = res.Sanitized } - if memberKey != "" && sensitiveJSONKeyRe.MatchString(memberKey) && len(out) >= 8 && !isAlreadyMasked(out) { + if memberKey != "" && sensitiveJSONKeyRe.MatchString(memberKey) && !isAlreadyMasked(out) && + utf8.RuneCountInString(out) >= minJSONFieldLen { masked := Mask(out) findings = append(findings, Finding{ Scanner: "secret_redactor", Name: "json_field", Severity: "high", - Detail: fmt.Sprintf("Redacted json_field (%d chars) -> %s", len(out), masked), + Detail: fmt.Sprintf("Redacted json_field (%d chars) -> %s", utf8.RuneCountInString(out), masked), }) out = masked } diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 53dd32554a..f4f30f479f 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -43,18 +43,20 @@ func TestSanitizeJSONDocument_DuplicateKeysSurviveRewrite(t *testing.T) { assert.NotContains(t, string(out), "ghp_FAKEtesttoken") } -// TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersFailsClosed pins that a -// private key spread over several members is detected in the bytes that are -// actually written. Scanning only the re-encoded form missed it: encoding a map -// sorts keys, and with the END marker sorted before the BEGIN marker the -// pattern no longer matched the original key material. -func TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersFailsClosed(t *testing.T) { +// TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersMasksCoveredMembers pins +// that a private key spread over several members is neutralized member by member +// instead of dropping the whole document. Scanning only the re-encoded form +// missed the block: encoding a map sorts keys, and with the END marker sorted +// before the BEGIN marker the pattern no longer matched the original key +// material. Dropping the document was the other extreme — a review result lost +// its verdict with it (#5705). +func TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersMasksCoveredMembers(t *testing.T) { p := OutputPipeline() begin := "-----BEGIN RSA" + " PRIVATE KEY-----" end := "-----END RSA" + " PRIVATE KEY-----" // Reverse the members' sort order so a map re-encode would emit END before // BEGIN and hide the block from a serialized scan. - doc := []byte(`{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `"}`) + doc := []byte(`{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `","verdict":"approve"}`) out, findings, err := SanitizeJSONDocument(doc, p) require.NoError(t, err) @@ -62,7 +64,36 @@ func TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersFailsClosed(t *testing assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) assert.NotContains(t, string(out), "BEGIN RSA") assert.NotContains(t, string(out), "MIIEpAIBAAKCAQEA") - assert.Contains(t, string(out), "output removed", "an unmappable match must fail closed") + assert.NotContains(t, string(out), "output removed", "the document must be kept, not dropped") + assert.Contains(t, string(out), `"verdict":"approve"`, "a member outside the block must survive") +} + +// TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview pins the +// regression a reviewer found: a review result that quotes the PEM header in one +// finding and the footer in another matches the lazy private-key pattern across +// members, but nothing is hidden and the review still has to be posted. Only the +// members the match covers are masked, so the verdict survives (#5705). +func TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN" + " PRIVATE KEY-----" + end := "-----END" + " PRIVATE KEY-----" + doc := []byte(`{"findings":[{"body":"checks for the ` + begin + ` header"},` + + `{"body":"stops at the ` + end + ` footer"}],"verdict":"approve"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "the cross-member marker pair is still reported") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "output removed", "the review must not be dropped whole") + assert.NotContains(t, string(out), "PRIVATE KEY-----") + + var result struct { + Findings []map[string]string `json:"findings"` + Verdict string `json:"verdict"` + } + require.NoError(t, json.Unmarshal(out, &result), "the sanitized review must still decode: %s", out) + assert.Equal(t, "approve", result.Verdict, "the verdict must survive") + assert.Len(t, result.Findings, 2, "every finding must survive") } // TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed pins that a @@ -85,16 +116,16 @@ func TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed(t *testing assert.NotContains(t, string(out), secret) } -// TestSanitizeJSONDocument_CrossMemberPrivateKeyWithLeafSecretFailsClosed pins -// that a leaf secret and a framing-spanning private key in the same document -// are both handled: the rewrite keeps member order, so the framing-spanning -// block is still visible in the rewritten bytes. -func TestSanitizeJSONDocument_CrossMemberPrivateKeyWithLeafSecretFailsClosed(t *testing.T) { +// TestSanitizeJSONDocument_CrossMemberPrivateKeyWithLeafSecret pins that a leaf +// secret and a framing-spanning private key in the same document are both +// handled: the rewrite keeps member order, and the members carrying the block +// are masked while the rest of the document survives. +func TestSanitizeJSONDocument_CrossMemberPrivateKeyWithLeafSecret(t *testing.T) { p := OutputPipeline() begin := "-----BEGIN RSA" + " PRIVATE KEY-----" end := "-----END RSA" + " PRIVATE KEY-----" doc := []byte(`{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `",` + - `"token":"ghp_FAKEtesttoken000000000000000000000000"}`) + `"token":"ghp_FAKEtesttoken000000000000000000000000","verdict":"approve"}`) out, findings, err := SanitizeJSONDocument(doc, p) require.NoError(t, err) @@ -102,6 +133,7 @@ func TestSanitizeJSONDocument_CrossMemberPrivateKeyWithLeafSecretFailsClosed(t * assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) assert.NotContains(t, string(out), "ghp_FAKEtesttoken") assert.NotContains(t, string(out), "PRIVATE KEY-----") + assert.Contains(t, string(out), `"verdict":"approve"`, "a member outside the block must survive") } // TestSanitizeJSONDocument_DuplicateKeySanitizedKeyCollision pins that a @@ -261,6 +293,47 @@ func TestSanitizeJSONLines_SingleRecordPEMKeepsCleanRecords(t *testing.T) { assert.NotContains(t, lines[1], "MIIEpAIBAAKCAQEA") } +// TestOutputRemoval pins the markers recognized as a whole-file replacement and +// the reason reported for the operator alert. +func TestOutputRemoval(t *testing.T) { + for name, tc := range map[string]struct { + input string + reason string + removed bool + }{ + "invalid json": {failClosedInvalidJSON + "\n", "redaction would invalidate JSON", true}, + "cross-record": {failClosedCrossRecordJSON, "a secret spanned multiple records", true}, + "spans members": {failClosedSpansMembersJSON, "a private key block spans JSON framing", true}, + "text fallback": {OutputRemovalTextJSONMarker + "\r\n", "text redaction would invalidate JSON", true}, + "ordinary doc": {`{"error":"not a removal marker"}`, "", false}, + "not json": {"plain prose", "", false}, + "empty": {"", "", false}, + } { + t.Run(name, func(t *testing.T) { + reason, removed := OutputRemoval([]byte(tc.input)) + assert.Equal(t, tc.removed, removed) + assert.Equal(t, tc.reason, reason) + }) + } +} + +// TestJSONProvenance_UnmappableBlock pins the defensive fallback: a block that no +// recorded leaf range covers is reported as unmappable so the caller fails +// closed instead of writing bytes that may still carry it. +func TestJSONProvenance_UnmappableBlock(t *testing.T) { + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + v := &jsonProvenance{} + v.decoded.WriteString(begin + "\n" + "MIIEkeymaterial" + "\n" + end + "\n") + // One empty leaf, which can never overlap a match. + v.ranges = []recordSpan{{start: 0, end: 0}} + + spans := v.spanningPrivateKeys() + assert.Equal(t, 1, spans.unmappable) + assert.Zero(t, spans.localized) + assert.Empty(t, spans.covered) +} + // TestSanitizeJSONDocument_AlreadyMaskedValueNotRemasked pins that rescanning a // document leaves an existing mask placeholder intact. func TestSanitizeJSONDocument_AlreadyMaskedValueNotRemasked(t *testing.T) { @@ -410,16 +483,16 @@ func TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch(t *testing. assert.Equal(t, `{"value":"middle"}`, lines[3], "the repeated clean record outside the match must survive") } -// TestSanitizeJSONDocument_SensitiveBeginMemberFailsClosed pins that masking a -// member value cannot hide a private-key block that spans members. A +// TestSanitizeJSONDocument_SensitiveBeginMemberMasksBlock pins that masking a +// sensitive member value cannot hide a private-key block that spans members. A // sensitive-named member holding only the BEGIN marker is masked as a -// json_field, which leaves the body and END marker behind; the block must be -// detected in the original framing and fail closed. -func TestSanitizeJSONDocument_SensitiveBeginMemberFailsClosed(t *testing.T) { +// json_field, which would leave the body and END marker behind; the block is +// detected in the original framing and its members are masked. +func TestSanitizeJSONDocument_SensitiveBeginMemberMasksBlock(t *testing.T) { p := OutputPipeline() begin := "-----BEGIN RSA" + " PRIVATE KEY-----" end := "-----END RSA" + " PRIVATE KEY-----" - doc := []byte(`{"key_start":"` + begin + `","payload":"MIIEpAIBAAKCAQEA0123456789abcdef","tail":"` + end + `"}`) + doc := []byte(`{"key_start":"` + begin + `","payload":"MIIEpAIBAAKCAQEA0123456789abcdef","tail":"` + end + `","verdict":"approve"}`) out, findings, err := SanitizeJSONDocument(doc, p) require.NoError(t, err) @@ -427,7 +500,7 @@ func TestSanitizeJSONDocument_SensitiveBeginMemberFailsClosed(t *testing.T) { assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) assert.NotContains(t, string(out), "MIIEpAIBAAKCAQEA", "the key body must not survive") assert.NotContains(t, string(out), "END RSA") - assert.Contains(t, string(out), "output removed") + assert.Contains(t, string(out), `"verdict":"approve"`, "a member outside the block must survive") } // TestSanitizeJSONLines_CleanDuplicateKeyRecordPreserved pins that a clean @@ -569,10 +642,10 @@ func TestLineBounded(t *testing.T) { } } -// TestSanitizeJSONDocument_LeafAndSplitPrivateKeysFailClosed pins that a -// handled leaf block does not exempt a second, framing-spanning block in the -// same document. -func TestSanitizeJSONDocument_LeafAndSplitPrivateKeysFailClosed(t *testing.T) { +// TestSanitizeJSONDocument_LeafAndSplitPrivateKeysMasked pins that a handled +// leaf block does not exempt a second, framing-spanning block in the same +// document, and that neither leaves key material behind. +func TestSanitizeJSONDocument_LeafAndSplitPrivateKeysMasked(t *testing.T) { p := OutputPipeline() begin := "-----BEGIN RSA" + " PRIVATE KEY-----" end := "-----END RSA" + " PRIVATE KEY-----" @@ -585,7 +658,6 @@ func TestSanitizeJSONDocument_LeafAndSplitPrivateKeysFailClosed(t *testing.T) { assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) assert.NotContains(t, string(out), "MIIEspanningkeymaterial") assert.NotContains(t, string(out), "MIIEleafkeymaterial") - assert.Contains(t, string(out), "output removed") } // TestSanitizeJSONLines_SensitiveBeginRecordFailsClosed pins that a @@ -645,7 +717,6 @@ func TestSanitizeJSONDocument_EscapedLeafBlockDoesNotExemptSplitBlock(t *testing assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) assert.NotContains(t, string(out), "MIIEspanningkeymaterial", "the spanning block must not survive") assert.NotContains(t, string(out), "MIIEleafkeymaterial", "the escaped leaf block must be redacted") - assert.Contains(t, string(out), "output removed") } // TestSanitizeJSONLines_EscapedBeginRecordFailsClosed pins that a cross-record @@ -690,10 +761,10 @@ func TestSanitizeJSONDocument_CRLFNoStrayCarriageReturn(t *testing.T) { } } -// TestSanitizeJSONDocument_EscapedMarkersAcrossMembersFailsClosed pins that a -// block spanning members is detected even when no leaf produces a finding and -// the markers are \u-escaped in the raw bytes. -func TestSanitizeJSONDocument_EscapedMarkersAcrossMembersFailsClosed(t *testing.T) { +// TestSanitizeJSONDocument_EscapedMarkersAcrossMembersMasked pins that a block +// spanning members is detected even when no leaf produces a finding and the +// markers are \u-escaped in the raw bytes. +func TestSanitizeJSONDocument_EscapedMarkersAcrossMembersMasked(t *testing.T) { p := OutputPipeline() end := "-----END RSA" + " PRIVATE KEY-----" doc := []byte(`["\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + @@ -704,13 +775,12 @@ func TestSanitizeJSONDocument_EscapedMarkersAcrossMembersFailsClosed(t *testing. require.NotEmpty(t, findings) assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) assert.NotContains(t, string(out), "MIIEspanningkeymaterial") - assert.Contains(t, string(out), "output removed") } -// TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersFailsClosed pins that -// the decoded view applies the same Unicode normalization as the leaf scan, so -// a marker obfuscated with a zero-width character cannot hide a spanning block. -func TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersFailsClosed(t *testing.T) { +// TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersMasked pins that the +// decoded view applies the same Unicode normalization as the leaf scan, so a +// marker obfuscated with a zero-width character cannot hide a spanning block. +func TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersMasked(t *testing.T) { p := OutputPipeline() end := "-----END RSA" + " PRIVATE KEY-----" // U+200B inside the BEGIN marker: not a PEM block in any single form. @@ -722,13 +792,13 @@ func TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersFailsClosed(t *testi require.NotEmpty(t, findings) assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) assert.NotContains(t, string(out), "MIIEspanningkeymaterial") - assert.Contains(t, string(out), "output removed") } -// TestSanitizeJSONDocument_UnterminatedBeginBeforeCompleteBlockFailsClosed pins +// TestSanitizeJSONDocument_UnterminatedBeginBeforeCompleteBlockMasksBoth pins // that a lazy match starting at one leaf's BEGIN and ending at another leaf's -// END cannot cancel out a complete leaf block: containment is judged per match. -func TestSanitizeJSONDocument_UnterminatedBeginBeforeCompleteBlockFailsClosed(t *testing.T) { +// END cannot cancel out a complete leaf block: containment is judged per match, +// so both blocks are neutralized. +func TestSanitizeJSONDocument_UnterminatedBeginBeforeCompleteBlockMasksBoth(t *testing.T) { p := OutputPipeline() begin := "-----BEGIN RSA" + " PRIVATE KEY-----" end := "-----END RSA" + " PRIVATE KEY-----" @@ -739,7 +809,7 @@ func TestSanitizeJSONDocument_UnterminatedBeginBeforeCompleteBlockFailsClosed(t require.NotEmpty(t, findings) assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) assert.NotContains(t, string(out), "MIIEfirstkeymaterial", "the unterminated block must not survive") - assert.Contains(t, string(out), "output removed") + assert.NotContains(t, string(out), "ZZZZZZZZ", "the complete block must not survive") } // TestSanitizeJSONDocument_LeavesUnsupportedInputAlone pins the fallback diff --git a/internal/security/redactor.go b/internal/security/redactor.go index 15e3da021a..b421d878fd 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -7,6 +7,7 @@ import ( "slices" "strings" "sync" + "unicode/utf8" ) // Runtime secrets are exact credential values the runner learned during @@ -17,6 +18,12 @@ import ( // trivial string can never blank out ordinary output. const minRuntimeSecretLen = 8 +// minJSONFieldLen is the shortest value masked as a json_field. It is counted in +// runes, matching the {8,} quantifier the json_field value used before the +// pattern was widened to span escaped quotes inside a JSON string. The other +// structural patterns enforce their own minimum in the pattern itself. +const minJSONFieldLen = 8 + var ( runtimeSecretsMu sync.RWMutex runtimeSecrets []string @@ -178,28 +185,18 @@ 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 the matched secret ends with a backslash and is immediately // followed by a quote delimiter, the trailing backslash was escaping // that delimiter (e.g. \" in JSON or code strings). Preserve the // escape by excluding the backslash from the redacted secret span. - originalLen := len(secret) - if end < len(current) && (current[end] == '"' || current[end] == '\'') { + // json_field spans escaped quotes in its own value pattern, so its + // capture already ends at the delimiter it belongs to. + if p.name != "json_field" && end < len(current) && (current[end] == '"' || current[end] == '\'') { numBackslashes := 0 for k := len(secret) - 1; k >= 0 && secret[k] == '\\'; k-- { numBackslashes++ } - if numBackslashes%2 == 1 && p.name != "json_field" { + if numBackslashes%2 == 1 { secret = secret[:len(secret)-1] end-- } @@ -215,10 +212,15 @@ func (s *SecretRedactor) Scan(text string) ScanResult { if isAlreadyMasked(secret) { continue } - masked := Mask(secret) - if originalLen < minLen { + // Only json_field needs the length gate here: its value pattern + // matches any length, while env_assignment, auth_header and + // db_connection_password enforce their own minimum in the pattern. + // The gate counts runes and runs on the trimmed span, so the bytes + // actually masked are never shorter than the documented minimum. + if p.name == "json_field" && utf8.RuneCountInString(secret) < minJSONFieldLen { continue } + masked := Mask(secret) result.Findings = append(result.Findings, Finding{ Scanner: "secret_redactor", Name: p.name, diff --git a/internal/security/scanner_test.go b/internal/security/scanner_test.go index 8e31c37455..86f2fce7a5 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -544,6 +544,18 @@ func TestSecretRedactor(t *testing.T) { assert.NotContains(t, result.Sanitized, "ijklmnop") }) + t.Run("json_field minimum counts runes, not bytes", func(t *testing.T) { + // Three CJK characters are nine bytes. The {8,} quantifier the value + // pattern used before it spanned escaped quotes counted characters, so + // a byte count would start masking values it never masked. + short := r.Scan(`{"password": "秘密の鍵"}`) + assert.True(t, short.Safe, "a value below the minimum must not be masked: %s", short.Sanitized) + + exact := r.Scan(`{"password": "秘密の鍵ですよね"}`) // 8 runes + assert.False(t, exact.Safe) + assert.True(t, hasFinding(exact, "json_field")) + }) + t.Run("mask does not leave dangling escape sequence", func(t *testing.T) { input1 := `Authorization: Bearer abc\ndefghijkl` result1 := r.Scan(input1) From 1345e867e9e2b645ba04648a4653743e617598f8 Mon Sep 17 00:00:00 2001 From: anevans Date: Fri, 20 Nov 2026 09:44:48 -0500 Subject: [PATCH 26/51] docs(#5705): describe member-level private-key masking and the removal alert Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index e79b18b6e4..723bbae3f3 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -628,7 +628,11 @@ bytes. A sanitized key that would collide with a different member is disambiguated (`_`). The bytes actually written are scanned as well, so a secret that only exists in the serialized form is still caught, and a private-key block spanning members is detected in a decoded view of the document -before masking a member value can hide its BEGIN marker. +before masking a member value can hide its BEGIN marker. Such a block is +neutralized member by member: every key and leaf the match covers becomes +`[REDACTED PRIVATE KEY]`, so the rest of the document — a review verdict, a +summary — survives instead of being dropped because one finding quoted the PEM +header and another quoted the footer. `.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the record framing; a secret that spans records cannot be redacted without rewriting that framing, so only the records it covers are replaced. A @@ -643,11 +647,13 @@ unchanged. Some content cannot be redacted in place. A JSON document or JSONL record is replaced with a valid fail-closed marker instead — never with corrupted -syntax — when a secret spans JSON framing (such as a private-key block split -across members), when a match spans record boundaries, or when a text -redaction would leave the document invalid. Markers look -like `{"error":"output removed because …"}` and are logged as findings in -`security/findings.jsonl`. +syntax — when a private-key block cannot be localized to members, when a match +spans record boundaries, or when a text redaction would leave the document +invalid. Markers look like `{"error":"output removed because …"}` and are logged +as findings in `security/findings.jsonl`. Because a replaced file loses +everything the agent wrote into it, and because the run still exits 0, the +reason a marker states is also emitted as a `::error::` workflow annotation +whenever the file is written under GitHub Actions. A sanitized file that cannot be written does not stop the walk: every remaining file is still scanned and redacted, and the run fails closed From 1183991609dda3425c3ee91d3007dc0e2f2c11c8 Mon Sep 17 00:00:00 2001 From: anevans Date: Fri, 20 Nov 2026 10:59:36 -0500 Subject: [PATCH 27/51] fix(#5705): keep prior redactions intact when rescanning JSON output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The serialized-bytes backstop ran every structural pattern over bytes the leaf walk had already redacted, so a redaction placeholder followed by JSON escape characters was captured as a secret and masked a second time. That dropped the informative prefix and one non-secret backslash, and logged a duplicate finding. The backstop now runs only the whole-value patterns a leaf scan cannot see — registered runtime values and private-key blocks — and isAlreadyMasked ignores trailing backslashes so a placeholder never becomes a new secret. json_field regains the raw newline its single-quoted value matched before the escape handling was added: the escape-aware branches exclude newlines, so a fallback branch that cannot cross a quote covers a multi-line value again, including one followed by another field. OutputRecordRemovals reports the reasons a JSONL record was replaced with a fail-closed marker, for the CLI to annotate. Signed-off-by: anevans --- internal/security/jsonsanitize.go | 36 ++++++++++-- internal/security/jsonsanitize_test.go | 40 ++++++++++++++ internal/security/redactor.go | 76 +++++++++++++++++++------- internal/security/scanner.go | 36 ++++++++++++ internal/security/scanner_test.go | 25 +++++++++ 5 files changed, 188 insertions(+), 25 deletions(-) diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 2856d15c0c..399ca4bf6a 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -58,6 +58,26 @@ func OutputRemoval(sanitized []byte) (string, bool) { return "", false } +// OutputRecordRemovals returns the reason stated by each fail-closed marker +// record in a sanitized JSONL stream, in order and without repeats. A JSONL file +// keeps its framing when records are replaced, so it is never a whole-file +// marker, yet the records it lost still have to reach an operator (#5705). +func OutputRecordRemovals(sanitized []byte) []string { + var ( + reasons []string + seen = map[string]bool{} + ) + for _, line := range bytes.Split(sanitized, []byte("\n")) { + reason, removed := OutputRemoval(line) + if !removed || seen[reason] { + continue + } + seen[reason] = true + reasons = append(reasons, reason) + } + return reasons +} + // sensitiveJSONKeyRe matches object keys whose values are masked even when the // value itself does not match a secret pattern. var sensitiveJSONKeyRe = regexp.MustCompile(`(?i)(?:key|token|secret|password|credential|auth)`) @@ -108,10 +128,10 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { if spans.localized > 0 { findings = append(findings, privateKeySpanFinding(spans.localized, true)) } - // Scan the bytes that will actually be written. The walk above already - // scanned every decoded key and leaf, so a match here spans JSON framing - // (for example a PEM block split across members) and cannot be mapped back - // to a single leaf. + // Scan the bytes that will actually be written, for the whole-value secrets + // a leaf scan cannot see: a runtime value or a private-key block that spans + // JSON framing (for example a PEM block split across members) and so cannot + // be mapped back to a single leaf. sanitizedOut, outputFindings := redactJSONOutput(out, p) return preserveTrailingNewline(sanitizedOut, doc), append(findings, outputFindings...), nil } @@ -247,8 +267,14 @@ func preserveTrailingNewline(encoded, doc []byte) []byte { // it is applied only when the redacted text is still valid JSON; otherwise the // document fails closed with a valid marker. clean is returned unchanged when // the scan finds nothing. +// +// Only whole-value patterns run here. The leaf walk has already applied the +// value patterns to the decoded document, so a value match on the re-encoded +// bytes is a redaction placeholder followed by JSON escape characters rather +// than a secret, and masking it again would drop both the placeholder's prefix +// and a non-secret backslash (#5705). func redactJSONOutput(clean []byte, p *Pipeline) ([]byte, []Finding) { - res := p.Scan(string(clean)) + res := p.ScanWholeValueSecrets(string(clean)) if len(res.Findings) == 0 { return clean, nil } diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index f4f30f479f..96b53341d2 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -220,6 +220,30 @@ func TestSanitizeJSONLines_DisjointCrossRecordMatchesKeepCleanRecord(t *testing. } } +// TestSanitizeJSONDocument_BackstopKeepsEarlierMask pins that the +// serialized-bytes backstop never masks a redaction placeholder a second time. +// The leaf pass masked part of an escaped sequence, so re-encoding left the +// placeholder followed by doubled backslashes. A value pattern captured that +// tail, found no complete mask, and masked again — dropping the informative +// prefix and a non-secret backslash, and logging a duplicate finding (#5705). +func TestSanitizeJSONDocument_BackstopKeepsEarlierMask(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"body":"x token_usage = metrics.get(\\\"token_usage\\\") or {}"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.Len(t, findings, 1, "only the leaf match may be reported: %+v", findings) + assert.Equal(t, "env_assignment", findings[0].Name) + + var decoded struct { + Body string `json:"body"` + } + require.NoError(t, json.Unmarshal(out, &decoded)) + assert.Equal(t, `x token_usage = metr...\"token_usage\") or {}`, decoded.Body, + "the earlier mask and the non-secret backslashes must survive") +} + // TestSanitizeJSONDocument_BackstopRedactsSecondRuntimeSecret pins that a // runtime secret exposed only by serializing the parsed document is still // handled when another runtime secret was already found in a leaf. @@ -317,6 +341,22 @@ func TestOutputRemoval(t *testing.T) { } } +// TestOutputRecordRemovals pins that a JSONL stream whose records were replaced +// reports each distinct reason once. A replaced record keeps the file's framing, +// so the file never equals a whole-file marker, and this is how its loss reaches +// an operator (#5705). +func TestOutputRecordRemovals(t *testing.T) { + stream := []byte( + `{"event":"clean"}` + "\n" + + failClosedCrossRecordJSON + "\r\n" + + failClosedCrossRecordJSON + "\n" + + failClosedSpansMembersJSON + "\n") + assert.Equal(t, + []string{"a secret spanned multiple records", "a private key block spans JSON framing"}, + OutputRecordRemovals(stream)) + assert.Empty(t, OutputRecordRemovals([]byte(`{"event":"clean"}`+"\n"))) +} + // TestJSONProvenance_UnmappableBlock pins the defensive fallback: a block that no // recorded leaf range covers is reported as unmappable so the caller fails // closed instead of writing bytes that may still carry it. diff --git a/internal/security/redactor.go b/internal/security/redactor.go index b421d878fd..5c8df64e67 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -99,6 +99,21 @@ func NewSecretRedactor() *SecretRedactor { func (s *SecretRedactor) Name() string { return "secret_redactor" } func (s *SecretRedactor) Scan(text string) ScanResult { + return s.scan(text, false) +} + +// ScanWholeValueSecrets masks only the secrets whose match is the entire value: +// registered runtime values and private-key blocks. It is meant for bytes a leaf +// scan has already redacted, where a pattern match can be a redaction +// placeholder plus JSON escape characters rather than a new secret (#5705). +func (s *SecretRedactor) ScanWholeValueSecrets(text string) ScanResult { + return s.scan(text, true) +} + +// scan runs the pattern set. wholeValueOnly restricts it to the patterns whose +// match is the whole secret, which are the only ones that can still be present +// in bytes an earlier pass already redacted. +func (s *SecretRedactor) scan(text string, wholeValueOnly bool) ScanResult { result := ScanResult{Safe: true, Sanitized: text} current := text @@ -122,29 +137,37 @@ func (s *SecretRedactor) Scan(text string) ScanResult { // Prefix-based patterns (full match is the secret). // Use ReplaceAll to catch duplicate occurrences of the same secret. - for _, p := range s.prefixPatterns { - // Deduplicate matches so we report each unique secret once. - seen := map[string]bool{} - matches := p.regex.FindAllString(current, -1) - for _, match := range matches { - if seen[match] { - continue + if !wholeValueOnly { + for _, p := range s.prefixPatterns { + // Deduplicate matches so we report each unique secret once. + seen := map[string]bool{} + matches := p.regex.FindAllString(current, -1) + for _, match := range matches { + if seen[match] { + continue + } + seen[match] = true + masked := Mask(match) + result.Findings = append(result.Findings, Finding{ + Scanner: "secret_redactor", + Name: p.name, + Severity: "critical", + Detail: fmt.Sprintf("Redacted %s (%d chars) -> %s", p.name, len(match), masked), + }) + current = strings.ReplaceAll(current, match, masked) + result.Safe = false } - seen[match] = true - masked := Mask(match) - result.Findings = append(result.Findings, Finding{ - Scanner: "secret_redactor", - Name: p.name, - Severity: "critical", - Detail: fmt.Sprintf("Redacted %s (%d chars) -> %s", p.name, len(match), masked), - }) - current = strings.ReplaceAll(current, match, masked) - result.Safe = false } } - // Structural patterns (capture group is the secret) + // Structural patterns (capture group is the secret). Only the private-key + // block is safe to match in whole-value mode: every other pattern captures a + // value out of surrounding text, so a match on bytes that already carry a + // redaction placeholder can be that placeholder rather than a secret. for _, p := range s.structuralPatterns { + if wholeValueOnly && p.name != "private_key" { + continue + } // Private key: replace full match (no capture group needed). if p.name == "private_key" { matches := p.regex.FindAllString(current, -1) @@ -254,8 +277,12 @@ func Mask(value string) string { } // isAlreadyMasked reports whether value is already a redaction placeholder -// produced by Mask. +// produced by Mask. Trailing backslashes are ignored: a placeholder that sits in +// a JSON string can be followed by escape characters once the string is +// re-encoded, and that tail must not turn the placeholder into a new secret +// (#5705). func isAlreadyMasked(value string) bool { + value = strings.TrimRight(value, `\`) return value == "***" || len(value) == 7 && strings.HasSuffix(value, "...") } @@ -312,7 +339,16 @@ 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]|[^"\\])*)"|'((?:''|\\\r?\n|\\.|[^'\r\n\\])*[^'\r\n\\])'|'((?:''|[^'\r\n])*\\)')`}, + // json_field captures a value out of a quoted field. The double-quoted + // branch and the first single-quoted branch consume escaped delimiters, so + // a JSON or YAML string with an embedded quote is matched whole. The second + // single-quoted branch covers a value that ends in a literal backslash, + // where that backslash must not escape the closing quote. The last branch + // keeps a raw newline inside a single-quoted value matchable, as it was + // before the escape handling was added: it cannot cross a quote, so it + // never swallows the field that follows. The minimum length is enforced in + // scan, not here. + {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\[\s\S]|[^"\\])*)"|'((?:''|\\\r?\n|\\.|[^'\r\n\\])*[^'\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.go b/internal/security/scanner.go index a793cdee5c..e1df3743fd 100644 --- a/internal/security/scanner.go +++ b/internal/security/scanner.go @@ -79,6 +79,42 @@ func (p *Pipeline) Scan(text string) ScanResult { return aggregate } +// wholeValueScanner masks only the secrets whose match is the entire value. +// Pipeline.ScanWholeValueSecrets uses it to rescan bytes an earlier pass has +// already redacted without mistaking a redaction placeholder for a secret. +type wholeValueScanner interface { + ScanWholeValueSecrets(text string) ScanResult +} + +// ScanWholeValueSecrets runs only the whole-value masking of the pipeline's +// scanners: registered runtime values and private-key blocks. Normalizers and +// value patterns are skipped, because the leaf scan has already applied them to +// the decoded document, and re-running them over serialized bytes can only +// damage the redactions they produced (#5705). +func (p *Pipeline) ScanWholeValueSecrets(text string) ScanResult { + aggregate := ScanResult{Safe: true, Sanitized: text} + current := text + for _, s := range p.scanners { + w, ok := s.(wholeValueScanner) + if !ok { + continue + } + result := w.ScanWholeValueSecrets(current) + aggregate.Findings = append(aggregate.Findings, result.Findings...) + if !result.Safe { + aggregate.Safe = false + } + if result.Sanitized != "" { + current = result.Sanitized + aggregate.Sanitized = current + } + } + if aggregate.Sanitized == text { + aggregate.Sanitized = "" // no changes + } + return aggregate +} + // InputPipeline returns the standard input scanning pipeline for // untrusted text entering the agent. Order matters: // 1. UnicodeNormalizer — strip invisible chars, normalize fullwidth diff --git a/internal/security/scanner_test.go b/internal/security/scanner_test.go index 86f2fce7a5..6069b9e110 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -544,6 +544,31 @@ func TestSecretRedactor(t *testing.T) { assert.NotContains(t, result.Sanitized, "ijklmnop") }) + t.Run("json_field redacts a single-quoted value spanning a raw newline", func(t *testing.T) { + // Base matched `'([^']{8,})'`, which crosses newlines. Handling escaped + // delimiters must not narrow the pattern: a raw newline inside the + // value is still part of the secret. + result := r.Scan("'password': 'line1\nline2line3'") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "line2line3") + }) + + t.Run("json_field multi-line value does not swallow the next field", func(t *testing.T) { + input := "'password': 'line1\nline2line3'\n'secret': 'ijklmnop'" + result := r.Scan(input) + assert.False(t, result.Safe) + findings := 0 + for _, f := range result.Findings { + if f.Name == "json_field" { + findings++ + } + } + assert.Equal(t, 2, findings, "both fields must be detected and redacted") + assert.NotContains(t, result.Sanitized, "line2line3") + assert.NotContains(t, result.Sanitized, "ijklmnop") + }) + t.Run("json_field minimum counts runes, not bytes", func(t *testing.T) { // Three CJK characters are nine bytes. The {8,} quantifier the value // pattern used before it spanned escaped quotes counted characters, so From 40b1cff8fff7fc9457a2758cae4a13e583c01ed9 Mon Sep 17 00:00:00 2001 From: anevans Date: Fri, 20 Nov 2026 11:01:16 -0500 Subject: [PATCH 28/51] fix(#5705)!: fail closed on output that cannot be sanitized MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A sanitizer error returned from the WalkDir callback and stopped the walk, so the failing file and every file after it stayed on disk unredacted while the artifact steps run with `if: always()`. Sanitizer errors are now contained the way write errors are: the file is replaced with the fail-closed marker (removed if even that write fails), the error is joined after the walk, and every remaining file is still scanned. A JSONL file whose records are replaced keeps its framing, so it never equals a whole-file marker and raised no annotation. Each distinct marker reason is now emitted as a `::error::` annotation under GitHub Actions, matching what the docs promise for whole-file replacement. BREAKING CHANGE: Output files are no longer left unredacted when their sanitized content cannot be computed or written. Such a file is replaced with `{"error":"output removed because it could not be redacted"}` and the run fails. A document or JSONL record that cannot be redacted in place is replaced with an `{"error":"output removed because …"}` marker, and a redacted JSON number is written as a string (`{"id":"***"}`). Anything that parses `output/` must treat a marker document as an error, not as the file's schema. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 41 +++++----- .../user/run-artifacts-and-private-data.md | 5 +- internal/cli/run.go | 77 +++++++++++++++---- internal/cli/scan_output_telemetry_test.go | 76 ++++++++++++++++++ 4 files changed, 164 insertions(+), 35 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 723bbae3f3..159a8ad937 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -625,14 +625,17 @@ individually through a token-preserving walk that keeps member order and duplicate keys, so an earlier value that map decoding would drop is still scanned, and a secret spanning JSON framing stays visible in the rewritten bytes. A sanitized key that would collide with a different member is -disambiguated (`_`). The bytes actually written are scanned as well, so -a secret that only exists in the serialized form is still caught, and a -private-key block spanning members is detected in a decoded view of the document -before masking a member value can hide its BEGIN marker. Such a block is -neutralized member by member: every key and leaf the match covers becomes -`[REDACTED PRIVATE KEY]`, so the rest of the document — a review verdict, a -summary — survives instead of being dropped because one finding quoted the PEM -header and another quoted the footer. +disambiguated (`_`). The bytes actually written are scanned as well, but +only for whole-value secrets — registered runtime values and private-key blocks, +the two patterns a leaf scan cannot see once a member value is masked. Every +other pattern has already been applied to the decoded key or leaf, so a match on +the serialized bytes would be a redaction placeholder plus JSON escape +characters, not a secret. A private-key block spanning members is detected in a +decoded view of the document before masking a member value can hide its BEGIN +marker. Such a block is neutralized member by member: every key and leaf the +match covers becomes `[REDACTED PRIVATE KEY]`, so the rest of the document — a +review verdict, a summary — survives instead of being dropped because one +finding quoted the PEM header and another quoted the footer. `.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the record framing; a secret that spans records cannot be redacted without rewriting that framing, so only the records it covers are replaced. A @@ -650,16 +653,18 @@ replaced with a valid fail-closed marker instead — never with corrupted syntax — when a private-key block cannot be localized to members, when a match spans record boundaries, or when a text redaction would leave the document invalid. Markers look like `{"error":"output removed because …"}` and are logged -as findings in `security/findings.jsonl`. Because a replaced file loses -everything the agent wrote into it, and because the run still exits 0, the -reason a marker states is also emitted as a `::error::` workflow annotation -whenever the file is written under GitHub Actions. - -A sanitized file that cannot be written does not stop the walk: every -remaining file is still scanned and redacted, and the run fails closed -afterwards with all write errors joined. The file itself is replaced with a -fail-closed marker so the unredacted bytes never reach the uploaded artifact. In `quiet` mode the affected paths -are counted, not named (ADR 0163). +as findings in `security/findings.jsonl`. Because a replaced file or record loses +everything the agent wrote into it, and because the run still exits 0, the reason +a marker states is also emitted as a `::error::` workflow annotation whenever the +file is written under GitHub Actions: one annotation for a file replaced whole, +and one per distinct reason for a JSONL file whose records were replaced. + +A sanitized file that cannot be written, and a file that cannot be sanitized at +all, do not stop the walk: every remaining file is still scanned and redacted, +and the run fails closed afterwards with all failures joined. The file itself is +replaced with a fail-closed marker so the unredacted bytes never reach the +uploaded artifact. In `quiet` mode the affected paths are counted, not named +(ADR 0163). ## Agent rule layering diff --git a/docs/guides/user/run-artifacts-and-private-data.md b/docs/guides/user/run-artifacts-and-private-data.md index 4b36f99115..578c011bbc 100644 --- a/docs/guides/user/run-artifacts-and-private-data.md +++ b/docs/guides/user/run-artifacts-and-private-data.md @@ -347,8 +347,9 @@ download the artifact until it expires. The output scan masks secret literals; it does not remove personal data, customer names or other private business text. When a secret cannot be masked without breaking a file's JSON structure, the affected JSON document or JSONL record is replaced with a JSON -error marker, a file whose redacted content cannot be written is replaced by -such a marker, and the run itself fails. +error marker; a file whose redacted content cannot be written or computed is +replaced by such a marker and fails the run. Either way the job log carries an +error annotation, because a run that only lost content still exits 0. `fullsend run` leaves `output/` untouched. At the end of the job, `fullsend prepare-artifacts` builds a filtered copy at the level you set, and diff --git a/internal/cli/run.go b/internal/cli/run.go index 2ae4e1591b..89906e975e 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7063,6 +7063,14 @@ func printExtractedOutputFiles(printer *ui.Printer, extracted []string, elapsed printer.StepDone(fmt.Sprintf("Extracted %d output file(s) (%.1fs)", len(extracted), elapsed.Seconds())) } +// The structural sanitizers are variables so tests can inject a sanitizer +// failure: their error path has no natural trigger, because they only fail on a +// decoder limit after json.Valid has accepted the document. +var ( + sanitizeJSONDocument = security.SanitizeJSONDocument + sanitizeJSONLines = security.SanitizeJSONLines +) + // scanOutputFiles runs the output security pipeline (unicode normalization and // secret redaction) on extracted output files, recursively walking all // subdirectories (iteration-N/output/, etc.). At the quiet progress level @@ -7082,10 +7090,10 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri pipeline := security.OutputPipeline() findingCount := 0 // At quiet, unreadable and unwritable files are counted, not named. - unreadable, unwritable := 0, 0 - // Write failures are collected rather than returned from the walk callback - // so every remaining file is still scanned and redacted. The run still - // fails closed once the walk finishes (#5705). + unreadable, unwritable, unsanitizable := 0, 0, 0 + // Write and sanitizer failures are collected rather than returned from the + // walk callback so every remaining file is still scanned and redacted. The + // run still fails closed once the walk finishes (#5705). var writeErrs []error findingsPath := filepath.Join(outputDir, "security", "findings.jsonl") @@ -7131,10 +7139,14 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri // JSONL and NDJSON are sanitized record by record so one record never // rewrites another (#5705). if ext == ".jsonl" || ext == ".ndjson" { - out, jsonLineFindings, scanErr := security.SanitizeJSONLines(content, pipeline) + out, jsonLineFindings, scanErr := sanitizeJSONLines(content, pipeline) if scanErr != nil { - return fmt.Errorf("could not sanitize JSONL output %s: %w", relPath, scanErr) + writeErrs = append(writeErrs, sanitizeFailure(quiet, path, relPath, scanErr, &unsanitizable)) + return nil } + // A record that was replaced with a marker is not a whole-file + // marker, so this is the only place its loss reaches an operator. + alertOnRecordRemoval(printer, out) if len(jsonLineFindings) > 0 { findingCount += len(jsonLineFindings) for _, f := range jsonLineFindings { @@ -7146,7 +7158,6 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri Phase: "host_output", Finding: f, }) } - alertOnOutputRemoval(printer, out) if writeErr := writeFile(path, out, 0o644); writeErr != nil { writeErrs = append(writeErrs, writeFailure(quiet, path, relPath, writeErr, &unwritable)) } @@ -7158,9 +7169,10 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri // syntax and fails closed (#5705). Non-JSON files fall through to the // plain text scan below. if json.Valid(bytes.TrimSpace(content)) { - out, jsonFindings, jsonErr := security.SanitizeJSONDocument(content, pipeline) + out, jsonFindings, jsonErr := sanitizeJSONDocument(content, pipeline) if jsonErr != nil { - return fmt.Errorf("could not sanitize JSON output %s: %w", relPath, jsonErr) + writeErrs = append(writeErrs, sanitizeFailure(quiet, path, relPath, jsonErr, &unsanitizable)) + return nil } if len(jsonFindings) > 0 { findingCount += len(jsonFindings) @@ -7225,6 +7237,9 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri if unwritable > 0 { printer.StepWarn(fmt.Sprintf("Could not write %d sanitized output file(s)", unwritable)) } + if unsanitizable > 0 { + printer.StepWarn(fmt.Sprintf("Could not sanitize %d output file(s)", unsanitizable)) + } if findingCount > 0 { printer.StepWarn(fmt.Sprintf("Sanitized %d finding(s) in output files", findingCount)) } else { @@ -7250,24 +7265,56 @@ func alertOnOutputRemoval(printer *ui.Printer, sanitized []byte) { printer.Raw("::error::Output file replaced with a fail-closed marker: " + reason + "\n") } +// alertOnRecordRemoval emits a workflow annotation for each distinct reason a +// JSONL record was replaced with a fail-closed marker. Such a file keeps its +// records, so it is never a whole-file marker, and the record's loss would +// otherwise show up only as one scan line — the silent failure #5705 set out to +// fix. Only the marker's fixed reason reaches the annotation, never a path or a +// matched value (ADR 0163). +func alertOnRecordRemoval(printer *ui.Printer, sanitized []byte) { + if os.Getenv("GITHUB_ACTIONS") != "true" { + return + } + for _, reason := range security.OutputRecordRemovals(sanitized) { + printer.Raw("::error::Output record replaced with a fail-closed marker: " + reason + "\n") + } +} + // writeFailure records a sanitized-output write error. At the quiet progress // level the path is withheld because it can carry an agent-chosen name // (ADR 0163); non-quiet callers name it. func writeFailure(quiet bool, path, relPath string, writeErr error, unwritable *int) error { *unwritable++ - // The unredacted bytes must not reach the uploaded artifact, so replace the - // file with a valid fail-closed marker; remove it if even that fails. - if err := os.WriteFile(path, []byte(unwritableOutputMarker), 0o644); err != nil { - _ = os.Remove(path) - } + quarantineOutput(path) if quiet { return fmt.Errorf("could not write sanitized output file") } return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) } +// sanitizeFailure records a sanitization error and contains the file it could +// not sanitize, so the walk continues to the remaining files instead of leaving +// them unredacted. The unredacted bytes must never reach the uploaded artifact, +// so the file is replaced with the marker as on a write failure (#5705). +func sanitizeFailure(quiet bool, path, relPath string, scanErr error, unsanitizable *int) error { + *unsanitizable++ + quarantineOutput(path) + if quiet { + return fmt.Errorf("could not sanitize output file") + } + return fmt.Errorf("could not sanitize %s: %w", relPath, scanErr) +} + +// quarantineOutput replaces path with the fail-closed marker, removing it if even +// that write fails, so unredacted bytes never reach the uploaded artifact. +func quarantineOutput(path string) { + if err := os.WriteFile(path, []byte(unwritableOutputMarker), 0o644); err != nil { + _ = os.Remove(path) + } +} + // unwritableOutputMarker replaces a file whose sanitized content could not be -// written. It is valid JSON so downstream parsers keep working. +// computed or written. It is valid JSON so downstream parsers keep working. const unwritableOutputMarker = `{"error":"output removed because it could not be redacted"}` // downloadSandboxFindings extracts the sandbox-side findings directory. It is a diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index cfe186e1d1..6b04f5f71d 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" + "errors" "fmt" "os" "os/exec" @@ -408,6 +409,81 @@ func TestScanOutputFiles_ReturnsErrorWhenSanitizedWriteFails(t *testing.T) { assert.Contains(t, err.Error(), "could not write sanitized secret.txt") } +// TestScanOutputFiles_SanitizerErrorContainsFileAndContinues pins that a +// sanitizer error is contained the way a write failure is: the file it could not +// sanitize is replaced with the marker, the walk continues to the remaining +// files, and the run still fails closed. The sanitizers only fail on a decoder +// limit, so the failure is injected. +func TestScanOutputFiles_SanitizerErrorContainsFileAndContinues(t *testing.T) { + original := sanitizeJSONDocument + t.Cleanup(func() { sanitizeJSONDocument = original }) + sanitizeJSONDocument = func([]byte, *security.Pipeline) ([]byte, []security.Finding, error) { + return nil, nil, errors.New("decoder limit") + } + + dir := t.TempDir() + failing := filepath.Join(dir, "a-result.json") + require.NoError(t, os.WriteFile(failing, []byte(`{"body":"ghp_FAKEtesttoken000000000000000000000000"}`), 0o644)) + later := filepath.Join(dir, "b-notes.txt") + require.NoError(t, os.WriteFile(later, []byte("Token: ghp_FAKEtesttoken000000000000000000000000"), 0o644)) + + err := scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{})) + require.Error(t, err) + assert.Contains(t, err.Error(), "could not sanitize a-result.json") + + got, readErr := os.ReadFile(failing) + require.NoError(t, readErr) + assert.Equal(t, unwritableOutputMarker, string(got), "an unsanitizable file must be contained") + assert.NotContains(t, string(got), "ghp_FAKEtesttoken") + + got, readErr = os.ReadFile(later) + require.NoError(t, readErr) + assert.NotContains(t, string(got), "ghp_FAKEtesttoken", + "the walk must continue past a sanitizer error and redact the remaining files") +} + +// TestScanOutputFiles_EmitsAnnotationForJSONLRecordRemoval pins that a replaced +// JSONL record is announced too. The file keeps its record framing, so it is +// never a whole-file marker, and without the annotation a lost record would only +// show up as one scan line (#5705). +func TestScanOutputFiles_EmitsAnnotationForJSONLRecordRemoval(t *testing.T) { + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + content := "{\"event\":\"start\",\"text\":\"" + begin + "\"}\n" + + "{\"event\":\"body\",\"text\":\"MIIEpAIBAAKCAQEA0123456789abcdef\"}\n" + + "{\"event\":\"end\",\"text\":\"" + end + "\"}\n" + + for name, tc := range map[string]struct { + actions string + want string + }{ + "github actions": { + actions: "true", + want: "::error::Output record replaced with a fail-closed marker: a secret spanned multiple records", + }, + "local run": {actions: "", want: ""}, + } { + t.Run(name, func(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", tc.actions) + dir := t.TempDir() + path := filepath.Join(dir, "transcript.jsonl") + require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) + + var output bytes.Buffer + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&output))) + + got, err := os.ReadFile(path) + require.NoError(t, err) + assert.NotContains(t, string(got), "MIIEpAIBAAKCAQEA") + if tc.want == "" { + assert.NotContains(t, output.String(), "::error::") + return + } + assert.Contains(t, output.String(), tc.want) + }) + } +} + func TestScanOutputFiles_QuietJSONWriteFailureIsFatal(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "secret.json") From 83e496018a6ca874008fa82a674eeec2478b4635 Mon Sep 17 00:00:00 2001 From: anevans Date: Fri, 20 Nov 2026 12:23:03 -0500 Subject: [PATCH 29/51] fix(#5705): keep JSON key names when masking a spanning private key MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Masking a private-key block that spans JSON members replaced every covered object key with `[REDACTED PRIVATE KEY]`, so a review result lost required fields such as `severity`, `category` and `file` and could no longer satisfy its own schema. Key names are the document's structure, not block content: the rewrite now masks the string values the match covers and keeps every key name, so a review that quotes the PEM header in one finding and the footer in another keeps its shape. A key name is treated as content and masked only when the name itself carries a `-----BEGIN`/`-----END` marker, which is the one case where it cannot be written back. Tests: `TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview` now runs a review-result-shaped document (action, pr_number, repo, findings carrying severity, category, file and description) and asserts every required finding key survives, alongside new coverage for a marker inside a key name and for the value-only span map. Docs: the user guide no longer claims an error annotation for files whose redacted content cannot be written or computed — that path fails the run — and states that annotations appear on GitHub Actions only. The runtime guide describes the value-only masking. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 13 +- .../user/run-artifacts-and-private-data.md | 8 +- internal/security/jsonsanitize.go | 126 ++++++++++++------ internal/security/jsonsanitize_test.go | 95 +++++++++++-- 4 files changed, 190 insertions(+), 52 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 159a8ad937..98688e33a8 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -632,10 +632,15 @@ other pattern has already been applied to the decoded key or leaf, so a match on the serialized bytes would be a redaction placeholder plus JSON escape characters, not a secret. A private-key block spanning members is detected in a decoded view of the document before masking a member value can hide its BEGIN -marker. Such a block is neutralized member by member: every key and leaf the -match covers becomes `[REDACTED PRIVATE KEY]`, so the rest of the document — a -review verdict, a summary — survives instead of being dropped because one -finding quoted the PEM header and another quoted the footer. +marker. Such a block is neutralized member by member: every string value the +match covers becomes `[REDACTED PRIVATE KEY]`, while object keys keep their +names, so a document that merely quotes the PEM header in one finding and the +footer in another keeps its shape — every required field of a review result is +still present — instead of being dropped whole. A key name is treated as block +content only when the name itself carries a marker; then it is masked too, +because it cannot be written back as structure. Every string value inside the +matched span is masked, since nothing distinguishes a quoted marker pair from +fragments of real key material. `.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the record framing; a secret that spans records cannot be redacted without rewriting that framing, so only the records it covers are replaced. A diff --git a/docs/guides/user/run-artifacts-and-private-data.md b/docs/guides/user/run-artifacts-and-private-data.md index 578c011bbc..c2e2a925c9 100644 --- a/docs/guides/user/run-artifacts-and-private-data.md +++ b/docs/guides/user/run-artifacts-and-private-data.md @@ -348,8 +348,12 @@ literals; it does not remove personal data, customer names or other private business text. When a secret cannot be masked without breaking a file's JSON structure, the affected JSON document or JSONL record is replaced with a JSON error marker; a file whose redacted content cannot be written or computed is -replaced by such a marker and fails the run. Either way the job log carries an -error annotation, because a run that only lost content still exits 0. +replaced by such a marker and fails the run. A marked document or record leaves +its keys in place but masks the string values inside the matched span. When a +replacement happens in a run that still exits 0, the job log carries an error +annotation to say so — on GitHub Actions only; on GitLab and Forgejo the run's +log and exit status are the signal. A write or sanitize failure needs no +annotation because the run itself fails. `fullsend run` leaves `output/` untouched. At the end of the job, `fullsend prepare-artifacts` builds a filtered copy at the level you set, and diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 399ca4bf6a..c1e785ca72 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -29,8 +29,9 @@ const ( OutputRemovalTextJSONMarker = `{"error":"output removed because text redaction would invalidate JSON"}` ) -// privateKeyMask replaces each JSON key and string leaf that carries part of a -// private-key block spanning JSON framing. +// privateKeyMask replaces each JSON string value that carries part of a +// private-key block spanning JSON framing, and any key name that carries a +// block marker itself. const privateKeyMask = "[REDACTED PRIVATE KEY]" // outputRemovalMarkers lists every whole-file removal marker with the reason it @@ -114,7 +115,7 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { return preserveTrailingNewline([]byte(failClosedSpansMembersJSON), doc), []Finding{privateKeySpanFinding(spans.unmappable, false)}, nil } - rebuilt, findings, err := rewriteJSONTokens(trimmed, p, spans.covered) + rebuilt, findings, err := rewriteJSONTokens(trimmed, p, spans) if err != nil { // json.Valid accepted the text and the walk uses the same scanner, so // this is a decoder limit rather than a syntax error. Return the error @@ -140,7 +141,7 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { // localized says whether they were masked in the members that carried them or // the whole document had to be dropped. func privateKeySpanFinding(blocks int, localized bool) Finding { - detail := fmt.Sprintf("%d private key block(s) span JSON framing; masked the members carrying them", blocks) + detail := fmt.Sprintf("%d private key block(s) span JSON framing; masked the string values carrying them", blocks) if !localized { detail = "Private key block spans JSON framing and cannot be localized; output removed" } @@ -164,6 +165,12 @@ var privateKeyRe = func() *regexp.Regexp { panic("private_key structural pattern is missing") }() +// privateKeyMarkerRe matches either boundary line of a private-key block. It +// marks the key names that carry block text instead of JSON structure, so a key +// whose name holds a marker is masked with the values rather than kept. The +// quoted markers are the ones privateKeyRe delimits a block with. +var privateKeyMarkerRe = regexp.MustCompile(`-----BEGIN\s|-----END\s`) + // jsonProvenance accumulates an order-preserving view of the decoded strings // in a document so a private-key block that spans members can be detected after // JSON decoding. The raw bytes are not usable for this: a member may encode a @@ -172,6 +179,10 @@ var privateKeyRe = func() *regexp.Regexp { type jsonProvenance struct { decoded bytes.Buffer ranges []recordSpan + // keys marks the entries in ranges that are object keys rather than string + // values. Key names are the document's structure, so a block that spans + // them is neutralized differently from a block that spans values. + keys []bool } // decodedViewNormalizer normalizes decoded JSON text before it is matched for @@ -179,22 +190,26 @@ type jsonProvenance struct { // characters is normalized exactly as the per-leaf scan normalizes it. var decodedViewNormalizer = NewUnicodeNormalizer() -// addString appends one decoded key or string leaf to the view and records its +// addString appends one decoded key or string value to the view and records its // byte range so a match can be mapped back to the leaves that carry it. -func (v *jsonProvenance) addString(s string) { +func (v *jsonProvenance) addString(s string, isKey bool) { s = decodedViewNormalizer.Scan(s).Sanitized start := v.decoded.Len() v.decoded.WriteString(s) v.decoded.WriteByte('\n') v.ranges = append(v.ranges, recordSpan{start: start, end: v.decoded.Len() - 1}) + v.keys = append(v.keys, isKey) } // privateKeySpans is the result of looking for private-key blocks that span the -// keys and leaves of one document. +// keys and values of one document. type privateKeySpans struct { - // covered holds the indexes of the keys and leaves that carry part of a - // block spanning more than one of them. + // covered holds the indexes of the string values that carry part of a block + // spanning more than one leaf. Every covered value is replaced whole. covered map[int]bool + // maskedKeys holds the indexes of the object keys whose own name carries a + // block marker and is therefore block content rather than structure. + maskedKeys map[int]bool // localized counts the blocks that were mapped onto leaves. localized int // unmappable counts the blocks that no leaf range covers. @@ -202,17 +217,21 @@ type privateKeySpans struct { } // spanningPrivateKeys finds the private-key blocks in the decoded view that are -// not contained in a single key or leaf, and maps each one onto the leaves it +// not contained in a single key or value, and maps each one onto the leaves it // covers. Containment is checked per match: a lazy pattern can start at one // leaf's BEGIN and end at another leaf's END, and counting differences would let // that match cancel out a complete leaf block. // // A block whose markers sit in different members is not proof that key material // spans them — a review that quotes the header in one finding and the footer in -// another matches too — so the callers mask only the members the match covers -// and leave the rest of the document (a verdict, a summary) intact. +// another matches too — so only the members the match covers are touched. String +// values are masked whole, because a value is where an agent writes key +// material. An object key keeps its name unless the name itself carries a block +// marker: key names are the document's structure, and masking them would drop a +// required field such as a finding's severity, category or file and make the +// document fail schema validation. func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { - spans := privateKeySpans{covered: map[int]bool{}} + spans := privateKeySpans{covered: map[int]bool{}, maskedKeys: map[int]bool{}} for _, match := range privateKeyRe.FindAllIndex(v.decoded.Bytes(), -1) { if v.leafContaining(match[0], match[1]) >= 0 { // A block inside one leaf is that leaf's own scan. @@ -230,7 +249,13 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { } spans.localized++ for _, i := range hit { - spans.covered[i] = true + if !v.keys[i] { + spans.covered[i] = true + continue + } + if privateKeyMarkerRe.Match(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) { + spans.maskedKeys[i] = true + } } } return spans @@ -451,32 +476,47 @@ func writeDecodedJSONView(buf *bytes.Buffer, doc []byte) { } // collectJSONLeaves walks doc and records every decoded object key and string -// leaf, in document order, in a view where a value split across members reads as +// value, in document order, in a view where a value split across members reads as // one contiguous run of text. Each leaf's range in that view is kept so a match // can be mapped back to the members that carry it. func collectJSONLeaves(doc []byte) *jsonProvenance { prov := &jsonProvenance{} dec := json.NewDecoder(bytes.NewReader(doc)) dec.UseNumber() - var walk func() - walk = func() { + var walkValue func() + walkValue = func() { tok, err := dec.Token() if err != nil { return } switch t := tok.(type) { case json.Delim: - if t == '{' || t == '[' { + switch t { + case '{': + for dec.More() { + keyTok, err := dec.Token() + if err != nil { + return + } + key, ok := keyTok.(string) + if !ok { + return + } + prov.addString(key, true) + walkValue() + } + _, _ = dec.Token() // consume the closing delimiter + case '[': for dec.More() { - walk() + walkValue() } _, _ = dec.Token() // consume the closing delimiter } case string: - prov.addString(t) + prov.addString(t, false) } } - walk() + walkValue() return prov } @@ -597,14 +637,15 @@ func lineBounded(data []byte, start, end int) bool { // scalar value, and renders a valid JSON document. Unlike map decoding it // keeps member order and duplicate keys, so a secret in an earlier, overwritten // value is still found, and a secret spanning JSON framing stays visible in the -// rewritten bytes. Keys and leaves whose index is in masked are replaced whole, -// which is how a framing-spanning private key is neutralized member by member. -func rewriteJSONTokens(doc []byte, p *Pipeline, masked map[int]bool) ([]byte, []Finding, error) { +// rewritten bytes. String values and key names that a framing-spanning private +// key covers are replaced whole, which is how such a block is neutralized member +// by member. +func rewriteJSONTokens(doc []byte, p *Pipeline, spans privateKeySpans) ([]byte, []Finding, error) { dec := json.NewDecoder(bytes.NewReader(doc)) dec.UseNumber() var ( buf bytes.Buffer - w = &jsonRewrite{pipeline: p, masked: masked} + w = &jsonRewrite{pipeline: p, spans: spans} ) if err := w.writeValue(dec, &buf, ""); err != nil { return nil, nil, fmt.Errorf("could not tokenize JSON: %w", err) @@ -616,24 +657,33 @@ func rewriteJSONTokens(doc []byte, p *Pipeline, masked map[int]bool) ([]byte, [] } // jsonRewrite is the state one token walk carries: the pipeline, the findings it -// has collected, and the keys and leaves a framing-spanning private key covers. +// has collected, and the keys and string values a framing-spanning private key +// covers. type jsonRewrite struct { pipeline *Pipeline findings []Finding - masked map[int]bool - // index counts the keys and leaves already walked, in document order, so it - // lines up with the ranges in jsonProvenance. + spans privateKeySpans + // index counts the keys and string values already walked, in document + // order, so it lines up with the ranges in jsonProvenance. index int } -// nextLeaf advances the leaf cursor and reports whether the key or leaf reached -// must be replaced whole because a framing-spanning private key covers it. -func (w *jsonRewrite) nextLeaf() bool { - masked := w.masked[w.index] +// nextIndex advances the leaf cursor past the next key or string value and +// returns that leaf's index in the provenance view. +func (w *jsonRewrite) nextIndex() int { + i := w.index w.index++ - return masked + return i } +// valueMasked reports whether the string value at index i carries part of a +// framing-spanning private key and must be replaced whole. +func (w *jsonRewrite) valueMasked(i int) bool { return w.spans.covered[i] } + +// keyMasked reports whether the object key at index i carries a block marker and +// must be replaced whole. +func (w *jsonRewrite) keyMasked(i int) bool { return w.spans.maskedKeys[i] } + // writeValue writes one JSON value to buf, sanitizing object keys and scalar // leaves as it goes. memberKey is the enclosing object key when the value is an // object member, so sensitive-key masking still applies; it is empty for array @@ -647,7 +697,7 @@ func (w *jsonRewrite) writeValue(dec *json.Decoder, buf *bytes.Buffer, memberKey case json.Delim: return w.writeContainer(dec, buf, t) case string: - if w.nextLeaf() { + if w.valueMasked(w.nextIndex()) { return writeJSONString(buf, privateKeyMask) } sanitized, stringFindings := sanitizeJSONString(t, memberKey, w.pipeline) @@ -699,11 +749,11 @@ func (w *jsonRewrite) writeContainer(dec *json.Decoder, buf *bytes.Buffer, delim if !ok { return fmt.Errorf("JSON object key is %T, want string", keyTok) } - masked := w.nextLeaf() + masked := w.keyMasked(w.nextIndex()) sanitizedKey, keyFindings := sanitizeJSONKey(key, w.pipeline) if masked { - // The whole key goes: it carried part of a private-key block - // that spans members. + // The key name carried a private-key block marker, so it is + // block content rather than structure and cannot be kept. sanitizedKey, keyFindings = privateKeyMask, nil } w.findings = append(w.findings, keyFindings...) diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 96b53341d2..02744b87dd 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -66,19 +66,27 @@ func TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersMasksCoveredMembers(t assert.NotContains(t, string(out), "MIIEpAIBAAKCAQEA") assert.NotContains(t, string(out), "output removed", "the document must be kept, not dropped") assert.Contains(t, string(out), `"verdict":"approve"`, "a member outside the block must survive") + assert.Contains(t, string(out), `"z_begin":`, "key names are structure and must survive") + assert.Contains(t, string(out), `"m_body":`) + assert.Contains(t, string(out), `"a_end":`) } // TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview pins the // regression a reviewer found: a review result that quotes the PEM header in one // finding and the footer in another matches the lazy private-key pattern across // members, but nothing is hidden and the review still has to be posted. Only the -// members the match covers are masked, so the verdict survives (#5705). +// string values the match covers are masked, so the document keeps its shape: +// every required finding key (severity, category, file, description) survives, and +// the fields outside the matched span keep their content (#5705). func TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview(t *testing.T) { p := OutputPipeline() begin := "-----BEGIN" + " PRIVATE KEY-----" end := "-----END" + " PRIVATE KEY-----" - doc := []byte(`{"findings":[{"body":"checks for the ` + begin + ` header"},` + - `{"body":"stops at the ` + end + ` footer"}],"verdict":"approve"}`) + doc := []byte(`{"action":"comment","pr_number":12,"repo":"acme/widgets","findings":[` + + `{"severity":"high","category":"logic-error","file":"a.go","description":"quotes the ` + begin + ` header"},` + + `{"severity":"medium","category":"missing-test","file":"b.go","description":"a finding between the markers"},` + + `{"severity":"low","category":"stale-doc","file":"c.go","description":"quotes the ` + end + ` footer"},` + + `{"severity":"info","category":"doc-style","file":"d.go","description":"a finding after the block"}],"body":"summary"}`) out, findings, err := SanitizeJSONDocument(doc, p) require.NoError(t, err) @@ -88,12 +96,81 @@ func TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview(t *testing.T) assert.NotContains(t, string(out), "PRIVATE KEY-----") var result struct { - Findings []map[string]string `json:"findings"` - Verdict string `json:"verdict"` + Action string `json:"action"` + PRNumber int `json:"pr_number"` + Repo string `json:"repo"` + Body string `json:"body"` + Findings []struct { + Severity string `json:"severity"` + Category string `json:"category"` + File string `json:"file"` + Description string `json:"description"` + } `json:"findings"` } require.NoError(t, json.Unmarshal(out, &result), "the sanitized review must still decode: %s", out) - assert.Equal(t, "approve", result.Verdict, "the verdict must survive") - assert.Len(t, result.Findings, 2, "every finding must survive") + assert.Equal(t, "comment", result.Action, "the action must survive") + assert.Equal(t, 12, result.PRNumber) + assert.Equal(t, "acme/widgets", result.Repo) + assert.Equal(t, "summary", result.Body, "a field outside the matched span keeps its content") + require.Len(t, result.Findings, 4, "every finding must survive") + + // The blocking requirement is that the required finding keys still exist in + // every finding: review-result.schema.json declares additionalProperties false + // and requires severity, category, file and description. + for i, finding := range result.Findings { + assert.NotEmpty(t, finding.Severity, "finding %d must keep its severity key", i) + assert.NotEmpty(t, finding.Category, "finding %d must keep its category key", i) + assert.NotEmpty(t, finding.File, "finding %d must keep its file key", i) + assert.NotEmpty(t, finding.Description, "finding %d must keep its description key", i) + } + // Nothing can tell a quoted marker pair from key material fragments, so every + // string value inside the matched span is masked. + assert.Equal(t, "a.go", result.Findings[0].File, "a value before the match keeps its content") + assert.Equal(t, privateKeyMask, result.Findings[0].Description, "the value carrying the marker is masked") + for i := 1; i < 3; i++ { + assert.Equal(t, privateKeyMask, result.Findings[i].File, "finding %d is inside the matched span", i) + } + // A finding after the footer is outside the span and keeps its content. + assert.Equal(t, "d.go", result.Findings[3].File) + assert.Equal(t, "a finding after the block", result.Findings[3].Description) +} + +// TestSanitizeJSONDocument_KeyNameCarryingMarkerIsMasked pins the other half of +// the key rule: a key name is structure and keeps its name, unless the name itself +// carries a block marker. Then the name is block content and cannot be written +// back, while a sibling key between the markers still keeps its name (#5705). +func TestSanitizeJSONDocument_KeyNameCarryingMarkerIsMasked(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + doc := []byte(`{"` + begin + `":"x","severity":"high","` + end + `":"y"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "BEGIN RSA") + assert.NotContains(t, string(out), "END RSA") + assert.Contains(t, string(out), `"severity":`, "a key name between the markers keeps its name") +} + +// TestJSONProvenance_KeysAreStructure pins that the decoded view records which +// leaves are object keys and that a spanning block only covers string values, so +// the rewrite never renames a key unless its own text carries a marker. +func TestJSONProvenance_KeysAreStructure(t *testing.T) { + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + doc := []byte(`{"severity":"` + begin + `","category":"MIIEkeymaterial","file":"` + end + `"}`) + + prov := collectJSONLeaves(doc) + require.Equal(t, len(prov.ranges), len(prov.keys), "every recorded leaf must carry a kind") + spans := prov.spanningPrivateKeys() + require.Equal(t, 1, spans.localized) + assert.Empty(t, spans.maskedKeys, "no key name carries a marker") + require.Len(t, spans.covered, 3, "every string value in the span is masked") + for i := range spans.covered { + assert.False(t, prov.keys[i], "only string values are covered") + } } // TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed pins that a @@ -365,13 +442,15 @@ func TestJSONProvenance_UnmappableBlock(t *testing.T) { end := "-----END RSA" + " PRIVATE KEY-----" v := &jsonProvenance{} v.decoded.WriteString(begin + "\n" + "MIIEkeymaterial" + "\n" + end + "\n") - // One empty leaf, which can never overlap a match. + // One empty string value, which can never overlap a match. v.ranges = []recordSpan{{start: 0, end: 0}} + v.keys = []bool{false} spans := v.spanningPrivateKeys() assert.Equal(t, 1, spans.unmappable) assert.Zero(t, spans.localized) assert.Empty(t, spans.covered) + assert.Empty(t, spans.maskedKeys) } // TestSanitizeJSONDocument_AlreadyMaskedValueNotRemasked pins that rescanning a From 078ffa299c4d69dadca0f722539469cf60525543 Mon Sep 17 00:00:00 2001 From: anevans Date: Fri, 20 Nov 2026 14:06:05 -0500 Subject: [PATCH 30/51] fix(#5705): keep review shape and stop re-scanning redacted JSONL records MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two false positives from the previous pass still lost output while the run exited 0. The JSONL path rescanned the rebuilt stream with the full pattern set. Every value pattern had already been applied to each decoded record, so the rescan re-matched a redaction placeholder followed by JSON escape bytes: in encoded JSON a `\n` escape is two non-space bytes, which lets `env_assignment` run past the end of the value it had just masked. `{"text":"run: API_KEY=secret\nnext"}` was masked correctly and then replaced with the cross-record marker, a benign `export GITHUB_TOKEN=$TOKEN\nnext` record was replaced too, and the finding was counted twice. The rescan now uses `ScanWholeValueSecrets`, the same set the single-document path scans in its written form, so only a registered runtime value or a private-key block — the two shapes that can cross a record boundary — is looked for. A within-record whole-value secret is already handled per record by `SanitizeJSONDocument`, and a block spanning records by `failClosedCrossRecordPrivateKeys`. A private-key block spanning members masked every string value in the matched span, enum-valued fields included. A review result that quotes the PEM header in one finding and the footer in another came back with `"severity":"[REDACTED PRIVATE KEY]"` and `"category":"[REDACTED PRIVATE KEY]"`, so `review-result.schema.json` rejected it and the review was not posted. The span is now masked by content: the members the match starts and ends in carry marker text and are masked unconditionally (a marker split across members leaves only fragments), a value in between is masked when it holds a marker or a base64 run long enough to be PEM body material, and everything else keeps its content. A hex-only run is kept, because a PEM body is base64 and a hex run is more likely a commit SHA or a finding id, both schema-constrained. Tests: `TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview` now validates the sanitized fixture against the review-result schema constraints (enums, patterns, required members, no additional properties) instead of asserting non-empty fields, so the failure this fixes is caught. New coverage for a split block that keeps structural enums, a marker split across members, hex values inside a span, and the two JSONL regressions (a redacted assignment before an escaped newline, and a benign one). Docs: the runtime guide states that a spanning block masks the values carrying key material rather than every covered value, and that the JSONL rescan is limited to whole-value secrets; the user guide no longer says every value inside a matched span is masked. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 32 ++- .../user/run-artifacts-and-private-data.md | 3 +- internal/cli/scan_output_telemetry_test.go | 8 +- internal/security/jsonsanitize.go | 123 ++++++-- internal/security/jsonsanitize_test.go | 265 ++++++++++++++++-- 5 files changed, 366 insertions(+), 65 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 98688e33a8..f37d1f6f7f 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -632,21 +632,33 @@ other pattern has already been applied to the decoded key or leaf, so a match on the serialized bytes would be a redaction placeholder plus JSON escape characters, not a secret. A private-key block spanning members is detected in a decoded view of the document before masking a member value can hide its BEGIN -marker. Such a block is neutralized member by member: every string value the -match covers becomes `[REDACTED PRIVATE KEY]`, while object keys keep their -names, so a document that merely quotes the PEM header in one finding and the -footer in another keeps its shape — every required field of a review result is -still present — instead of being dropped whole. A key name is treated as block -content only when the name itself carries a marker; then it is masked too, -because it cannot be written back as structure. Every string value inside the -matched span is masked, since nothing distinguishes a quoted marker pair from -fragments of real key material. +marker. Such a block is neutralized member by member: every string value that +carries a block marker or base64 body material becomes +`[REDACTED PRIVATE KEY]`, while object keys keep their names, so a document that +merely quotes the PEM header in one finding and the footer in another keeps its +shape — every required field of a review result is still present, and its +enum-valued fields (`action`, `severity`, `category`) keep values +`review-result.schema.json` accepts — instead of being dropped whole or rewritten +into a document the schema rejects. A key name is treated as block content only +when the name itself carries a marker; then it is masked too, because it cannot +be written back as structure. A value that neither carries a marker nor holds a +base64 run long enough to be PEM body material keeps its content: nothing +distinguishes a quoted marker pair from a split block, so the choice is between +masking free text and enum values, which loses the review, and keeping a +fragment too short to be recognized as key material. `.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the record framing; a secret that spans records cannot be redacted without rewriting that framing, so only the records it covers are replaced. A private-key block spanning records is detected in a decoded view of the stream, before per-record masking can remove its BEGIN marker, so a marker written with -\u escapes is still recognized. Localization inside the changed region is +\u escapes is still recognized. After the per-record pass the rebuilt stream is +rescanned, but only for whole-value secrets — registered runtime values and +private-key blocks, the same set the single-document path scans in its written +form. Running the value patterns again would re-match a redaction placeholder +followed by JSON escape bytes: in encoded JSON a `\n` escape is two non-space +bytes, so `env_assignment` runs past the end of a value the record pass already +redacted and every such match would replace a correct record with a cross-record +marker. Localization inside the changed region is conservative but per record: a record is kept only when its bytes are unique in the stream and reappear as a whole line in the redacted stream, because a repeated record could otherwise let an untouched copy stand in for the covered diff --git a/docs/guides/user/run-artifacts-and-private-data.md b/docs/guides/user/run-artifacts-and-private-data.md index c2e2a925c9..be656f8681 100644 --- a/docs/guides/user/run-artifacts-and-private-data.md +++ b/docs/guides/user/run-artifacts-and-private-data.md @@ -349,7 +349,8 @@ business text. When a secret cannot be masked without breaking a file's JSON structure, the affected JSON document or JSONL record is replaced with a JSON error marker; a file whose redacted content cannot be written or computed is replaced by such a marker and fails the run. A marked document or record leaves -its keys in place but masks the string values inside the matched span. When a +its keys in place but masks the string values that carry key material inside the +matched span. When a replacement happens in a run that still exits 0, the job log carries an error annotation to say so — on GitHub Actions only; on GitLab and Forgejo the run's log and exit status are the signal. A write or sanitize failure needs no diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 6b04f5f71d..79e9a69ad4 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -142,7 +142,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-----","MIIEpAIBAAKCAQEA0000000000000000","-----END RSA` + ` PRIVATE KEY-----"]` require.NoError(t, os.WriteFile(jsonFile9, []byte(validJSON9), 0o644)) var buf bytes.Buffer @@ -248,7 +248,7 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { require.NoError(t, err) assert.True(t, json.Valid(content9)) assert.NotContains(t, string(content9), "PRIVATE KEY-----", "split PEM-like material must be masked") - assert.NotContains(t, string(content9), "BASE64_KEY_MATERIAL_REDACTED") + assert.NotContains(t, string(content9), "MIIEpAIBAAKCAQEA", "base64 key material between the markers must be masked") // jq is the parser implicated by the original incident; exercise it when // available, while keeping the Go validity assertions portable. @@ -312,7 +312,7 @@ func TestScanOutputFiles_SingleRecordJSONL_PreservesLineCount(t *testing.T) { 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" + content := ` ["-----BEGIN RSA` + ` PRIVATE KEY-----","MIIEpAIBAAKCAQEA0000000000000000","-----END RSA` + ` PRIVATE KEY-----"]` + "\n" require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{}))) got, err := os.ReadFile(path) @@ -321,7 +321,7 @@ func TestScanOutputFiles_JSONLCrossValuePrivateKeyRemainsValid(t *testing.T) { line := strings.TrimSpace(string(got)) assert.True(t, json.Valid([]byte(line)), "each JSONL record must remain valid JSON: %s", line) assert.NotContains(t, line, "PRIVATE KEY-----", "the members carrying the markers must be masked") - assert.NotContains(t, line, "KEY_MATERIAL_BASE64_VALUE_1234567890") + assert.NotContains(t, line, "MIIEpAIBAAKCAQEA", "base64 key material between the markers must be masked") assert.NotContains(t, line, "output removed", "the record must be kept, not dropped") } diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index c1e785ca72..1c86dc9004 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -29,9 +29,9 @@ const ( OutputRemovalTextJSONMarker = `{"error":"output removed because text redaction would invalidate JSON"}` ) -// privateKeyMask replaces each JSON string value that carries part of a -// private-key block spanning JSON framing, and any key name that carries a -// block marker itself. +// privateKeyMask replaces each JSON string value that carries key material from a +// private-key block spanning JSON framing, and any key name that carries block +// text itself. const privateKeyMask = "[REDACTED PRIVATE KEY]" // outputRemovalMarkers lists every whole-file removal marker with the reason it @@ -165,11 +165,29 @@ var privateKeyRe = func() *regexp.Regexp { panic("private_key structural pattern is missing") }() -// privateKeyMarkerRe matches either boundary line of a private-key block. It -// marks the key names that carry block text instead of JSON structure, so a key -// whose name holds a marker is masked with the values rather than kept. The -// quoted markers are the ones privateKeyRe delimits a block with. -var privateKeyMarkerRe = regexp.MustCompile(`-----BEGIN\s|-----END\s`) +// privateKeyMarkerRe matches a private-key marker line, including the fragments a +// marker is reduced to when it is split across members. It marks the text a +// multi-member block carries into a key name or string value, so nothing that is +// block content is written back as structure. The quoted markers are the ones +// privateKeyRe delimits a block with. +var privateKeyMarkerRe = regexp.MustCompile(`-----BEGIN|-----END|PRIVATE KEY-----`) + +// privateKeyMaterialRe matches a run of PEM body material: the base64 alphabet +// (which covers hex) at a length no ordinary prose word or schema enum reaches. +// A string value covered by a framing-spanning block is masked only when it +// holds a marker or matches this, because a lazy pattern that runs from one +// member's BEGIN to another member's END also covers the members between them. +// Masking those unconditionally replaced structural values — a finding's +// severity, category, action or repo, all of which the review schema constrains +// to enums and patterns — so the review failed validation and was not posted, +// which is the #5705 outcome. Real PEM bodies are 64-character base64 lines (or +// a partial final line), so a 16-character floor keeps every realistic split +// while leaving free text and enum values readable. valueCarriesKeyMaterial still +// has to reject a hex-only run, which is more likely a hash than a PEM line. A +// fragment shorter than the floor cannot be recognized as key material, which is +// the same limit that makes a quoted marker pair indistinguishable from a split +// block. +var privateKeyMaterialRe = regexp.MustCompile(`[A-Za-z0-9+/]{16,}=*`) // jsonProvenance accumulates an order-preserving view of the decoded strings // in a document so a private-key block that spans members can be detected after @@ -224,12 +242,17 @@ type privateKeySpans struct { // // A block whose markers sit in different members is not proof that key material // spans them — a review that quotes the header in one finding and the footer in -// another matches too — so only the members the match covers are touched. String -// values are masked whole, because a value is where an agent writes key -// material. An object key keeps its name unless the name itself carries a block -// marker: key names are the document's structure, and masking them would drop a -// required field such as a finding's severity, category or file and make the -// document fail schema validation. +// another matches too — so only the members the match carries block content into +// are touched. The strings the match starts and ends in carry marker text and are +// masked unconditionally; a string value in between is masked when it holds a +// block marker or base64 body material (valueCarriesKeyMaterial). Those are the +// two shapes key material takes in a member, while the free text and enum values +// between a quoted marker pair stay readable, so a review result keeps its shape +// instead of failing schema validation and being dropped (#5705). An object key +// keeps its name unless the match starts or ends in it, or the name itself carries +// a block marker: key names are the document's structure, and masking them would +// drop a required field such as a finding's severity, category or file and make +// the document fail schema validation. func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { spans := privateKeySpans{covered: map[int]bool{}, maskedKeys: map[int]bool{}} for _, match := range privateKeyRe.FindAllIndex(v.decoded.Bytes(), -1) { @@ -248,19 +271,56 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { continue } spans.localized++ - for _, i := range hit { - if !v.keys[i] { - spans.covered[i] = true + for pos, i := range hit { + // The match begins with a BEGIN marker and ends with an END marker, so + // the leaves it starts and ends in always carry marker text. They are + // masked even when the marker itself is split across two members and + // neither fragment matches privateKeyMarkerRe on its own. + atBoundary := pos == 0 || pos == len(hit)-1 + if v.keys[i] { + if atBoundary || privateKeyMarkerRe.Match(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) { + spans.maskedKeys[i] = true + } continue } - if privateKeyMarkerRe.Match(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) { - spans.maskedKeys[i] = true + if atBoundary || v.valueCarriesKeyMaterial(i) { + spans.covered[i] = true } } } return spans } +// valueCarriesKeyMaterial reports whether the string value at index i has to be +// replaced whole: it carries a block marker, or it holds base64 body material. A +// value outside those two shapes is free text or a schema-constrained token that +// the match only covers because a lazy pattern ran from one member's marker to +// another's, so it keeps its content. +func (v *jsonProvenance) valueCarriesKeyMaterial(i int) bool { + text := v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end] + if privateKeyMarkerRe.Match(text) { + return true + } + run := privateKeyMaterialRe.Find(text) + if run == nil { + return false + } + // A run of hex digits alone is as likely a content hash, a commit SHA or a + // stable finding id as it is key material, and those are schema-constrained + // values (head_sha, id, file). A PEM body is base64, so a real body run + // almost always carries a base64-only character; treating a hex-only run as + // key material would mask a required field and lose the review (#5705). + for _, b := range run { + switch { + case b == '+' || b == '/' || b == '=': + return true + case b >= 'G' && b <= 'Z', b >= 'g' && b <= 'z': + return true + } + } + return false +} + // leafContaining returns the index of the leaf that fully contains [start, end), // or -1 when no single leaf does. func (v *jsonProvenance) leafContaining(start, end int) int { @@ -384,12 +444,25 @@ func SanitizeJSONLines(content []byte, p *Pipeline) ([]byte, []Finding, error) { } rebuilt := out.Bytes() - stream := p.Scan(string(rebuilt)) + // Rescan the rebuilt stream only for the secrets no single record can show. + // The per-record pass has already applied every value pattern to the decoded + // record, so running them again on the encoded stream re-matches a redaction + // placeholder followed by JSON escape characters: in encoded JSON a \n escape + // is two non-space bytes, which lets env_assignment run past the end of the + // decoded value and swallow the next word. Each such match replaced an + // already-correct record — and a record whose only secret was an escaped + // newline — with a cross-record marker, which is exactly the failure + // redactJSONOutput rules out for single documents (#5705). Only whole-value + // secrets (registered runtime values and private-key blocks) can still cross + // a record boundary, so only those are scanned here. + stream := p.ScanWholeValueSecrets(string(rebuilt)) if len(stream.Findings) == 0 { return rebuilt, findings, nil } - // Every finding a single record could account for was handled above, so - // what remains spans a record boundary. + // Every finding a single record could account for was handled above: a + // within-record whole-value secret is caught by SanitizeJSONDocument, and a + // private-key block crossing records by failClosedCrossRecordPrivateKeys. What + // remains spans a record boundary. findings = append(findings, stream.Findings...) return failClosedRecordSpans(rebuilt, spans, stream), findings, nil } @@ -637,9 +710,9 @@ func lineBounded(data []byte, start, end int) bool { // scalar value, and renders a valid JSON document. Unlike map decoding it // keeps member order and duplicate keys, so a secret in an earlier, overwritten // value is still found, and a secret spanning JSON framing stays visible in the -// rewritten bytes. String values and key names that a framing-spanning private -// key covers are replaced whole, which is how such a block is neutralized member -// by member. +// rewritten bytes. String values that a framing-spanning private key carries key +// material into, and key names whose own text carries a block marker, are +// replaced whole, which is how such a block is neutralized member by member. func rewriteJSONTokens(doc []byte, p *Pipeline, spans privateKeySpans) ([]byte, []Finding, error) { dec := json.NewDecoder(bytes.NewReader(doc)) dec.UseNumber() diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 02744b87dd..6ad010242e 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -75,14 +75,19 @@ func TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersMasksCoveredMembers(t // regression a reviewer found: a review result that quotes the PEM header in one // finding and the footer in another matches the lazy private-key pattern across // members, but nothing is hidden and the review still has to be posted. Only the -// string values the match covers are masked, so the document keeps its shape: -// every required finding key (severity, category, file, description) survives, and -// the fields outside the matched span keep their content (#5705). +// values that carry a marker or key material are masked, so the structural values +// the review schema constrains keep theirs — action, repo, severity and category +// included — and the sanitized document still validates against +// schemas/review-result.schema.json. Masking every covered value instead replaced +// those enums with the block marker, so validation failed and the review was not +// posted, which is the #5705 outcome (#5705). func TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview(t *testing.T) { p := OutputPipeline() begin := "-----BEGIN" + " PRIVATE KEY-----" end := "-----END" + " PRIVATE KEY-----" - doc := []byte(`{"action":"comment","pr_number":12,"repo":"acme/widgets","findings":[` + + doc := []byte(`{"action":"comment","pr_number":12,"repo":"acme/widgets",` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01",` + + `"findings":[` + `{"severity":"high","category":"logic-error","file":"a.go","description":"quotes the ` + begin + ` header"},` + `{"severity":"medium","category":"missing-test","file":"b.go","description":"a finding between the markers"},` + `{"severity":"low","category":"stale-doc","file":"c.go","description":"quotes the ` + end + ` footer"},` + @@ -95,6 +100,10 @@ func TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview(t *testing.T) assert.NotContains(t, string(out), "output removed", "the review must not be dropped whole") assert.NotContains(t, string(out), "PRIVATE KEY-----") + // The blocking requirement: the sanitized review still satisfies the schema + // the harness validates before post-review runs. + assertReviewResultSchemaValid(t, out) + var result struct { Action string `json:"action"` PRNumber int `json:"pr_number"` @@ -114,27 +123,100 @@ func TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview(t *testing.T) assert.Equal(t, "summary", result.Body, "a field outside the matched span keeps its content") require.Len(t, result.Findings, 4, "every finding must survive") - // The blocking requirement is that the required finding keys still exist in - // every finding: review-result.schema.json declares additionalProperties false - // and requires severity, category, file and description. - for i, finding := range result.Findings { - assert.NotEmpty(t, finding.Severity, "finding %d must keep its severity key", i) - assert.NotEmpty(t, finding.Category, "finding %d must keep its category key", i) - assert.NotEmpty(t, finding.File, "finding %d must keep its file key", i) - assert.NotEmpty(t, finding.Description, "finding %d must keep its description key", i) - } - // Nothing can tell a quoted marker pair from key material fragments, so every - // string value inside the matched span is masked. + // Only the values that carry a marker are masked; the free text between the + // quoted markers is not key material and keeps its content. + assert.Equal(t, "high", result.Findings[0].Severity, "a structural enum before the match keeps its value") assert.Equal(t, "a.go", result.Findings[0].File, "a value before the match keeps its content") assert.Equal(t, privateKeyMask, result.Findings[0].Description, "the value carrying the marker is masked") - for i := 1; i < 3; i++ { - assert.Equal(t, privateKeyMask, result.Findings[i].File, "finding %d is inside the matched span", i) - } - // A finding after the footer is outside the span and keeps its content. - assert.Equal(t, "d.go", result.Findings[3].File) + assert.Equal(t, "a finding between the markers", result.Findings[1].Description, + "free text between a quoted marker pair is not key material") + assert.Equal(t, privateKeyMask, result.Findings[2].Description, "the value carrying the footer is masked") + assert.Equal(t, "d.go", result.Findings[3].File, "a finding after the footer is outside the span") assert.Equal(t, "a finding after the block", result.Findings[3].Description) } +// TestSanitizeJSONDocument_KeyMaterialInSpanKeepsStructuralEnums pins the other +// half of the rule: when the block really is split across members, the values +// carrying key material are masked, while the structural values the review schema +// constrains keep theirs so the review can still be posted (#5705). +func TestSanitizeJSONDocument_KeyMaterialInSpanKeepsStructuralEnums(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + doc := []byte(`{"action":"request-changes","pr_number":12,"repo":"acme/widgets",` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","findings":[` + + `{"severity":"high","category":"secret-exposure","file":"a.go","description":"leaked ` + begin + `"},` + + `{"severity":"high","category":"secret-exposure","file":"b.go","description":"MIIEpAIBAAKCAQEA0123456789abcdef"},` + + `{"severity":"high","category":"secret-exposure","file":"c.go","description":"and ` + end + `"}],"body":"remove it"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "output removed", "the review must not be dropped whole") + assert.NotContains(t, string(out), "PRIVATE KEY-----") + assert.NotContains(t, string(out), "MIIEpAIBAAKCAQEA", "the key material must not survive") + assertReviewResultSchemaValid(t, out) + + var result struct { + Findings []struct { + Severity string `json:"severity"` + Category string `json:"category"` + File string `json:"file"` + Description string `json:"description"` + } `json:"findings"` + } + require.NoError(t, json.Unmarshal(out, &result)) + require.Len(t, result.Findings, 3) + for i, finding := range result.Findings { + assert.Equal(t, "high", finding.Severity, "finding %d must keep its severity enum", i) + assert.Equal(t, "secret-exposure", finding.Category, "finding %d must keep its category enum", i) + assert.NotEmpty(t, finding.File, "finding %d must keep its file", i) + assert.NotEmpty(t, finding.Description, "finding %d must keep its description", i) + } +} + +// TestSanitizeJSONDocument_MarkerSplitAcrossMembersMasked pins that a marker +// written in pieces does not survive: the leaves the match starts and ends in are +// always masked, and a value carrying only a marker fragment is masked too, so no +// piece of the block header or footer is written back (#5705). +func TestSanitizeJSONDocument_MarkerSplitAcrossMembersMasked(t *testing.T) { + p := OutputPipeline() + doc := []byte(`["-----BEGIN"," RSA PRIVATE KEY-----","MIIEb2R5","-----END"," RSA PRIVATE KEY-----"]`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "-----BEGIN") + assert.NotContains(t, string(out), "-----END") + assert.NotContains(t, string(out), "PRIVATE KEY-----") +} + +// TestSanitizeJSONDocument_HexValuesInSpanKeepTheirContent pins that a hex run +// inside a quoted marker span is not treated as key material. A commit SHA or a +// finding id is schema-constrained (head_sha, id), and a PEM body is base64, so a +// hex-only run is far more likely a hash than a PEM line (#5705). +func TestSanitizeJSONDocument_HexValuesInSpanKeepTheirContent(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + doc := []byte(`{"action":"comment","pr_number":12,"repo":"acme/widgets","findings":[` + + `{"severity":"high","category":"logic-error","file":"a.go","id":"f_0123456789abcdef0123456789abcdef","description":"quotes the ` + begin + ` header"},` + + `{"severity":"low","category":"doc-style","file":"b.go","id":"f_0123456789abcdef0123456789abcdef","description":"and the ` + end + ` footer"}],` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","body":"summary"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.Contains(t, string(out), `"head_sha":"abcdef0123456789abcdef0123456789abcdef01"`, + "a commit SHA is not PEM body material") + assert.Contains(t, string(out), `"id":"f_0123456789abcdef0123456789abcdef"`, + "a finding id is not PEM body material") + assert.NotContains(t, string(out), "PRIVATE KEY-----") +} + // TestSanitizeJSONDocument_KeyNameCarryingMarkerIsMasked pins the other half of // the key rule: a key name is structure and keeps its name, unless the name itself // carries a block marker. Then the name is block content and cannot be written @@ -155,22 +237,24 @@ func TestSanitizeJSONDocument_KeyNameCarryingMarkerIsMasked(t *testing.T) { } // TestJSONProvenance_KeysAreStructure pins that the decoded view records which -// leaves are object keys and that a spanning block only covers string values, so -// the rewrite never renames a key unless its own text carries a marker. +// leaves are object keys, that a spanning block only covers string values, and +// that a value between the markers is covered only when it carries key material, +// so the rewrite never renames a key unless its own text carries a marker. func TestJSONProvenance_KeysAreStructure(t *testing.T) { begin := "-----BEGIN RSA" + " PRIVATE KEY-----" end := "-----END RSA" + " PRIVATE KEY-----" - doc := []byte(`{"severity":"` + begin + `","category":"MIIEkeymaterial","file":"` + end + `"}`) + doc := []byte(`{"severity":"` + begin + `","category":"MIIEpAIBAAKCAQEA0123456789abcdef","body":"x","file":"` + end + `"}`) prov := collectJSONLeaves(doc) require.Equal(t, len(prov.ranges), len(prov.keys), "every recorded leaf must carry a kind") spans := prov.spanningPrivateKeys() require.Equal(t, 1, spans.localized) assert.Empty(t, spans.maskedKeys, "no key name carries a marker") - require.Len(t, spans.covered, 3, "every string value in the span is masked") + require.Len(t, spans.covered, 3, "the marker and the key-material values are covered") for i := range spans.covered { assert.False(t, prov.keys[i], "only string values are covered") } + assert.False(t, spans.covered[5], "free text between the markers is not key material") } // TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed pins that a @@ -262,7 +346,42 @@ func TestSanitizeJSONLines_CrossRecordRuntimeSecretFailsClosed(t *testing.T) { } } -// TestSanitizeJSONLines_DisjointCrossRecordMatchesKeepCleanRecord pins that +// TestSanitizeJSONLines_RedactedAssignmentBeforeEscapedNewlineKeepsRecord pins +// that the whole-stream rescan cannot re-match a value the per-record pass +// already redacted. In encoded JSON a \n escape is two non-space bytes, so +// running env_assignment over the rebuilt stream matched the placeholder plus +// the next word, and the correctly redacted record was replaced with a +// cross-record marker — a false alarm that dropped real content from +// transcripts/*.jsonl and output.jsonl (#5705). +func TestSanitizeJSONLines_RedactedAssignmentBeforeEscapedNewlineKeepsRecord(t *testing.T) { + p := OutputPipeline() + content := []byte(`{"type":"assistant","text":"run: API_KEY=supersecretvalue123\nnext line"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.Len(t, findings, 1, "one secret must be reported once, not recounted by the stream rescan: %+v", findings) + assert.Equal(t, "env_assignment", findings[0].Name) + + line := strings.TrimSpace(string(out)) + assert.True(t, json.Valid([]byte(line)), "the record must stay valid JSON: %s", line) + assert.NotContains(t, line, "output removed", "a redacted record must not be replaced") + assert.NotContains(t, line, "supersecretvalue123") + assert.Contains(t, line, "next line", "the text after the escaped newline must survive") +} + +// TestSanitizeJSONLines_BenignEscapedAssignmentKeepsRecord pins the benign half +// of the same regression: a shell command with an escaped newline contains no +// secret at all, and the per-record pass leaves it alone (#5705). +func TestSanitizeJSONLines_BenignEscapedAssignmentKeepsRecord(t *testing.T) { + p := OutputPipeline() + content := []byte(`{"text":"export GITHUB_TOKEN=$TOKEN\nnext line"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.Empty(t, findings, "no secret is present, so nothing may be reported") + assert.Equal(t, string(content), string(out), "a benign record must be written back unchanged") +} + // only the records a cross-record match touches are replaced. A single // first-to-last changed region used to swallow every record between two // disjoint matches. @@ -1110,3 +1229,99 @@ func TestSanitizeJSONDocument_DuplicateKeyWithSecretKey(t *testing.T) { assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) assert.NotContains(t, string(out), secret) } + +// review-result.schema.json is authored in fullsend-ai/agents and is not +// vendored here, so the checks below mirror the constraints sanitization can +// break in a review result: the enums and patterns of the structural fields, +// additionalProperties false, and the required members. Update them when the +// schema's enums change. +var ( + reviewResultActions = []string{"approve", "request-changes", "comment", "reject", "failure"} + reviewResultSeverities = []string{"critical", "high", "medium", "low", "info"} + reviewResultCategories = []string{ + "logic-error", "nil-deref", "off-by-one", "edge-case", "api-contract", "missing-test", + "test-inadequate", "pattern-violation", "test-weakened", "test-removed", "mock-loosened", + "assertion-weakened", "coverage-reduced", "test-poisoning", "split-payload", "stale-reference", + "auth-bypass", "rbac-violation", "data-exposure", "privilege-escalation", "injection-vuln", + "sandbox-escape", "xss", "ssrf", "insecure-deserialization", "prompt-injection", + "unicode-steganography", "bidi-override", "homoglyph-attack", "instruction-smuggling", "fail-open", + "permission-expansion", "permission-reduction", "role-escalation", "workflow-permission", + "secret-exposure", "scope-exceeded", "tier-mismatch", "unauthorized-change", "scope-creep", + "missing-authorization", "misleading-label", "design-direction", "complexity-ratio", + "misplaced-abstraction", "architectural-conflict", "design-smell", "over-engineering", + "under-engineering", "scope-bundling", "naming-convention", "error-handling-idiom", "api-shape", + "code-organization", "doc-style", "pattern-inconsistency", "stale-doc", "missing-doc", + "incorrect-doc", "incomplete-doc", "breaking-api", "breaking-schema", "breaking-config", + "breaking-cli", "missing-deprecation", "missing-version-bump", "backward-incompatible", + "uxd-evaluate-code-heuristics", "protected-path", "provenance-warning", + "scope-authorization-implicit", "sub-agent-failure", + } +) + +// assertReviewResultSchemaValid checks doc against the review-result schema +// constraints sanitization can break. A review the harness rejects is not posted, +// which is the #5705 outcome, so a fixture that survives sanitization has to still +// satisfy these. +func assertReviewResultSchemaValid(t *testing.T, doc []byte) { + t.Helper() + + var result map[string]json.RawMessage + require.NoError(t, json.Unmarshal(doc, &result), "sanitized review must decode: %s", doc) + + topLevel := map[string]bool{ + "action": true, "pr_number": true, "repo": true, "head_sha": true, "body": true, + "findings": true, "reason": true, "dispositions": true, "label_actions": true, + "risk_assessment": true, "risk_gated": true, + } + for key := range result { + assert.True(t, topLevel[key], "unexpected top-level member %q", key) + } + + var action string + require.NoError(t, json.Unmarshal(result["action"], &action), "action is required") + assert.Contains(t, reviewResultActions, action, "action must be one of the schema enums") + + var repo string + require.NoError(t, json.Unmarshal(result["repo"], &repo), "repo is required") + assert.Regexp(t, `^[a-zA-Z0-9._-]+(/[a-zA-Z0-9._-]+)+$`, repo, "repo must match the schema pattern") + + var prNumber int + require.NoError(t, json.Unmarshal(result["pr_number"], &prNumber), "pr_number is required") + assert.Positive(t, prNumber, "pr_number must be at least 1") + + if action == "comment" || action == "approve" || action == "request-changes" || action == "reject" { + var headSHA, body string + require.NoError(t, json.Unmarshal(result["head_sha"], &headSHA), "%s requires head_sha", action) + require.NoError(t, json.Unmarshal(result["body"], &body), "%s requires body", action) + assert.Regexp(t, `^[0-9a-fA-F]{40}$|^[0-9a-fA-F]{64}$`, headSHA, "head_sha must match the schema pattern") + assert.NotEmpty(t, body, "body must be at least one character") + } + + rawFindings, hasFindings := result["findings"] + if !hasFindings { + assert.NotContains(t, []string{"request-changes", "reject"}, action, "%s requires findings", action) + return + } + var findings []map[string]json.RawMessage + require.NoError(t, json.Unmarshal(rawFindings, &findings), "findings must be an array of objects") + require.NotEmpty(t, findings, "findings must not be empty") + + allowedFinding := map[string]bool{ + "severity": true, "category": true, "file": true, "line": true, "description": true, + "remediation": true, "actionable": true, "id": true, "dimension": true, + } + for i, finding := range findings { + for key := range finding { + assert.True(t, allowedFinding[key], "finding %d has unexpected member %q", i, key) + } + var severity, category, file, description string + require.NoError(t, json.Unmarshal(finding["severity"], &severity), "finding %d requires severity", i) + require.NoError(t, json.Unmarshal(finding["category"], &category), "finding %d requires category", i) + require.NoError(t, json.Unmarshal(finding["file"], &file), "finding %d requires file", i) + require.NoError(t, json.Unmarshal(finding["description"], &description), "finding %d requires description", i) + assert.Contains(t, reviewResultSeverities, severity, "finding %d severity must be one of the schema enums", i) + assert.Contains(t, reviewResultCategories, category, "finding %d category must be one of the schema enums", i) + assert.NotEmpty(t, file, "finding %d file must be at least one character", i) + assert.NotEmpty(t, description, "finding %d description must be at least one character", i) + } +} From ac8de2f19ee5bd4d32d83f6241c1936b93fea7f3 Mon Sep 17 00:00:00 2001 From: anevans Date: Fri, 20 Nov 2026 14:08:41 -0500 Subject: [PATCH 31/51] docs(#5705): describe masking a spanning block by content The runtime guide still described the previous whole-span mask. It now states that the members the match starts and ends in are always masked, a value between them only when it carries a marker or base64 body material, and that a hex-only run is kept because a PEM body is base64 while a hex run is more likely a commit SHA or a finding id. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 33 ++++++++++++--------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index f37d1f6f7f..fe3a49238c 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -632,20 +632,25 @@ other pattern has already been applied to the decoded key or leaf, so a match on the serialized bytes would be a redaction placeholder plus JSON escape characters, not a secret. A private-key block spanning members is detected in a decoded view of the document before masking a member value can hide its BEGIN -marker. Such a block is neutralized member by member: every string value that -carries a block marker or base64 body material becomes -`[REDACTED PRIVATE KEY]`, while object keys keep their names, so a document that -merely quotes the PEM header in one finding and the footer in another keeps its -shape — every required field of a review result is still present, and its -enum-valued fields (`action`, `severity`, `category`) keep values -`review-result.schema.json` accepts — instead of being dropped whole or rewritten -into a document the schema rejects. A key name is treated as block content only -when the name itself carries a marker; then it is masked too, because it cannot -be written back as structure. A value that neither carries a marker nor holds a -base64 run long enough to be PEM body material keeps its content: nothing -distinguishes a quoted marker pair from a split block, so the choice is between -masking free text and enum values, which loses the review, and keeping a -fragment too short to be recognized as key material. +marker. Such a block is neutralized member by member. The members the match +starts and ends in carry marker text, so they are always masked — even when a +marker is split across two members and neither fragment looks like one alone. A +string value between them is masked when it carries a block marker or base64 body +material (PEM body lines are base64, and the floor is longer than any prose word +or schema enum); object keys keep their names, so a document that merely quotes +the PEM header in one finding and the footer in another keeps its shape — every +required field of a review result is still present, and its enum-valued fields +(`action`, `severity`, `category`) and patterned fields (`head_sha`, finding +`id`) keep values `review-result.schema.json` accepts — instead of being dropped +whole or rewritten into a document the schema rejects. A key name is treated as +block content only when the match starts or ends in it or the name itself carries +a marker; then it is masked too, because it cannot be written back as structure. A +value that neither carries a marker nor holds a base64 run long enough to be PEM +body material keeps its content: nothing distinguishes a quoted marker pair from a +split block, so the choice is between masking free text and enum values, which +loses the review, and keeping a fragment too short to be recognized as key +material. A hex-only run is kept for the same reason the enum values are: a PEM +body is base64, while a hex run is more likely a commit SHA or a finding id. `.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the record framing; a secret that spans records cannot be redacted without rewriting that framing, so only the records it covers are replaced. A From d8d8e3fa8d78633c6b3e1ba0d545a961263f8d29 Mon Sep 17 00:00:00 2001 From: anevans Date: Fri, 20 Nov 2026 15:22:29 -0500 Subject: [PATCH 32/51] fix(#5705): keep BOM-prefixed JSON on the structural path The plain-text fallback still carried a JSON-validity guard that could not run: a file only reached it after json.Valid on the trimmed content failed, and a document that is valid on its own cannot fail that test. The branch, its marker and its fail-closed reason were dead, while the runtime guide listed the cause as live. BOM-prefixed JSON was the real gap behind it. A UTF-8 BOM is not JSON whitespace, so such a document fell to the text scan, where a redaction can still break its syntax. The structural path now strips the BOM, scans the document, and restores the mark on write, so a clean document still comes back byte for byte. The guard and OutputRemovalTextJSONMarker go away, and the annotation tests pin that a Forgejo Actions run, which sets GITHUB_ACTIONS=true, gets the alert too. Signed-off-by: anevans --- internal/cli/run.go | 21 +++---- internal/cli/scan_output_telemetry_test.go | 71 ++++++++++++++++++---- internal/security/jsonsanitize.go | 45 ++++++++++---- internal/security/jsonsanitize_test.go | 34 ++++++++++- 4 files changed, 133 insertions(+), 38 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index 89906e975e..d97fd50b5d 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7166,9 +7166,11 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri } // Structurally sanitize valid JSON so redaction never breaks JSON - // syntax and fails closed (#5705). Non-JSON files fall through to the - // plain text scan below. - if json.Valid(bytes.TrimSpace(content)) { + // syntax and fails closed (#5705). The test tolerates a leading UTF-8 + // BOM, so a document that carries one is not left to the text scan, + // where a redaction could still break its syntax. Non-JSON files fall + // through to the plain text scan below. + if security.IsJSONDocument(content) { out, jsonFindings, jsonErr := sanitizeJSONDocument(content, pipeline) if jsonErr != nil { writeErrs = append(writeErrs, sanitizeFailure(quiet, path, relPath, jsonErr, &unsanitizable)) @@ -7211,16 +7213,11 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri }) } // Sanitized may be empty when all content was invisible characters. + // Nothing here writes a fail-closed marker: a document that parsed + // as JSON took the structural path above, so this text scan cannot + // turn valid JSON into invalid JSON, and the alert has nothing to + // report. out := result.Sanitized - // A malformed input that still parses as JSON must not be turned - // into invalid JSON by a cross-value text redaction. - 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 = security.OutputRemovalTextJSONMarker - } - alertOnOutputRemoval(printer, []byte(out)) if writeErr := writeFile(path, []byte(out), 0o644); writeErr != nil { writeErrs = append(writeErrs, writeFailure(quiet, path, relPath, writeErr, &unwritable)) } diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 79e9a69ad4..23a37fb431 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -347,24 +347,35 @@ func TestScanOutputFiles_JSONLRawMultilinePEMRemainsValid(t *testing.T) { // TestScanOutputFiles_EmitsAnnotationWhenOutputIsRemoved pins that a whole-file // fail-closed replacement is announced as a workflow annotation. A review lost to // redaction must not pass silently: the run still exits 0, so the annotation is -// the only signal an operator gets (#5705). +// the only signal an operator gets (#5705). Forgejo Actions runners set +// GITHUB_ACTIONS=true too and understand the same workflow command, so they get +// the annotation as well, which is why the check is the variable and not the +// forge. func TestScanOutputFiles_EmitsAnnotationWhenOutputIsRemoved(t *testing.T) { const secret = `"v1","k2"` require.True(t, security.RegisterRuntimeSecret(secret)) t.Cleanup(security.ResetRuntimeSecretsForTest) for name, tc := range map[string]struct { - actions string - want string + env map[string]string + want string }{ "github actions": { - actions: "true", - want: "::error::Output file replaced with a fail-closed marker: redaction would invalidate JSON", + env: map[string]string{"GITHUB_ACTIONS": "true"}, + want: "::error::Output file replaced with a fail-closed marker: redaction would invalidate JSON", }, - "local run": {actions: "", want: ""}, + "forgejo actions": { + env: map[string]string{"GITHUB_ACTIONS": "true", "FORGEJO_ACTIONS": "true"}, + want: "::error::Output file replaced with a fail-closed marker: redaction would invalidate JSON", + }, + "local run": {env: nil, want: ""}, } { t.Run(name, func(t *testing.T) { - t.Setenv("GITHUB_ACTIONS", tc.actions) + t.Setenv("GITHUB_ACTIONS", "") + t.Setenv("FORGEJO_ACTIONS", "") + for key, value := range tc.env { + t.Setenv(key, value) + } dir := t.TempDir() path := filepath.Join(dir, "agent-result.json") // The secret spans the closing quote, comma and next key, so it @@ -454,17 +465,25 @@ func TestScanOutputFiles_EmitsAnnotationForJSONLRecordRemoval(t *testing.T) { "{\"event\":\"end\",\"text\":\"" + end + "\"}\n" for name, tc := range map[string]struct { - actions string - want string + env map[string]string + want string }{ "github actions": { - actions: "true", - want: "::error::Output record replaced with a fail-closed marker: a secret spanned multiple records", + env: map[string]string{"GITHUB_ACTIONS": "true"}, + want: "::error::Output record replaced with a fail-closed marker: a secret spanned multiple records", }, - "local run": {actions: "", want: ""}, + "forgejo actions": { + env: map[string]string{"GITHUB_ACTIONS": "true", "FORGEJO_ACTIONS": "true"}, + want: "::error::Output record replaced with a fail-closed marker: a secret spanned multiple records", + }, + "local run": {env: nil, want: ""}, } { t.Run(name, func(t *testing.T) { - t.Setenv("GITHUB_ACTIONS", tc.actions) + t.Setenv("GITHUB_ACTIONS", "") + t.Setenv("FORGEJO_ACTIONS", "") + for key, value := range tc.env { + t.Setenv(key, value) + } dir := t.TempDir() path := filepath.Join(dir, "transcript.jsonl") require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) @@ -608,3 +627,29 @@ func TestScanOutputFiles_WriteFailureRemovesUnredactedBytes(t *testing.T) { assert.NotContains(t, string(got), secret, "the unredacted bytes must not survive a write failure") assert.JSONEq(t, `{"error":"output removed because it could not be redacted"}`, string(got)) } + +// TestScanOutputFiles_SanitizesBOMPrefixedJSONStructurally pins that a JSON +// document that starts with a UTF-8 BOM still takes the structural path. The BOM +// is not JSON whitespace, so before this it fell through to the plain-text scan, +// which cannot guarantee the document keeps valid JSON syntax (#5705). +func TestScanOutputFiles_SanitizesBOMPrefixedJSONStructurally(t *testing.T) { + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + doc := `{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `","verdict":"approve"}` + + dir := t.TempDir() + path := filepath.Join(dir, "agent-result.json") + require.NoError(t, os.WriteFile(path, append([]byte("\ufeff"), doc...), 0o644)) + + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{}))) + + got, err := os.ReadFile(path) + require.NoError(t, err) + bom := []byte("\ufeff") + require.True(t, bytes.HasPrefix(got, bom), "a BOM-prefixed file keeps its encoding mark: %q", got) + body := bytes.TrimPrefix(got, bom) + assert.True(t, json.Valid(body), "the sanitized document must stay valid JSON: %s", body) + assert.NotContains(t, string(body), "BEGIN RSA") + assert.NotContains(t, string(body), "MIIEpAIBAAKCAQEA") + assert.Contains(t, string(body), `"verdict":"approve"`, "a member outside the block must survive") +} diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 1c86dc9004..6a2103e457 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -21,12 +21,6 @@ const ( failClosedInvalidJSON = `{"error":"output removed because redaction would invalidate JSON"}` failClosedCrossRecordJSON = `{"error":"output removed because output contained a cross-record secret"}` failClosedSpansMembersJSON = `{"error":"output removed because a private key block spans JSON framing"}` - - // OutputRemovalTextJSONMarker replaces a whole file whose plain-text - // redaction would leave the JSON it started as syntactically broken. The CLI - // writes it on the fallback path for files the structural path cannot - // handle. - OutputRemovalTextJSONMarker = `{"error":"output removed because text redaction would invalidate JSON"}` ) // privateKeyMask replaces each JSON string value that carries key material from a @@ -34,6 +28,31 @@ const ( // text itself. const privateKeyMask = "[REDACTED PRIVATE KEY]" +// utf8BOM is the encoding mark some tooling writes at the start of a UTF-8 +// file. encoding/json does not accept it as leading content, so a document that +// carries one has to lose the prefix before it can be parsed and get it back on +// write. Without that, the file falls through to the plain-text scan, where a +// redaction can still break the JSON syntax the BOM was hiding (#5705). +var utf8BOM = []byte{0xEF, 0xBB, 0xBF} + +// IsJSONDocument reports whether doc is one JSON document, tolerating a leading +// UTF-8 BOM. SanitizeJSONDocument uses the same test, so callers route exactly +// the documents here that it will treat structurally. +func IsJSONDocument(doc []byte) bool { + return json.Valid(bytes.TrimSpace(bytes.TrimPrefix(doc, utf8BOM))) +} + +// restoreBOM puts back the UTF-8 BOM the structural path strips, so a +// BOM-prefixed file keeps its encoding mark. +func restoreBOM(original, sanitized []byte) []byte { + if !bytes.HasPrefix(original, utf8BOM) { + return sanitized + } + out := make([]byte, 0, len(utf8BOM)+len(sanitized)) + out = append(out, utf8BOM...) + return append(out, sanitized...) +} + // outputRemovalMarkers lists every whole-file removal marker with the reason it // states. var outputRemovalMarkers = []struct { @@ -42,7 +61,6 @@ var outputRemovalMarkers = []struct { {failClosedInvalidJSON, "redaction would invalidate JSON"}, {failClosedCrossRecordJSON, "a secret spanned multiple records"}, {failClosedSpansMembersJSON, "a private key block spans JSON framing"}, - {OutputRemovalTextJSONMarker, "text redaction would invalidate JSON"}, } // OutputRemoval reports whether sanitized is a whole-file removal marker and @@ -99,10 +117,13 @@ const redactedJSONKey = "redacted" // a map and re-encoded: that keeps member order and duplicate keys, so a // secret that spans JSON framing is still visible in the rewritten bytes. func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { - trimmed := bytes.TrimSpace(doc) - if len(trimmed) == 0 || !json.Valid(trimmed) { + if !IsJSONDocument(doc) { return doc, nil, nil } + // A BOM is framing rather than content: the token walk cannot parse it, and + // every return below puts it back, so it is stripped once here. + body := bytes.TrimPrefix(doc, utf8BOM) + trimmed := bytes.TrimSpace(body) // A block that spans members is invisible to both the leaf scan and the // written-bytes scan once a member is masked, and its markers may be // \u-escaped in the raw bytes. The decoded view is the only place it is @@ -112,7 +133,7 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { // The view is built from the leaves themselves, so localization should // never fail. If the walks ever disagree, fail closed rather than write // bytes that may still carry the block. - return preserveTrailingNewline([]byte(failClosedSpansMembersJSON), doc), + return restoreBOM(doc, preserveTrailingNewline([]byte(failClosedSpansMembersJSON), doc)), []Finding{privateKeySpanFinding(spans.unmappable, false)}, nil } rebuilt, findings, err := rewriteJSONTokens(trimmed, p, spans) @@ -122,7 +143,7 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { // so the caller fails closed instead of writing unscanned bytes. return nil, nil, fmt.Errorf("could not sanitize JSON document: %w", err) } - out := doc + out := body if len(findings) > 0 || spans.localized > 0 { out = rebuilt } @@ -134,7 +155,7 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { // JSON framing (for example a PEM block split across members) and so cannot // be mapped back to a single leaf. sanitizedOut, outputFindings := redactJSONOutput(out, p) - return preserveTrailingNewline(sanitizedOut, doc), append(findings, outputFindings...), nil + return restoreBOM(doc, preserveTrailingNewline(sanitizedOut, body)), append(findings, outputFindings...), nil } // privateKeySpanFinding reports the private-key blocks that span JSON framing. diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 6ad010242e..5f164a228d 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -1,6 +1,7 @@ package security import ( + "bytes" "encoding/json" "fmt" "strings" @@ -524,7 +525,6 @@ func TestOutputRemoval(t *testing.T) { "invalid json": {failClosedInvalidJSON + "\n", "redaction would invalidate JSON", true}, "cross-record": {failClosedCrossRecordJSON, "a secret spanned multiple records", true}, "spans members": {failClosedSpansMembersJSON, "a private key block spans JSON framing", true}, - "text fallback": {OutputRemovalTextJSONMarker + "\r\n", "text redaction would invalidate JSON", true}, "ordinary doc": {`{"error":"not a removal marker"}`, "", false}, "not json": {"plain prose", "", false}, "empty": {"", "", false}, @@ -1325,3 +1325,35 @@ func assertReviewResultSchemaValid(t *testing.T, doc []byte) { assert.NotEmpty(t, description, "finding %d description must be at least one character", i) } } + +// TestSanitizeJSONDocument_KeepsBOM pins that a document carrying a UTF-8 BOM is +// sanitized structurally and keeps its encoding mark. The BOM is not JSON +// whitespace, so without this the document falls through to the plain-text scan, +// which is the scan that cannot guarantee JSON syntax stays intact (#5705). +func TestSanitizeJSONDocument_KeepsBOM(t *testing.T) { + p := OutputPipeline() + bom := []byte("\ufeff") + + clean := append(append([]byte{}, bom...), []byte(`{"verdict":"approve"}`)...) + out, findings, err := SanitizeJSONDocument(clean, p) + require.NoError(t, err) + assert.Empty(t, findings) + assert.Equal(t, clean, out, "a clean BOM-prefixed document must be returned unchanged") + + dirty := append(append([]byte{}, bom...), []byte(`{"token":"ghp_FAKEtesttoken000000000000000000000000"}`)...) + out, findings, err = SanitizeJSONDocument(dirty, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, bytes.HasPrefix(out, bom), "the BOM must survive the rewrite: %q", out) + assert.True(t, json.Valid(bytes.TrimPrefix(out, bom)), "sanitized document must stay valid JSON: %s", out) + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") +} + +// TestOutputRemoval_NoPlainTextReason pins that the plain-text marker the CLI no +// longer writes is not a recognized reason. A document that parses as JSON takes +// the structural path, so every remaining fail-closed reason is structural. +func TestOutputRemoval_NoPlainTextReason(t *testing.T) { + reason, removed := OutputRemoval([]byte(`{"error":"output removed because text redaction would invalidate JSON"}`)) + assert.False(t, removed, "the removed plain-text marker must not be recognized") + assert.Empty(t, reason) +} From 7ea095bfee4830d318a489f5acf2fc9925f0b102 Mon Sep 17 00:00:00 2001 From: anevans Date: Fri, 20 Nov 2026 15:23:09 -0500 Subject: [PATCH 33/51] docs(#5705): correct the fail-closed outcomes and the scan scope The user guide said a marked document keeps its keys, but every fail-closed marker replaces the whole document or record; only the spanning-block path keeps keys. It also said the error annotation is GitHub-only, while the check is GITHUB_ACTIONS, which Forgejo Actions sets as well. The contributor guide said the scan walks output/, but it walks the run directory, iteration-N/ transcripts included. It also listed a text-redaction fail-closed cause that no longer exists. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 22 +++++++++++-------- .../user/run-artifacts-and-private-data.md | 19 ++++++++-------- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 3a959e870d..6878ff8749 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -617,10 +617,13 @@ origins and warnings are documented in ### The post-run output scan `scanOutputFiles` runs the output pipeline (Unicode normalization, then secret -redaction) over every file under `output/` except the skips above, any -directory named `security` (which holds `findings.jsonl`), and the telemetry -JSONL. Valid JSON is sanitized structurally so redaction -never changes its syntax: every object key and scalar leaf is scanned +redaction) over every file under the run directory (`/`, including +`iteration-N/` transcripts) except the skips above, any directory named +`security` (which holds `findings.jsonl`), and the telemetry +JSONL. Valid JSON is sanitized structurally so redaction never changes its +syntax. A leading UTF-8 BOM does not send a document to the text scan either: +it is stripped before the token walk and restored on write, and a clean document +comes back byte for byte. The walk visits every object key and scalar leaf individually through a token-preserving walk that keeps member order and duplicate keys, so an earlier value that map decoding would drop is still scanned, and a secret spanning JSON framing stays visible in the rewritten @@ -672,14 +675,15 @@ unchanged. Some content cannot be redacted in place. A JSON document or JSONL record is replaced with a valid fail-closed marker instead — never with corrupted -syntax — when a private-key block cannot be localized to members, when a match -spans record boundaries, or when a text redaction would leave the document -invalid. Markers look like `{"error":"output removed because …"}` and are logged +syntax — when a private-key block cannot be localized to members or when a +match spans record boundaries. Markers look like +`{"error":"output removed because …"}` and are logged as findings in `security/findings.jsonl`. Because a replaced file or record loses everything the agent wrote into it, and because the run still exits 0, the reason a marker states is also emitted as a `::error::` workflow annotation whenever the -file is written under GitHub Actions: one annotation for a file replaced whole, -and one per distinct reason for a JSONL file whose records were replaced. +job sets `GITHUB_ACTIONS=true` — GitHub Actions and Forgejo Actions both do: one +annotation for a file replaced whole, and one per distinct reason for a JSONL +file whose records were replaced. A sanitized file that cannot be written, and a file that cannot be sanitized at all, do not stop the walk: every remaining file is still scanned and redacted, diff --git a/docs/guides/user/run-artifacts-and-private-data.md b/docs/guides/user/run-artifacts-and-private-data.md index be656f8681..6079bafe1e 100644 --- a/docs/guides/user/run-artifacts-and-private-data.md +++ b/docs/guides/user/run-artifacts-and-private-data.md @@ -345,16 +345,17 @@ Tool results in those files can quote what the agent read, such as the text of a private Jira issue. On a public repository, any signed-in user can download the artifact until it expires. The output scan masks secret literals; it does not remove personal data, customer names or other private -business text. When a secret cannot be masked without breaking a file's JSON -structure, the affected JSON document or JSONL record is replaced with a JSON -error marker; a file whose redacted content cannot be written or computed is -replaced by such a marker and fails the run. A marked document or record leaves -its keys in place but masks the string values that carry key material inside the -matched span. When a +business text. A secret that cannot be localized replaces the whole JSON +document or JSONL record with a JSON error marker, and a file whose redacted +content cannot be written or computed is replaced by such a marker and fails +the run. A private-key block that spans JSON members is handled in place +instead: the keys keep their names, and each string value that carries block +text or base64 key material becomes `[REDACTED PRIVATE KEY]`. When a replacement happens in a run that still exits 0, the job log carries an error -annotation to say so — on GitHub Actions only; on GitLab and Forgejo the run's -log and exit status are the signal. A write or sanitize failure needs no -annotation because the run itself fails. +annotation to say so. The annotation is a workflow command, so it appears +whenever the job sets `GITHUB_ACTIONS=true`, which covers GitHub Actions and +Forgejo Actions; on GitLab the run's log and exit status are the signal. A +write or sanitize failure needs no annotation because the run itself fails. `fullsend run` leaves `output/` untouched. At the end of the job, `fullsend prepare-artifacts` builds a filtered copy at the level you set, and From b0ab1e2832321cb9fe33b204117883b6c174d87d Mon Sep 17 00:00:00 2001 From: anevans Date: Fri, 20 Nov 2026 16:23:14 -0500 Subject: [PATCH 34/51] fix(#5705): stop a hex prefix and free text from deciding key material MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The framing-spanning block check looked only at the first material run in a member value, so a value that prefixed the body with a hash ("sha ") returned false at the hex run. The markers were then masked while the base64 body was written back, and the written-bytes rescan could not see the block any more because its markers were gone. Every run is examined now, so the body is found after the prefix. The 16-character floor also did not separate body material from free text: a long word such as "misconfiguration" and a file path such as "internal/security/jsonsanitize" both reach it and use only base64 characters, so a review that quoted the PEM header in one finding and the footer in another lost its file and description. A run now also has to look like a base64 body — upper case, lower case, a digit, and a character outside the hex range — which a word or a path does not have, while a real body line almost always does. The comment and the runtime guide said the floor alone left prose readable, so both are corrected. Test bodies that carried no digit are made realistic, and the two regressions are pinned by new tests. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 30 ++++--- internal/security/jsonsanitize.go | 79 +++++++++++------- internal/security/jsonsanitize_test.go | 91 ++++++++++++++++++--- 3 files changed, 147 insertions(+), 53 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 6878ff8749..fd9f85beb2 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -638,19 +638,23 @@ decoded view of the document before masking a member value can hide its BEGIN marker. Such a block is neutralized member by member. The members the match starts and ends in carry marker text, so they are always masked — even when a marker is split across two members and neither fragment looks like one alone. A -string value between them is masked when it carries a block marker or base64 body -material (PEM body lines are base64, and the floor is longer than any prose word -or schema enum); object keys keep their names, so a document that merely quotes -the PEM header in one finding and the footer in another keeps its shape — every -required field of a review result is still present, and its enum-valued fields -(`action`, `severity`, `category`) and patterned fields (`head_sha`, finding -`id`) keep values `review-result.schema.json` accepts — instead of being dropped -whole or rewritten into a document the schema rejects. A key name is treated as -block content only when the match starts or ends in it or the name itself carries -a marker; then it is masked too, because it cannot be written back as structure. A -value that neither carries a marker nor holds a base64 run long enough to be PEM -body material keeps its content: nothing distinguishes a quoted marker pair from a -split block, so the choice is between masking free text and enum values, which +string value between them is masked when it carries a block marker or a run that +looks like PEM body material: at least 16 characters of the base64 alphabet that +mix upper case, lower case and digits and include a character outside the hex +range. The length floor alone is not enough — a long word such as +`misconfiguration` and a path such as `internal/security/jsonsanitize` both reach +it while using only base64 characters — so the case and digit mix is what tells +body material from free text. Object keys keep their names, so a document that +merely quotes the PEM header in one finding and the footer in another keeps its +shape — every required field of a review result is still present, and its +enum-valued fields (`action`, `severity`, `category`) and patterned fields +(`head_sha`, finding `id`) keep values `review-result.schema.json` accepts — +instead of being dropped whole or rewritten into a document the schema rejects. A +key name is treated as block content only when the match starts or ends in it or +the name itself carries a marker; then it is masked too, because it cannot be +written back as structure. A value that neither carries a marker nor holds a run +of that shape keeps its content: nothing distinguishes a quoted marker pair from +a split block, so the choice is between masking free text and enum values, which loses the review, and keeping a fragment too short to be recognized as key material. A hex-only run is kept for the same reason the enum values are: a PEM body is base64, while a hex run is more likely a commit SHA or a finding id. diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 6a2103e457..5cf4751e95 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -193,18 +193,21 @@ var privateKeyRe = func() *regexp.Regexp { // privateKeyRe delimits a block with. var privateKeyMarkerRe = regexp.MustCompile(`-----BEGIN|-----END|PRIVATE KEY-----`) -// privateKeyMaterialRe matches a run of PEM body material: the base64 alphabet -// (which covers hex) at a length no ordinary prose word or schema enum reaches. -// A string value covered by a framing-spanning block is masked only when it -// holds a marker or matches this, because a lazy pattern that runs from one -// member's BEGIN to another member's END also covers the members between them. -// Masking those unconditionally replaced structural values — a finding's -// severity, category, action or repo, all of which the review schema constrains -// to enums and patterns — so the review failed validation and was not posted, -// which is the #5705 outcome. Real PEM bodies are 64-character base64 lines (or -// a partial final line), so a 16-character floor keeps every realistic split -// while leaving free text and enum values readable. valueCarriesKeyMaterial still -// has to reject a hex-only run, which is more likely a hash than a PEM line. A +// privateKeyMaterialRe matches a run of candidate PEM body material: the base64 +// alphabet (which covers hex) at a length no short identifier or enum value +// reaches. A string value covered by a framing-spanning block is masked only +// when it holds a marker or a run pemBodyRun accepts, because a lazy pattern that +// runs from one member's BEGIN to another member's END also covers the members +// between them. Masking those unconditionally replaced structural values — a +// finding's severity, category, action or repo, all of which the review schema +// constrains to enums and patterns — so the review failed validation and was not +// posted, which is the #5705 outcome. +// +// The length floor alone does not separate body material from free text: a long +// word ("misconfiguration") and a file path ("internal/security/jsonsanitize") +// both reach 16 characters using only base64 characters, and a path adds a slash +// that reads as base64 padding or division. pemBodyRun therefore also requires +// the case and digit mix a base64 body carries and a word or a path does not. A // fragment shorter than the floor cannot be recognized as key material, which is // the same limit that makes a quoted marker pair indistinguishable from a split // block. @@ -313,33 +316,53 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { } // valueCarriesKeyMaterial reports whether the string value at index i has to be -// replaced whole: it carries a block marker, or it holds base64 body material. A -// value outside those two shapes is free text or a schema-constrained token that -// the match only covers because a lazy pattern ran from one member's marker to -// another's, so it keeps its content. +// replaced whole: it carries a block marker, or one of its runs holds base64 +// body material. A value outside those two shapes is free text or a +// schema-constrained token that the match only covers because a lazy pattern ran +// from one member's marker to another's, so it keeps its content. func (v *jsonProvenance) valueCarriesKeyMaterial(i int) bool { text := v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end] if privateKeyMarkerRe.Match(text) { return true } - run := privateKeyMaterialRe.Find(text) - if run == nil { - return false + // Every run is checked, not only the first. A value can prefix the body with + // a hash or an id (a "sha " note), and stopping at that first + // hex-only run wrote the body back after the markers had been masked, where + // the written-bytes rescan can no longer see the block (#5705). + for _, run := range privateKeyMaterialRe.FindAll(text, -1) { + if pemBodyRun(run) { + return true + } } - // A run of hex digits alone is as likely a content hash, a commit SHA or a - // stable finding id as it is key material, and those are schema-constrained - // values (head_sha, id, file). A PEM body is base64, so a real body run - // almost always carries a base64-only character; treating a hex-only run as - // key material would mask a required field and lose the review (#5705). + return false +} + +// pemBodyRun reports whether run looks like a line of PEM body material rather +// than a hash, an id, a file path or a long word. A base64 body mixes upper case, +// lower case and digits and carries a character outside the hex range, while a +// hex run has no base64-only character, a word such as "misconfiguration" has +// neither an upper-case letter nor a digit, and a path such as +// "internal/security/jsonsanitize" adds a slash but no upper case or digit. +// Requiring the full mix keeps a hex-only run from masking a required field +// (head_sha, id, file) and loses no realistic body: a 64-character line, or a +// partial final line, almost always has all four. +func pemBodyRun(run []byte) bool { + var upper, lower, digit, base64Only bool for _, b := range run { switch { + case b >= 'a' && b <= 'z': + lower = true + base64Only = base64Only || b > 'f' + case b >= 'A' && b <= 'Z': + upper = true + base64Only = base64Only || b > 'F' + case b >= '0' && b <= '9': + digit = true case b == '+' || b == '/' || b == '=': - return true - case b >= 'G' && b <= 'Z', b >= 'g' && b <= 'z': - return true + base64Only = true } } - return false + return upper && lower && digit && base64Only } // leafContaining returns the index of the leaf that fully contains [start, end), diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 5f164a228d..dde28a8737 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -72,6 +72,73 @@ func TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersMasksCoveredMembers(t assert.Contains(t, string(out), `"a_end":`) } +// TestSanitizeJSONDocument_HexPrefixBeforeBodyMaterialMasked pins the regression +// a reviewer found: only the first material run in a value was examined, so a +// value that put a hash before the body ("sha ") returned false at +// the hex run. The markers were masked, the body was written back, and the +// written-bytes rescan could not catch it because the markers were gone (#5705). +func TestSanitizeJSONDocument_HexPrefixBeforeBodyMaterialMasked(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + body := "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcw" + doc := []byte(`{"a":"` + begin + `","b":"sha 0123456789abcdef0123 ` + body + `","c":"` + end + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), body, "a body after a hex prefix must not survive") + assert.NotContains(t, string(out), "0123456789abcdef0123", "the member carrying the block is replaced whole") + + var result struct { + B string `json:"b"` + } + require.NoError(t, json.Unmarshal(out, &result)) + assert.Equal(t, privateKeyMask, result.B, "the member carrying the block is masked") +} + +// TestSanitizeJSONDocument_PathsAndProseBetweenMarkersStayReadable pins the other +// regression a reviewer found: a file path and a long word both reach the +// material floor, so a path such as "internal/security/jsonsanitize" or a word +// such as "misconfiguration" was masked as key material. A quoted marker pair +// carries no secret, and the review has to keep the values its schema requires +// (#5705). +func TestSanitizeJSONDocument_PathsAndProseBetweenMarkersStayReadable(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + path := "internal/security/jsonsanitize" + prose := "a misconfiguration here" + doc := []byte(`{"action":"comment","pr_number":12,"repo":"acme/widgets",` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","findings":[` + + `{"severity":"high","category":"logic-error","file":"a.go","description":"quotes the ` + begin + ` header"},` + + `{"severity":"medium","category":"missing-test","file":"` + path + `","description":"` + prose + `"},` + + `{"severity":"low","category":"stale-doc","file":"c.go","description":"quotes the ` + end + ` footer"}],"body":"summary"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings, "the cross-member marker pair is still reported") + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----") + assertReviewResultSchemaValid(t, out) + + var result struct { + Findings []struct { + Severity string `json:"severity"` + File string `json:"file"` + Description string `json:"description"` + } `json:"findings"` + } + require.NoError(t, json.Unmarshal(out, &result), "the sanitized review must still decode: %s", out) + require.Len(t, result.Findings, 3) + assert.Equal(t, path, result.Findings[1].File, "a path is not PEM body material") + assert.Equal(t, prose, result.Findings[1].Description, "a long word is not PEM body material") + assert.Equal(t, "medium", result.Findings[1].Severity, "the structural enum keeps its value") + assert.Equal(t, privateKeyMask, result.Findings[0].Description, "the value carrying the header is masked") + assert.Equal(t, privateKeyMask, result.Findings[2].Description, "the value carrying the footer is masked") +} + // TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview pins the // regression a reviewer found: a review result that quotes the PEM header in one // finding and the footer in another matches the lazy private-key pattern across @@ -888,13 +955,13 @@ func TestSanitizeJSONDocument_LeafAndSplitPrivateKeysMasked(t *testing.T) { begin := "-----BEGIN RSA" + " PRIVATE KEY-----" end := "-----END RSA" + " PRIVATE KEY-----" doc := []byte(`{"note":"` + begin + `\nMIIEleafkeymaterial\n` + end + `",` + - `"key_start":"` + begin + `","payload":"MIIEspanningkeymaterial","tail":"` + end + `"}`) + `"key_start":"` + begin + `","payload":"MIIEspanningkeymaterial0","tail":"` + end + `"}`) out, findings, err := SanitizeJSONDocument(doc, p) require.NoError(t, err) require.NotEmpty(t, findings) assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) - assert.NotContains(t, string(out), "MIIEspanningkeymaterial") + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") assert.NotContains(t, string(out), "MIIEleafkeymaterial") } @@ -907,7 +974,7 @@ func TestSanitizeJSONLines_SensitiveBeginRecordFailsClosed(t *testing.T) { end := "-----END RSA" + " PRIVATE KEY-----" records := []string{ "{\"key_start\":\"" + begin + "\"}", - "{\"payload\":\"MIIEspanningkeymaterial\"}", + "{\"payload\":\"MIIEspanningkeymaterial0\"}", "{\"tail\":\"" + end + "\"}", } for name, tc := range map[string]struct { @@ -924,7 +991,7 @@ func TestSanitizeJSONLines_SensitiveBeginRecordFailsClosed(t *testing.T) { out, findings, err := SanitizeJSONLines(content, p) require.NoError(t, err) require.NotEmpty(t, findings) - assert.NotContains(t, string(out), "MIIEspanningkeymaterial") + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") assert.NotContains(t, string(out), "END RSA") lines := strings.Split(strings.TrimSuffix(strings.TrimSuffix(string(out), "\n"), "\r"), tc.sep) @@ -947,13 +1014,13 @@ func TestSanitizeJSONDocument_EscapedLeafBlockDoesNotExemptSplitBlock(t *testing end := "-----END RSA" + " PRIVATE KEY-----" escapedBegin := `\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" doc := []byte(`{"note":"` + escapedBegin + `\nMIIEleafkeymaterial\n` + end + `",` + - `"key_start":"` + begin + `","payload":"MIIEspanningkeymaterial","tail":"` + end + `"}`) + `"key_start":"` + begin + `","payload":"MIIEspanningkeymaterial0","tail":"` + end + `"}`) out, findings, err := SanitizeJSONDocument(doc, p) require.NoError(t, err) require.NotEmpty(t, findings) assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) - assert.NotContains(t, string(out), "MIIEspanningkeymaterial", "the spanning block must not survive") + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0", "the spanning block must not survive") assert.NotContains(t, string(out), "MIIEleafkeymaterial", "the escaped leaf block must be redacted") } @@ -964,13 +1031,13 @@ func TestSanitizeJSONLines_EscapedBeginRecordFailsClosed(t *testing.T) { p := OutputPipeline() end := "-----END RSA" + " PRIVATE KEY-----" content := []byte(`{"key_start":"\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + `"}` + "\n" + - `{"payload":"MIIEspanningkeymaterial"}` + "\n" + + `{"payload":"MIIEspanningkeymaterial0"}` + "\n" + `{"tail":"` + end + `"}` + "\n") out, findings, err := SanitizeJSONLines(content, p) require.NoError(t, err) require.NotEmpty(t, findings) - assert.NotContains(t, string(out), "MIIEspanningkeymaterial") + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") assert.NotContains(t, string(out), "END RSA") lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") @@ -1006,13 +1073,13 @@ func TestSanitizeJSONDocument_EscapedMarkersAcrossMembersMasked(t *testing.T) { p := OutputPipeline() end := "-----END RSA" + " PRIVATE KEY-----" doc := []byte(`["\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + - `","MIIEspanningkeymaterial","` + end + `"]`) + `","MIIEspanningkeymaterial0","` + end + `"]`) out, findings, err := SanitizeJSONDocument(doc, p) require.NoError(t, err) require.NotEmpty(t, findings) assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) - assert.NotContains(t, string(out), "MIIEspanningkeymaterial") + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") } // TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersMasked pins that the @@ -1023,13 +1090,13 @@ func TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersMasked(t *testing.T) end := "-----END RSA" + " PRIVATE KEY-----" // U+200B inside the BEGIN marker: not a PEM block in any single form. doc := []byte(`{"begin":"-----\u200bBEGIN RSA` + " PRIVATE KEY-----\"" + - `,"payload":"MIIEspanningkeymaterial","end":"` + end + `"}`) + `,"payload":"MIIEspanningkeymaterial0","end":"` + end + `"}`) out, findings, err := SanitizeJSONDocument(doc, p) require.NoError(t, err) require.NotEmpty(t, findings) assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) - assert.NotContains(t, string(out), "MIIEspanningkeymaterial") + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") } // TestSanitizeJSONDocument_UnterminatedBeginBeforeCompleteBlockMasksBoth pins From fcc90aba034775b86deadf94f5569f9048411c2d Mon Sep 17 00:00:00 2001 From: anevans Date: Mon, 23 Nov 2026 08:45:44 -0500 Subject: [PATCH 35/51] docs(#5705): stop claiming Forgejo surfaces the error annotation Forgejo Actions sets GITHUB_ACTIONS=true, so fullsend writes the same ::error:: workflow command there, but Forgejo has no annotation view. Its act-based runner parses the command and prints the line in the step log, and the exit status stays 0. Reword both docs, the code comments, and the test comment so the guide promises a rendered annotation only on GitHub Actions and describes the log line on Forgejo. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 10 ++++--- .../user/run-artifacts-and-private-data.md | 13 +++++---- internal/cli/run.go | 27 ++++++++++--------- internal/cli/scan_output_telemetry_test.go | 13 ++++----- 4 files changed, 36 insertions(+), 27 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index fd9f85beb2..9760353b23 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -684,10 +684,12 @@ match spans record boundaries. Markers look like `{"error":"output removed because …"}` and are logged as findings in `security/findings.jsonl`. Because a replaced file or record loses everything the agent wrote into it, and because the run still exits 0, the reason -a marker states is also emitted as a `::error::` workflow annotation whenever the -job sets `GITHUB_ACTIONS=true` — GitHub Actions and Forgejo Actions both do: one -annotation for a file replaced whole, and one per distinct reason for a JSONL -file whose records were replaced. +a marker states is also emitted as a `::error::` workflow command whenever the +job sets `GITHUB_ACTIONS=true`: one line for a file replaced whole, and one per +distinct reason for a JSONL file whose records were replaced. GitHub Actions +renders these as error annotations. Forgejo Actions also sets `GITHUB_ACTIONS=true`, +so its runner writes the same lines, but Forgejo has no annotation view: the +runner prints them in the step log and the exit status stays 0. A sanitized file that cannot be written, and a file that cannot be sanitized at all, do not stop the walk: every remaining file is still scanned and redacted, diff --git a/docs/guides/user/run-artifacts-and-private-data.md b/docs/guides/user/run-artifacts-and-private-data.md index 6079bafe1e..3e7d6f5c57 100644 --- a/docs/guides/user/run-artifacts-and-private-data.md +++ b/docs/guides/user/run-artifacts-and-private-data.md @@ -351,11 +351,14 @@ content cannot be written or computed is replaced by such a marker and fails the run. A private-key block that spans JSON members is handled in place instead: the keys keep their names, and each string value that carries block text or base64 key material becomes `[REDACTED PRIVATE KEY]`. When a -replacement happens in a run that still exits 0, the job log carries an error -annotation to say so. The annotation is a workflow command, so it appears -whenever the job sets `GITHUB_ACTIONS=true`, which covers GitHub Actions and -Forgejo Actions; on GitLab the run's log and exit status are the signal. A -write or sanitize failure needs no annotation because the run itself fails. +replacement happens in a run that still exits 0, the job log says so. On GitHub +Actions this is an error annotation: fullsend writes a `::error::` workflow +command whenever the job sets `GITHUB_ACTIONS=true`, and GitHub Actions renders +it. Forgejo Actions also sets `GITHUB_ACTIONS=true`, so the same `::error::` +line is written there, but Forgejo has no annotation view: its runner prints the +line in the step log and the exit status stays 0. On GitLab the line is not +written at all, so the run's log is the signal. A write or sanitize failure +needs no annotation because the run itself fails. `fullsend run` leaves `output/` untouched. At the end of the job, `fullsend prepare-artifacts` builds a filtered copy at the level you set, and diff --git a/internal/cli/run.go b/internal/cli/run.go index d97fd50b5d..51e6883df7 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7248,12 +7248,14 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri return nil } -// alertOnOutputRemoval emits a workflow annotation when an output file was -// replaced whole by a fail-closed marker. Everything the agent wrote into that -// file is gone, and a lost review that only shows up as one scan line is the -// silent failure #5705 set out to fix. Only the marker's fixed reason reaches -// the annotation: a file path or a matched value could carry agent-chosen text -// (ADR 0163). +// alertOnOutputRemoval emits a ::error:: workflow command when an output file +// was replaced whole by a fail-closed marker. Everything the agent wrote into +// that file is gone, and a lost review that only shows up as one scan line is +// the silent failure #5705 set out to fix. GitHub Actions renders the command as +// an error annotation; Forgejo Actions sets GITHUB_ACTIONS too but prints the +// line in the step log, since it has no annotation view. Only the marker's fixed +// reason reaches the line: a file path or a matched value could carry +// agent-chosen text (ADR 0163). func alertOnOutputRemoval(printer *ui.Printer, sanitized []byte) { reason, removed := security.OutputRemoval(sanitized) if !removed || os.Getenv("GITHUB_ACTIONS") != "true" { @@ -7262,12 +7264,13 @@ func alertOnOutputRemoval(printer *ui.Printer, sanitized []byte) { printer.Raw("::error::Output file replaced with a fail-closed marker: " + reason + "\n") } -// alertOnRecordRemoval emits a workflow annotation for each distinct reason a -// JSONL record was replaced with a fail-closed marker. Such a file keeps its -// records, so it is never a whole-file marker, and the record's loss would -// otherwise show up only as one scan line — the silent failure #5705 set out to -// fix. Only the marker's fixed reason reaches the annotation, never a path or a -// matched value (ADR 0163). +// alertOnRecordRemoval emits a ::error:: workflow command for each distinct +// reason a JSONL record was replaced with a fail-closed marker. Such a file +// keeps its records, so it is never a whole-file marker, and the record's loss +// would otherwise show up only as one scan line — the silent failure #5705 set +// out to fix. GitHub Actions renders the command as an annotation; Forgejo +// prints it in the step log. Only the marker's fixed reason reaches the line, +// never a path or a matched value (ADR 0163). func alertOnRecordRemoval(printer *ui.Printer, sanitized []byte) { if os.Getenv("GITHUB_ACTIONS") != "true" { return diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 23a37fb431..41ed13d1cb 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -345,12 +345,13 @@ func TestScanOutputFiles_JSONLRawMultilinePEMRemainsValid(t *testing.T) { } // TestScanOutputFiles_EmitsAnnotationWhenOutputIsRemoved pins that a whole-file -// fail-closed replacement is announced as a workflow annotation. A review lost to -// redaction must not pass silently: the run still exits 0, so the annotation is -// the only signal an operator gets (#5705). Forgejo Actions runners set -// GITHUB_ACTIONS=true too and understand the same workflow command, so they get -// the annotation as well, which is why the check is the variable and not the -// forge. +// fail-closed replacement is announced as a workflow command. A review lost to +// redaction must not pass silently: the run still exits 0, so the line is the +// only signal an operator gets (#5705). Forgejo Actions runners also set +// GITHUB_ACTIONS=true, so the same ::error:: line is written there, which is why +// the check is the variable and not the forge. GitHub Actions renders that line +// as an error annotation; Forgejo has no annotation view, so its runner prints +// the line in the step log and the exit status stays 0. func TestScanOutputFiles_EmitsAnnotationWhenOutputIsRemoved(t *testing.T) { const secret = `"v1","k2"` require.True(t, security.RegisterRuntimeSecret(secret)) From 703e235e58cb03e2100ad9ef0b1ab6873fd6d32a Mon Sep 17 00:00:00 2001 From: anevans Date: Mon, 23 Nov 2026 10:51:01 -0500 Subject: [PATCH 36/51] fix(#5705): mask joined key chunks and report failed quarantine - Mask() falls back to "***" when the prefix carries a quote, so a YAML single-quoted value whose doubled quote falls in the prefix keeps its surrounding quoting intact. - JSONL record-removal annotations are gated on findings, so a clean file that already holds a marker-equal line raises no false error. - A private-key body split into short or digit-free chunks is masked by deciding on the joined text of consecutive values, not one member at a time. - quarantineOutput reports a file it could not replace or remove, and both docs stop claiming unredacted bytes never reach the artifact. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 20 +++- .../user/run-artifacts-and-private-data.md | 4 +- internal/cli/run.go | 39 ++++--- internal/cli/scan_output_telemetry_test.go | 45 ++++++++ internal/security/jsonsanitize.go | 103 ++++++++++++++++-- internal/security/jsonsanitize_test.go | 37 +++++++ internal/security/redactor.go | 7 +- internal/security/scanner_test.go | 12 ++ 8 files changed, 235 insertions(+), 32 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 9760353b23..0436f13d13 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -656,8 +656,16 @@ written back as structure. A value that neither carries a marker nor holds a run of that shape keeps its content: nothing distinguishes a quoted marker pair from a split block, so the choice is between masking free text and enum values, which loses the review, and keeping a fragment too short to be recognized as key -material. A hex-only run is kept for the same reason the enum values are: a PEM -body is base64, while a hex run is more likely a commit SHA or a finding id. +material. Because one member holds only one line of a body, the values between +the boundary members are also decided on their joined text: consecutive +base64-only values are concatenated, and if the result looks like a body line — +upper case, lower case and a base64-only character — every value in that run is +masked. That catches a body split into short or digit-free chunks, while an +object key, a value with punctuation or whitespace, a hex-only run or a lowercase +word breaks the run. A hex-only run is kept for the same reason the enum values +are: a PEM body is base64, while a hex run is more likely a commit SHA or a +finding id. A single isolated fragment below the floor, with no neighbour to join +it to, is still kept. `.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the record framing; a secret that spans records cannot be redacted without rewriting that framing, so only the records it covers are replaced. A @@ -694,9 +702,11 @@ runner prints them in the step log and the exit status stays 0. A sanitized file that cannot be written, and a file that cannot be sanitized at all, do not stop the walk: every remaining file is still scanned and redacted, and the run fails closed afterwards with all failures joined. The file itself is -replaced with a fail-closed marker so the unredacted bytes never reach the -uploaded artifact. In `quiet` mode the affected paths are counted, not named -(ADR 0163). +replaced with a fail-closed marker so the unredacted bytes do not reach the +uploaded artifact when the filesystem allows it; if the marker write and the +fallback removal both fail, that failure is added to the joined error rather +than left unreported, so the run says the unredacted file is still on disk. In +`quiet` mode the affected paths are counted, not named (ADR 0163). ## Agent rule layering diff --git a/docs/guides/user/run-artifacts-and-private-data.md b/docs/guides/user/run-artifacts-and-private-data.md index 3e7d6f5c57..98f960c206 100644 --- a/docs/guides/user/run-artifacts-and-private-data.md +++ b/docs/guides/user/run-artifacts-and-private-data.md @@ -348,7 +348,9 @@ literals; it does not remove personal data, customer names or other private business text. A secret that cannot be localized replaces the whole JSON document or JSONL record with a JSON error marker, and a file whose redacted content cannot be written or computed is replaced by such a marker and fails -the run. A private-key block that spans JSON members is handled in place +the run. If the marker cannot be written and the file cannot be removed either, +the run's error says the unredacted file is still on disk. A private-key block +that spans JSON members is handled in place instead: the keys keep their names, and each string value that carries block text or base64 key material becomes `[REDACTED PRIVATE KEY]`. When a replacement happens in a run that still exits 0, the job log says so. On GitHub diff --git a/internal/cli/run.go b/internal/cli/run.go index 51e6883df7..7354d84c0d 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7146,8 +7146,12 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri } // A record that was replaced with a marker is not a whole-file // marker, so this is the only place its loss reaches an operator. - alertOnRecordRemoval(printer, out) + // The alert is gated on findings so a clean file that already + // contains a marker-equal line (a re-scanned artifact, a fixture, + // or a line the agent wrote on purpose) does not raise a false + // error when this pass removed nothing. if len(jsonLineFindings) > 0 { + alertOnRecordRemoval(printer, out) findingCount += len(jsonLineFindings) for _, f := range jsonLineFindings { if !quiet { @@ -7285,32 +7289,41 @@ func alertOnRecordRemoval(printer *ui.Printer, sanitized []byte) { // (ADR 0163); non-quiet callers name it. func writeFailure(quiet bool, path, relPath string, writeErr error, unwritable *int) error { *unwritable++ - quarantineOutput(path) + quarantineErr := quarantineOutput(path) if quiet { - return fmt.Errorf("could not write sanitized output file") + return errors.Join(errors.New("could not write sanitized output file"), quarantineErr) } - return fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr) + return errors.Join(fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr), quarantineErr) } // sanitizeFailure records a sanitization error and contains the file it could // not sanitize, so the walk continues to the remaining files instead of leaving -// them unredacted. The unredacted bytes must never reach the uploaded artifact, -// so the file is replaced with the marker as on a write failure (#5705). +// them unredacted. The unredacted bytes are replaced with the marker when the +// filesystem allows it, as on a write failure (#5705). func sanitizeFailure(quiet bool, path, relPath string, scanErr error, unsanitizable *int) error { *unsanitizable++ - quarantineOutput(path) + quarantineErr := quarantineOutput(path) if quiet { - return fmt.Errorf("could not sanitize output file") + return errors.Join(errors.New("could not sanitize output file"), quarantineErr) } - return fmt.Errorf("could not sanitize %s: %w", relPath, scanErr) + return errors.Join(fmt.Errorf("could not sanitize %s: %w", relPath, scanErr), quarantineErr) } // quarantineOutput replaces path with the fail-closed marker, removing it if even -// that write fails, so unredacted bytes never reach the uploaded artifact. -func quarantineOutput(path string) { - if err := os.WriteFile(path, []byte(unwritableOutputMarker), 0o644); err != nil { - _ = os.Remove(path) +// that write fails, so unredacted bytes do not reach the uploaded artifact. When +// neither works — a read-only directory is the common case — the original file is +// still on disk, and the returned error says so instead of leaving the failed +// quarantine unreported while the run's failure looks like a plain write error. +func quarantineOutput(path string) error { + if err := os.WriteFile(path, []byte(unwritableOutputMarker), 0o644); err == nil { + return nil + } + if err := os.Remove(path); err != nil { + // No path reaches the message: the file name can be agent-chosen + // (ADR 0163), and the caller already names it when it is safe to. + return errors.New("unredacted output file could not be replaced or removed") } + return nil } // unwritableOutputMarker replaces a file whose sanitized content could not be diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 41ed13d1cb..e28aae2468 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -421,6 +421,29 @@ func TestScanOutputFiles_ReturnsErrorWhenSanitizedWriteFails(t *testing.T) { assert.Contains(t, err.Error(), "could not write sanitized secret.txt") } +// TestScanOutputFiles_ReportsFailedQuarantine pins that a quarantine that cannot +// replace or remove the file is reported: the unredacted bytes are still on disk +// and the run's failure must say so, instead of looking like a plain write error +// (#5705). +func TestScanOutputFiles_ReportsFailedQuarantine(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("permission checks do not apply to root") + } + dir := t.TempDir() + path := filepath.Join(dir, "secret.txt") + require.NoError(t, os.WriteFile(path, []byte("Token: ghp_FAKEtesttoken000000000000000000000000"), 0o444)) + require.NoError(t, os.Chmod(dir, 0o555)) + t.Cleanup(func() { _ = os.Chmod(dir, 0o755) }) + + 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") + assert.Contains(t, err.Error(), "unredacted output file could not be replaced or removed", + "a failed quarantine must reach the joined error") +} + // TestScanOutputFiles_SanitizerErrorContainsFileAndContinues pins that a // sanitizer error is contained the way a write failure is: the file it could not // sanitize is replaced with the marker, the walk continues to the remaining @@ -504,6 +527,28 @@ func TestScanOutputFiles_EmitsAnnotationForJSONLRecordRemoval(t *testing.T) { } } +// TestScanOutputFiles_NoAnnotationForPreexistingMarkerLine pins that a clean +// JSONL file that already holds a marker-equal line raises no error annotation: +// this pass removed nothing, so an operator should not be told a record was lost. +// Such a line is a re-scanned artifact, a fixture, or a line the agent wrote on +// purpose (#5705). +func TestScanOutputFiles_NoAnnotationForPreexistingMarkerLine(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + content := `{"error":"output removed because output contained a cross-record secret"}` + "\n" + + `{"event":"done"}` + "\n" + dir := t.TempDir() + path := filepath.Join(dir, "transcript.jsonl") + require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) + + var output bytes.Buffer + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&output))) + + assert.NotContains(t, output.String(), "::error::", "a clean stream must not raise an annotation") + got, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, content, string(got), "a clean stream must be written back unchanged") +} + func TestScanOutputFiles_QuietJSONWriteFailureIsFatal(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "secret.json") diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 5cf4751e95..b613b46ade 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -207,12 +207,18 @@ var privateKeyMarkerRe = regexp.MustCompile(`-----BEGIN|-----END|PRIVATE KEY---- // word ("misconfiguration") and a file path ("internal/security/jsonsanitize") // both reach 16 characters using only base64 characters, and a path adds a slash // that reads as base64 padding or division. pemBodyRun therefore also requires -// the case and digit mix a base64 body carries and a word or a path does not. A -// fragment shorter than the floor cannot be recognized as key material, which is -// the same limit that makes a quoted marker pair indistinguishable from a split -// block. +// the case and digit mix a base64 body carries and a word or a path does not. +// A single member can hold only one line of the body, so a body split into short +// or digit-free chunks is decided by the joined text of consecutive members +// instead (maskSpanBody). var privateKeyMaterialRe = regexp.MustCompile(`[A-Za-z0-9+/]{16,}=*`) +// pemChunkCandidateRe matches a string value that could be one segment of a PEM +// body: every byte is in the base64 alphabet. A value with whitespace, a hyphen, +// a period or any other punctuation is free text or a structural token, so it +// breaks a run of segments rather than joining one. +var pemChunkCandidateRe = regexp.MustCompile(`^[A-Za-z0-9+/]+=*$`) + // jsonProvenance accumulates an order-preserving view of the decoded strings // in a document so a private-key block that spans members can be detected after // JSON decoding. The raw bytes are not usable for this: a member may encode a @@ -269,14 +275,15 @@ type privateKeySpans struct { // another matches too — so only the members the match carries block content into // are touched. The strings the match starts and ends in carry marker text and are // masked unconditionally; a string value in between is masked when it holds a -// block marker or base64 body material (valueCarriesKeyMaterial). Those are the -// two shapes key material takes in a member, while the free text and enum values -// between a quoted marker pair stay readable, so a review result keeps its shape -// instead of failing schema validation and being dropped (#5705). An object key -// keeps its name unless the match starts or ends in it, or the name itself carries -// a block marker: key names are the document's structure, and masking them would -// drop a required field such as a finding's severity, category or file and make -// the document fail schema validation. +// block marker or base64 body material (valueCarriesKeyMaterial) or when the +// joined text of its neighbours looks like a PEM body line (maskSpanBody). Those +// are the two shapes key material takes in a member, while the free text and enum +// values between a quoted marker pair stay readable, so a review result keeps its +// shape instead of failing schema validation and being dropped (#5705). An object +// key keeps its name unless the match starts or ends in it, or the name itself +// carries a block marker: key names are the document's structure, and masking them +// would drop a required field such as a finding's severity, category or file and +// make the document fail schema validation. func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { spans := privateKeySpans{covered: map[int]bool{}, maskedKeys: map[int]bool{}} for _, match := range privateKeyRe.FindAllIndex(v.decoded.Bytes(), -1) { @@ -295,6 +302,10 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { continue } spans.localized++ + // The middle members are decided together: a body split into chunks + // that are each shorter than the material floor is only recognizable + // once they are joined. + v.maskSpanBody(hit, &spans) for pos, i := range hit { // The match begins with a BEGIN marker and ends with an END marker, so // the leaves it starts and ends in always carry marker text. They are @@ -315,6 +326,46 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { return spans } +// maskSpanBody covers the string values between a framing-spanning block's +// boundary members when their joined text looks like PEM body material. A member +// holds one line of the body, and an agent can split the body so that every line +// is short or digit-free; a per-member test then accepts none of them and writes +// the body back after the markers are masked, where the written-bytes rescan can +// no longer see the block (#5705). Consecutive candidate segments are therefore +// decided together. An object key between two values breaks the run, because a +// key is structure rather than body, and a value with punctuation or whitespace +// breaks it too: those are structural tokens and free text, not body lines. +func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { + var group []int + flush := func() { + if len(group) == 0 { + return + } + joined := make([]byte, 0, len(group)*16) + for _, i := range group { + joined = append(joined, v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]...) + } + if pemBodyJoined(joined) { + for _, i := range group { + spans.covered[i] = true + } + } + group = group[:0] + } + for pos, i := range hit { + if pos == 0 || pos == len(hit)-1 || v.keys[i] { + flush() + continue + } + if !pemChunkCandidateRe.Match(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) { + flush() + continue + } + group = append(group, i) + } + flush() +} + // valueCarriesKeyMaterial reports whether the string value at index i has to be // replaced whole: it carries a block marker, or one of its runs holds base64 // body material. A value outside those two shapes is free text or a @@ -365,6 +416,34 @@ func pemBodyRun(run []byte) bool { return upper && lower && digit && base64Only } +// pemBodyJoined reports whether the concatenated text of consecutive member +// segments looks like PEM body material. It is the check maskSpanBody applies to +// a body split across members: a chunk on its own may be shorter than the +// material floor or carry no digit, but the joined body reconstructs both. It +// does not require a digit, because a single chunk can legitimately be digit-free +// and a body split so that every digit lands in another chunk would otherwise be +// written back. It still requires upper case, lower case and a base64-only +// character, which a hex SHA, a lowercase word, a path and free text do not have. +func pemBodyJoined(joined []byte) bool { + if len(joined) < 16 { + return false + } + var upper, lower, base64Only bool + for _, b := range joined { + switch { + case b >= 'a' && b <= 'z': + lower = true + base64Only = base64Only || b > 'f' + case b >= 'A' && b <= 'Z': + upper = true + base64Only = base64Only || b > 'F' + case b == '+' || b == '/' || b == '=': + base64Only = true + } + } + return upper && lower && base64Only +} + // leafContaining returns the index of the leaf that fully contains [start, end), // or -1 when no single leaf does. func (v *jsonProvenance) leafContaining(start, end int) int { diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index dde28a8737..cb5b2b8de2 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -261,6 +261,43 @@ func TestSanitizeJSONDocument_MarkerSplitAcrossMembersMasked(t *testing.T) { assert.NotContains(t, string(out), "PRIVATE KEY-----") } +// TestSanitizeJSONDocument_ChunkedBodyBetweenMarkersMasked pins the regression a +// reviewer found: a body split across members into chunks that are each short, +// digit-free, or hex-looking was written back after the boundary markers were +// masked, where the written-bytes rescan can no longer see the block. The joined +// text of consecutive values reconstructs the body, so every chunk is masked +// (#5705). +func TestSanitizeJSONDocument_ChunkedBodyBetweenMarkersMasked(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + cases := map[string][]string{ + "short chunks": {"MIIEowIB", "AAKCAQEA", "x9Kq2Lm"}, + "digit-free chunk": {"MIIEowIBAAKCAQEA"}, + "hex chunk in the run": {"MIIEowIBAAKCAQEA", "abcdef0123456789", "short+chunk"}, + } + for name, chunks := range cases { + t.Run(name, func(t *testing.T) { + quoted := make([]string, 0, len(chunks)+2) + quoted = append(quoted, `"`+begin+`"`) + for _, chunk := range chunks { + quoted = append(quoted, `"`+chunk+`"`) + } + quoted = append(quoted, `"`+end+`"`) + doc := []byte(`{"lines":[` + strings.Join(quoted, ",") + `]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----") + for _, chunk := range chunks { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } + }) + } +} + // TestSanitizeJSONDocument_HexValuesInSpanKeepTheirContent pins that a hex run // inside a quoted marker span is not treated as key material. A commit SHA or a // finding id is schema-constrained (head_sha, id), and a PEM body is base64, so a diff --git a/internal/security/redactor.go b/internal/security/redactor.go index 5c8df64e67..4a651ca9ec 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -270,7 +270,12 @@ func Mask(value string) string { return "***" } prefix := value[:4] - if strings.Contains(prefix, "\\") { + // A prefix that carries an escape or a quote delimiter cannot be written + // back: in a JSON or YAML string it would escape or close the surrounding + // quoting and break the document (#5705). The quote case covers a YAML + // single-quoted value whose doubled quote ('') falls inside the prefix: + // keeping half of the pair leaves a lone quote that ends the string early. + if strings.ContainsAny(prefix, "\\'\"") { return "***" } return prefix + "..." diff --git a/internal/security/scanner_test.go b/internal/security/scanner_test.go index 6069b9e110..80a12164fe 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -522,6 +522,18 @@ func TestSecretRedactor(t *testing.T) { assert.NotContains(t, result.Sanitized, "remaining_secret") }) + t.Run("json_field keeps YAML single-quoted value valid when doubled quote falls in the mask prefix", func(t *testing.T) { + // The mask prefix would end on half of the doubled '' pair, leaving a + // lone quote that closes the YAML string early. The value must fall back + // to the fixed placeholder instead (#5705). + result := r.Scan("'api_token': 'abc''defghijk'") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "defghijk") + assert.Equal(t, "'api_token': '***'", result.Sanitized, + "a prefix carrying a quote must not be written back") + }) + t.Run("json_field handles backslash followed by physical newline", func(t *testing.T) { result := r.Scan("'password': 'abcdefgh\\\nijklmnop'") assert.False(t, result.Safe) From 065038e1fc4dce1f706d7274ca9bb711eedfb06d Mon Sep 17 00:00:00 2001 From: anevans Date: Mon, 23 Nov 2026 14:41:14 -0500 Subject: [PATCH 37/51] fix(#5705): keep clean JSONL records and stop json_field swallowing fields - The json_field single-quoted branch for a value ending in a literal backslash is tried before the escape-reading branch and requires a field or line boundary after the closing quote, so a YAML flow mapping such as {'api_key': 'abcdefghi\', 'x': '...'} no longer reads the closing quote as an escape and swallows the field that follows. - JSONL records and the cross-record decoded view drop a leading UTF-8 BOM before the JSON checks, so a BOM-prefixed record carrying a \u-escaped BEGIN marker no longer hides a cross-record private-key block. - The cross-record private-key check replaces only the records that carry block content: the boundary records, plus middle records holding a block marker or PEM body material, decided with the joined-run logic the single-document path uses. A transcript that quotes the header in one record and the footer in another keeps its clean records. Signed-off-by: anevans --- internal/security/jsonsanitize.go | 209 +++++++++++++++++++------ internal/security/jsonsanitize_test.go | 118 +++++++++++++- internal/security/redactor.go | 21 ++- internal/security/scanner_test.go | 13 ++ 4 files changed, 300 insertions(+), 61 deletions(-) diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index b613b46ade..708687f542 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -368,11 +368,17 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { // valueCarriesKeyMaterial reports whether the string value at index i has to be // replaced whole: it carries a block marker, or one of its runs holds base64 -// body material. A value outside those two shapes is free text or a -// schema-constrained token that the match only covers because a lazy pattern ran -// from one member's marker to another's, so it keeps its content. +// body material. func (v *jsonProvenance) valueCarriesKeyMaterial(i int) bool { - text := v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end] + return textCarriesKeyMaterial(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) +} + +// textCarriesKeyMaterial reports whether a decoded key or value's text carries a +// block marker or a run of base64 body material. A leaf outside those two shapes +// is free text or a schema-constrained token that a framing-spanning match only +// covers because a lazy pattern ran from one member's marker to another's, so it +// keeps its content. +func textCarriesKeyMaterial(text []byte) bool { if privateKeyMarkerRe.Match(text) { return true } @@ -536,7 +542,7 @@ func SanitizeJSONLines(content []byte, p *Pipeline) ([]byte, []Finding, error) { switch { case len(trimmed) == 0: out.Write(line) - case json.Valid(trimmed): + case IsJSONDocument(trimmed): record, recordFindings, err := SanitizeJSONDocument(trimmed, p) if err != nil { return nil, findings, fmt.Errorf("could not sanitize JSONL record: %w", err) @@ -596,39 +602,107 @@ type recordSpan struct { start, end int } -// failClosedCrossRecordPrivateKeys replaces every record covered by a -// private-key block that crosses record boundaries with a valid marker. Match -// offsets come straight from the original stream, so localization is exact. +// failClosedCrossRecordPrivateKeys replaces the records that carry part of a +// private-key block crossing record boundaries with a valid marker. Match +// offsets come from a decoded view of the whole stream, so a marker written with +// \u escapes is still recognized, and every match maps back to the records that +// carry it. func failClosedCrossRecordPrivateKeys(content []byte) ([]byte, []Finding) { spans := jsonLineSpans(content) if len(spans) == 0 { return content, nil } - // Match in a decoded, order-preserving view so a marker written with - // \u escapes is still recognized, and keep each record's range in that - // view so a match maps back to the records it covers. - var ( - view bytes.Buffer - viewSpans []recordSpan - ) - for _, span := range spans { - start := view.Len() + covered, findings := newJSONLineView(content, spans).spanningRecordPrivateKeys() + if len(findings) == 0 { + return content, nil + } + var out bytes.Buffer + cursor := 0 + for i, span := range spans { + if !covered[i] { + continue + } + out.Write(content[cursor:span.start]) + out.WriteString(failClosedCrossRecordJSON) + cursor = span.end + } + out.Write(content[cursor:]) + return out.Bytes(), findings +} + +// jsonLineView is an order-preserving, decoded view of a JSONL stream: every +// object key and string value of every record, in document order, with a newline +// between records so nothing a record does not contain can join its neighbours. +// The raw bytes are not usable for cross-record matching: a record may encode a +// marker with \u escapes, and a BOM-prefixed record is not valid JSON until the +// mark is stripped. +type jsonLineView struct { + decoded bytes.Buffer + // records holds each record's range in the view, excluding the separator. + records []recordSpan + // leaves holds every decoded key and string value with the record it came + // from, so a match can be mapped back to whole records. + leaves []jsonLineLeaf +} + +// jsonLineLeaf is one decoded object key or string value in a jsonLineView. +type jsonLineLeaf struct { + record int + span recordSpan + key bool +} + +// newJSONLineView builds the decoded view of a stream whose non-empty records +// start at spans. A record that is one JSON document contributes its decoded +// leaves; anything else contributes its raw text as a single leaf, so a stream of +// PEM text lines is still matched line by line. +func newJSONLineView(content []byte, spans []recordSpan) *jsonLineView { + view := &jsonLineView{} + for i, span := range spans { + start := view.decoded.Len() line := content[span.start:span.end] - if trimmed := bytes.TrimSpace(line); json.Valid(trimmed) { - writeDecodedJSONView(&view, trimmed) + if body := jsonRecordBody(line); json.Valid(body) { + prov := collectJSONLeaves(body) + view.decoded.Write(prov.decoded.Bytes()) + for j, r := range prov.ranges { + view.leaves = append(view.leaves, jsonLineLeaf{ + record: i, + span: recordSpan{start: start + r.start, end: start + r.end}, + key: prov.keys[j], + }) + } } else { - view.Write(line) + view.decoded.Write(line) + if end := view.decoded.Len(); end > start { + view.leaves = append(view.leaves, jsonLineLeaf{record: i, span: recordSpan{start: start, end: end}}) + } } - view.WriteByte('\n') - viewSpans = append(viewSpans, recordSpan{start: start, end: view.Len() - 1}) + view.records = append(view.records, recordSpan{start: start, end: view.decoded.Len()}) + view.decoded.WriteByte('\n') } - matches := privateKeyRe.FindAllIndex(view.Bytes(), -1) - covered := make([]bool, len(spans)) + return view +} + +// spanningRecordPrivateKeys finds the private-key blocks in the decoded view that +// cross a record boundary and reports which records must be replaced. +// +// A block whose markers sit in different records is not proof that key material +// spans them — a transcript that quotes the header in one record and the footer +// in another matches too — so only the records the block carries content into are +// replaced. The records the match starts and ends in always carry marker text and +// are replaced; a record in between is replaced only when its leaves hold a block +// marker or PEM body material (textCarriesKeyMaterial), or when the joined text +// of consecutive leaves looks like a PEM body line (maskMiddleRecordBody). Those +// are the two shapes key material takes, while free text and structural values +// between a quoted marker pair stay readable, so a transcript of work on this very +// code is not gutted. The single-document path localizes the same way (#5705). +func (v *jsonLineView) spanningRecordPrivateKeys() ([]bool, []Finding) { + covered := make([]bool, len(v.records)) var findings []Finding - for _, match := range matches { + for _, match := range privateKeyRe.FindAllIndex(v.decoded.Bytes(), -1) { var hit []int - for i, span := range viewSpans { - if span.end > match[0] && span.start < match[1] { + for i, record := range v.records { + if record.start < match[1] && match[0] < record.end { hit = append(hit, i) } } @@ -641,34 +715,75 @@ func failClosedCrossRecordPrivateKeys(content []byte) ([]byte, []Finding) { Scanner: "secret_redactor", Name: "private_key", Severity: "critical", - Detail: "Private key block spans records and cannot be localized; output removed", + Detail: "Private key block spans records; removed the records carrying block content", }) - for _, i := range hit { - covered[i] = true - } + covered[hit[0]] = true + covered[hit[len(hit)-1]] = true + v.maskMiddleRecordBody(hit, covered) } - if len(findings) == 0 { - return content, nil + return covered, findings +} + +// maskMiddleRecordBody covers the records between a cross-record block's boundary +// records when their leaves carry key material. It is the record-level counterpart +// of maskSpanBody: consecutive candidate leaves are decided together, because a +// body split so that every line is short or digit-free is only recognizable once +// the lines are joined. An object key breaks the run, since a key is structure +// rather than body, and so does a value with punctuation or whitespace: those are +// structural tokens and free text, not body lines. +func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { + first, last := hit[0], hit[len(hit)-1] + var group []int + flush := func() { + if len(group) == 0 { + return + } + joined := make([]byte, 0, len(group)*16) + for _, i := range group { + joined = append(joined, v.decoded.Bytes()[v.leaves[i].span.start:v.leaves[i].span.end]...) + } + if pemBodyJoined(joined) { + for _, i := range group { + covered[v.leaves[i].record] = true + } + } + group = group[:0] } - var out bytes.Buffer - cursor := 0 - for i, span := range spans { - if !covered[i] { + for i, leaf := range v.leaves { + // The boundary records are already covered, and their leaves neither + // extend nor join a middle run. + if leaf.record <= first || leaf.record >= last { + flush() continue } - out.Write(content[cursor:span.start]) - out.WriteString(failClosedCrossRecordJSON) - cursor = span.end + text := v.decoded.Bytes()[leaf.span.start:leaf.span.end] + if leaf.key { + flush() + if privateKeyMarkerRe.Match(text) { + covered[leaf.record] = true + } + continue + } + if textCarriesKeyMaterial(text) { + covered[leaf.record] = true + flush() + continue + } + if !pemChunkCandidateRe.Match(text) { + flush() + continue + } + group = append(group, i) } - out.Write(content[cursor:]) - return out.Bytes(), findings + flush() } -// writeDecodedJSONView appends every decoded object key and string leaf of doc -// to buf in document order, one per line, so a value split across members is -// still visible as one contiguous run of text. -func writeDecodedJSONView(buf *bytes.Buffer, doc []byte) { - buf.Write(collectJSONLeaves(doc).decoded.Bytes()) +// jsonRecordBody returns a JSONL record's JSON body: surrounding whitespace and a +// leading UTF-8 BOM removed. encoding/json rejects a BOM, so a record carrying one +// would otherwise be read as plain text and its \u-escaped markers never decoded, +// which hid a cross-record block and left the key body behind (#5705). +func jsonRecordBody(line []byte) []byte { + return bytes.TrimSpace(bytes.TrimPrefix(bytes.TrimSpace(line), utf8BOM)) } // collectJSONLeaves walks doc and records every decoded object key and string diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index cb5b2b8de2..a6a95b5847 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -796,10 +796,12 @@ func TestSanitizeJSONLines_RepeatedRecordsFailsClosed(t *testing.T) { assert.Equal(t, `{"v":"bbb"}`, lines[4], "an untouched duplicate outside the change must survive") } -// TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch pins the -// inverse misattribution: a clean record that also appears later must not be -// kept in place of the covered copy, and the later clean copy must not be -// dropped for it. +// TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch pins that a +// clean record between a quoted header and footer survives, whether or not it +// repeats later. The cross-record check replaces only the records that carry +// block content, so a record that also appears after the block must not be +// dropped from the match and its copy outside the match must not be attributed to +// it. func TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch(t *testing.T) { p := OutputPipeline() begin := "-----BEGIN RSA" + " PRIVATE KEY-----" @@ -818,11 +820,71 @@ func TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch(t *testing. lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") require.Len(t, lines, 4, "record count must not change") - for _, line := range lines[:3] { + for _, i := range []int{0, 2} { + assert.True(t, json.Valid([]byte(lines[i])), "each replaced record must stay valid JSON: %s", lines[i]) + assert.Contains(t, lines[i], "output removed") + } + assert.Equal(t, `{"value":"middle"}`, lines[1], "a clean record inside the match must survive") + assert.Equal(t, `{"value":"middle"}`, lines[3], "its copy outside the match must survive too") +} + +// TestSanitizeJSONLines_QuotedMarkersKeepCleanRecords pins that a transcript that +// quotes a PEM header in one record and the footer in a later one loses only the +// records that carry block content. Replacing every record the lazy match touches +// gutted a transcript of work on this code — grep output and tool results quoting +// the markers — which is the #5705 outcome the single-document path avoids +// (6dca72790, 078ffa2, b0ab1e2). +func TestSanitizeJSONLines_QuotedMarkersKeepCleanRecords(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + content := []byte( + "{\"event\":\"quote\",\"text\":\"" + begin + "\"}\n" + + "{\"event\":\"normal record one\"}\n" + + "{\"event\":\"normal record two\"}\n" + + "{\"event\":\"quote\",\"text\":\"" + end + "\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), begin) + assert.NotContains(t, string(out), end) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, i := range []int{0, 3} { + assert.True(t, json.Valid([]byte(lines[i])), "each replaced record must stay valid JSON: %s", lines[i]) + assert.Contains(t, lines[i], "output removed") + } + assert.Equal(t, `{"event":"normal record one"}`, lines[1], "a record carrying no block content must survive") + assert.Equal(t, `{"event":"normal record two"}`, lines[2], "a record carrying no block content must survive") +} + +// TestSanitizeJSONLines_BodySplitAcrossRecordsCovered pins the other half: a +// middle record is kept only when it really is clean. A body split so that every +// record holds one short, digit-free chunk is still body material once the chunks +// are joined, and every record carrying it must be replaced. +func TestSanitizeJSONLines_BodySplitAcrossRecordsCovered(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + content := []byte( + "[\"" + begin + "\"]\n" + + "[\"dfghjk\"]\n" + + "[\"QWERTYuiop\"]\n" + + "[\"" + end + "\"]\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "dfghjkQWERTYuiop") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, line := range lines { assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) assert.Contains(t, line, "output removed") } - assert.Equal(t, `{"value":"middle"}`, lines[3], "the repeated clean record outside the match must survive") } // TestSanitizeJSONDocument_SensitiveBeginMemberMasksBlock pins that masking a @@ -1085,6 +1147,50 @@ func TestSanitizeJSONLines_EscapedBeginRecordFailsClosed(t *testing.T) { } } +// TestSanitizeJSONLines_BOMRecordEscapedBeginFailsClosed pins that a BOM on the +// first record does not hide a cross-record block. encoding/json rejects the mark, +// so the record was read as plain text, its \u-escaped BEGIN marker was never +// decoded, and the key body survived — bypassing the escaped-marker fix from +// bb35a97f6 (#5705). +func TestSanitizeJSONLines_BOMRecordEscapedBeginFailsClosed(t *testing.T) { + p := OutputPipeline() + bom := "\ufeff" + end := "-----END RSA" + " PRIVATE KEY-----" + content := []byte(bom + `{"a":"\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + `"}` + "\n" + + `{"b":"MIIEspanningkeymaterial0"}` + "\n" + + `{"c":"` + end + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "MIIEspanningkeymaterial0") + assert.NotContains(t, string(out), "END RSA") + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// TestSanitizeJSONLines_CleanBOMRecordPreserved pins that a BOM-prefixed record is +// routed through the structural path and keeps its encoding mark, exactly as a +// BOM-prefixed single document does. +func TestSanitizeJSONLines_CleanBOMRecordPreserved(t *testing.T) { + p := OutputPipeline() + bom := []byte("\ufeff") + content := append(append([]byte{}, bom...), []byte(`{"event":"clean"}`+"\n")...) + content = append(content, []byte("{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\"}\n")...) + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, bytes.HasPrefix(out, bom), "the BOM must survive: %q", out) + assert.Contains(t, string(out), `{"event":"clean"}`, "a clean BOM-prefixed record must be unchanged") + assert.NotContains(t, string(out), "ghp_FAKEtesttoken") +} + // TestSanitizeJSONDocument_CRLFNoStrayCarriageReturn pins that trailing CRLF // framing is reproduced exactly, without a duplicated carriage return, on the // unchanged and rewritten paths. diff --git a/internal/security/redactor.go b/internal/security/redactor.go index 4a651ca9ec..f1024693ba 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -345,15 +345,20 @@ func defaultStructuralPatterns() []secretPattern { // 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 captures a value out of a quoted field. The double-quoted - // branch and the first single-quoted branch consume escaped delimiters, so - // a JSON or YAML string with an embedded quote is matched whole. The second + // branch and the second single-quoted branch consume escaped delimiters, so + // a JSON or YAML string with an embedded quote is matched whole. The first // single-quoted branch covers a value that ends in a literal backslash, - // where that backslash must not escape the closing quote. The last branch - // keeps a raw newline inside a single-quoted value matchable, as it was - // before the escape handling was added: it cannot cross a quote, so it - // never swallows the field that follows. The minimum length is enforced in - // scan, not here. - {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\[\s\S]|[^"\\])*)"|'((?:''|\\\r?\n|\\.|[^'\r\n\\])*[^'\r\n\\])'|'((?:''|[^'\r\n])*\\)'|'([^']*)')`}, + // where that backslash must not escape the closing quote; it comes first + // because Go's regexp alternation is leftmost-first, so the escape-reading + // branch would otherwise match first and read the closing quote of + // 'api_key': 'secret\' in a YAML flow mapping as an escape, running on to + // the next quote on the same line and swallowing the field that follows. + // That branch therefore matches only when the quote after the backslash is + // followed by a field or line boundary. The last branch keeps a raw newline + // inside a single-quoted value matchable, as it was before the escape + // handling was added: it cannot cross a quote, so it never swallows the + // field that follows. The minimum length is enforced in scan, not here. + {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\[\s\S]|[^"\\])*)"|'((?:''|[^'\r\n])*\\)'[ \t]*(?:,|\}|\]|$)|'((?:''|\\\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 80a12164fe..39578f85ed 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -556,6 +556,19 @@ func TestSecretRedactor(t *testing.T) { assert.NotContains(t, result.Sanitized, "ijklmnop") }) + t.Run("json_field trailing backslash in a flow mapping keeps the next field", func(t *testing.T) { + // Go's regexp alternation is leftmost-first, so the escape-reading branch + // used to match first and read the closing quote as an escaped quote, + // running on to the next quote on the same line and swallowing the field + // that follows in a YAML flow mapping (#5705). + input := `{'api_key': 'abcdefghi\', 'x': 'yyyyyyyyyyyy'}` + result := r.Scan(input) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "abcdefghi") + assert.Contains(t, result.Sanitized, "'x': 'yyyyyyyyyyyy'", "the field that follows must survive intact") + }) + t.Run("json_field redacts a single-quoted value spanning a raw newline", func(t *testing.T) { // Base matched `'([^']{8,})'`, which crosses newlines. Handling escaped // delimiters must not narrow the pattern: a raw newline inside the From ed91e4f8fe36a5a61c8c724e6d4b967a9423edfb Mon Sep 17 00:00:00 2001 From: anevans Date: Mon, 23 Nov 2026 15:34:13 -0500 Subject: [PATCH 38/51] fix(#5705): fail closed on output files the scan cannot read The output scan failed closed on a file it could not write or sanitize but only warned about a file it could not read, so that file's bytes shipped without being scanned. A read failure now follows the write-failure path: the file is replaced with the fail-closed marker, or removed when even that write is refused, the walk still visits the remaining files, and the run fails closed with every failure joined. An entry the walk cannot open fails the run as well, because nothing under it was scanned. Both guides now say a file whose content cannot be read also fails the run, and the runtime guide states the current JSONL behavior: only the records that carry a cross-record secret or key material are replaced, a record between a quoted header and footer keeps its content, and a BOM-prefixed record is treated as JSON. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 37 +++++--- .../user/run-artifacts-and-private-data.md | 18 ++-- internal/cli/run.go | 45 ++++++++-- internal/cli/scan_output_telemetry_test.go | 89 +++++++++++++++++++ 4 files changed, 161 insertions(+), 28 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 982672022f..f3913f7000 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -678,11 +678,18 @@ finding id. A single isolated fragment below the floor, with no neighbour to joi it to, is still kept. `.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the record framing; a secret that spans records cannot be redacted without -rewriting that framing, so only the records it covers are replaced. A -private-key block spanning records is detected in a decoded view of the stream, -before per-record masking can remove its BEGIN marker, so a marker written with -\u escapes is still recognized. After the per-record pass the rebuilt stream is -rescanned, but only for whole-value secrets — registered runtime values and +rewriting that framing, so only the records that carry it are replaced, and a +record that merely sits between a quoted header and a quoted footer keeps its +content. A BOM-prefixed record is treated as JSON like any other, so a marker +written with \u escapes in it is still decoded. A private-key block spanning +records is detected in a decoded view of the stream, before per-record masking +can remove its BEGIN marker. The boundary records +always carry marker text, so they are always replaced; a record between them is +replaced only when its leaves hold a block marker or PEM body material, decided +the same way as in a single document — including the joined run of consecutive +base64-only values, which catches a body split into short or digit-free chunks. +After the per-record pass the rebuilt stream is rescanned, but only for +whole-value secrets — registered runtime values and private-key blocks, the same set the single-document path scans in its written form. Running the value patterns again would re-match a redaction placeholder followed by JSON escape bytes: in encoded JSON a `\n` escape is two non-space @@ -709,14 +716,18 @@ renders these as error annotations. Forgejo Actions also sets `GITHUB_ACTIONS=tr so its runner writes the same lines, but Forgejo has no annotation view: the runner prints them in the step log and the exit status stays 0. -A sanitized file that cannot be written, and a file that cannot be sanitized at -all, do not stop the walk: every remaining file is still scanned and redacted, -and the run fails closed afterwards with all failures joined. The file itself is -replaced with a fail-closed marker so the unredacted bytes do not reach the -uploaded artifact when the filesystem allows it; if the marker write and the -fallback removal both fail, that failure is added to the joined error rather -than left unreported, so the run says the unredacted file is still on disk. In -`quiet` mode the affected paths are counted, not named (ADR 0163). +A sanitized file that cannot be written, a file that cannot be read, and a file +that cannot be sanitized at all, do not stop the walk: every remaining file is +still scanned and redacted, and the run fails closed afterwards with all failures +joined. A file that cannot be read is contained exactly like one that cannot be +written, because its bytes were never scanned; an entry the walk cannot open fails +the run without being quarantined, since it may be a directory whose files were +never reached. The unredacted file is replaced with the fail-closed marker so its +bytes do not reach the uploaded artifact when the filesystem allows it; if the +marker write and the fallback removal both fail, that failure is added to the +joined error rather than left unreported, so the run says the unredacted file is +still on disk. In `quiet` mode the affected paths are counted, not named +(ADR 0163). ## Agent rule layering diff --git a/docs/guides/user/run-artifacts-and-private-data.md b/docs/guides/user/run-artifacts-and-private-data.md index 98f960c206..184e40e061 100644 --- a/docs/guides/user/run-artifacts-and-private-data.md +++ b/docs/guides/user/run-artifacts-and-private-data.md @@ -346,21 +346,21 @@ of a private Jira issue. On a public repository, any signed-in user can download the artifact until it expires. The output scan masks secret literals; it does not remove personal data, customer names or other private business text. A secret that cannot be localized replaces the whole JSON -document or JSONL record with a JSON error marker, and a file whose redacted -content cannot be written or computed is replaced by such a marker and fails -the run. If the marker cannot be written and the file cannot be removed either, -the run's error says the unredacted file is still on disk. A private-key block -that spans JSON members is handled in place -instead: the keys keep their names, and each string value that carries block -text or base64 key material becomes `[REDACTED PRIVATE KEY]`. When a +document, or the JSONL record that carries it, with a JSON error marker, and a +file whose redacted content cannot be read, written or computed is replaced by +such a marker and fails the run. If the marker cannot be written and the file +cannot be removed either, the run's error says the unredacted file is still on +disk. A private-key block that spans JSON members is handled in place instead: +the keys keep their names, and each string value that carries block text or +base64 key material becomes `[REDACTED PRIVATE KEY]`. When a replacement happens in a run that still exits 0, the job log says so. On GitHub Actions this is an error annotation: fullsend writes a `::error::` workflow command whenever the job sets `GITHUB_ACTIONS=true`, and GitHub Actions renders it. Forgejo Actions also sets `GITHUB_ACTIONS=true`, so the same `::error::` line is written there, but Forgejo has no annotation view: its runner prints the line in the step log and the exit status stays 0. On GitLab the line is not -written at all, so the run's log is the signal. A write or sanitize failure -needs no annotation because the run itself fails. +written at all, so the run's log is the signal. A read, write or sanitize +failure needs no annotation because the run itself fails. `fullsend run` leaves `output/` untouched. At the end of the job, `fullsend prepare-artifacts` builds a filtered copy at the level you set, and diff --git a/internal/cli/run.go b/internal/cli/run.go index 7354d84c0d..d3a0f34c00 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7099,7 +7099,11 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri err := filepath.WalkDir(outputDir, func(path string, d os.DirEntry, err error) error { if err != nil { - return nil // skip unreadable entries + // An entry the walk cannot open is output that cannot be scanned: + // everything under it would reach the artifact unredacted. The walk + // continues and the run fails closed once it finishes (#5705). + writeErrs = append(writeErrs, walkFailure(quiet, outputDir, path, err, &unreadable)) + return nil } if d.IsDir() { // Skip the security findings directory itself. @@ -7127,11 +7131,10 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri content, readErr := os.ReadFile(path) relPath, _ := filepath.Rel(outputDir, path) if readErr != nil { - if quiet { - unreadable++ - return nil - } - printer.StepWarn(fmt.Sprintf("Could not read %s: %v", relPath, readErr)) + // A file that cannot be read cannot be scanned, so its bytes would + // reach the artifact unredacted. It is contained like a write + // failure and the run fails closed (#5705). + writeErrs = append(writeErrs, readFailure(quiet, path, relPath, readErr, &unreadable)) return nil } ext := strings.ToLower(filepath.Ext(path)) @@ -7296,6 +7299,36 @@ func writeFailure(quiet bool, path, relPath string, writeErr error, unwritable * return errors.Join(fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr), quarantineErr) } +// readFailure records an output file that could not be read. Its bytes cannot be +// scanned, so it is contained like a write failure: the file is replaced with a +// marker, or removed, when the filesystem allows it, and the run fails closed +// afterwards (#5705). +func readFailure(quiet bool, path, relPath string, readErr error, unreadable *int) error { + *unreadable++ + quarantineErr := quarantineOutput(path) + if quiet { + return errors.Join(errors.New("could not read output file"), quarantineErr) + } + return errors.Join(fmt.Errorf("could not read %s: %w", relPath, readErr), quarantineErr) +} + +// walkFailure records an entry the walk could not open. Nothing under it was +// scanned, so the run fails closed instead of shipping those bytes as an +// artifact (#5705). The entry is not quarantined: it may be a directory, and the +// files it holds were never opened. +func walkFailure(quiet bool, outputDir, path string, walkErr error, unreadable *int) error { + *unreadable++ + if quiet { + // The path can carry an agent-chosen name (ADR 0163). + return errors.New("could not read an output entry") + } + relPath, err := filepath.Rel(outputDir, path) + if err != nil { + relPath = path + } + return fmt.Errorf("could not read %s: %w", relPath, walkErr) +} + // sanitizeFailure records a sanitization error and contains the file it could // not sanitize, so the walk continues to the remaining files instead of leaving // them unredacted. The unredacted bytes are replaced with the marker when the diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index e28aae2468..47558d004e 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -674,6 +674,95 @@ func TestScanOutputFiles_WriteFailureRemovesUnredactedBytes(t *testing.T) { assert.JSONEq(t, `{"error":"output removed because it could not be redacted"}`, string(got)) } +// TestScanOutputFiles_UnreadableFileFailsClosed pins that a file the scan cannot +// read does not reach the artifact unredacted. Its bytes were never scanned, so +// the file is contained with the fail-closed marker, the rest of the walk still +// runs, and the run fails closed (#5705). Before this, the file was only named in +// a warning and shipped. +func TestScanOutputFiles_UnreadableFileFailsClosed(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("permission checks do not apply to root") + } + dir := t.TempDir() + unreadable := filepath.Join(dir, "a-unreadable.txt") + const secret = "ghp_FAKEtesttoken000000000000000000000000" + require.NoError(t, os.WriteFile(unreadable, []byte("Token: "+secret), 0o644)) + require.NoError(t, os.Chmod(unreadable, 0o000)) + t.Cleanup(func() { _ = os.Chmod(unreadable, 0o644) }) + if file, err := os.Open(unreadable); err == nil { + _ = file.Close() + t.Skip("filesystem does not enforce unreadable file permissions") + } + later := filepath.Join(dir, "b-notes.txt") + require.NoError(t, os.WriteFile(later, []byte("Token: "+secret), 0o644)) + + err := scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{})) + require.Error(t, err) + assert.Contains(t, err.Error(), "could not read a-unreadable.txt") + + // The walk continued to the file after the unreadable one. + got, readErr := os.ReadFile(later) + require.NoError(t, readErr) + assert.NotContains(t, string(got), secret, "a later file must still be redacted") + + // The unreadable file is contained: its unredacted bytes are gone, either + // replaced by the marker or removed when it cannot be written. + contained, readErr := os.ReadFile(unreadable) + if readErr == nil { + assert.NotContains(t, string(contained), secret, "the unredacted bytes must not survive") + assert.JSONEq(t, `{"error":"output removed because it could not be redacted"}`, string(contained)) + } else { + assert.True(t, os.IsNotExist(readErr), "an unreadable file that cannot be replaced must be removed: %v", readErr) + } +} + +// TestScanOutputFiles_UnreadableDirectoryFailsClosed pins that a directory the +// walk cannot open fails the run: nothing under it was scanned, so its bytes +// would otherwise reach the artifact unredacted (#5705). +func TestScanOutputFiles_UnreadableDirectoryFailsClosed(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("permission checks do not apply to root") + } + dir := t.TempDir() + blocked := filepath.Join(dir, "agent-dir") + require.NoError(t, os.MkdirAll(blocked, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(blocked, "notes.txt"), []byte("Token: ghp_FAKEtesttoken000000000000000000000000"), 0o644)) + require.NoError(t, os.Chmod(blocked, 0o000)) + t.Cleanup(func() { _ = os.Chmod(blocked, 0o755) }) + if entries, err := os.ReadDir(blocked); err == nil { + _ = entries + t.Skip("filesystem does not enforce unreadable directory permissions") + } + + err := scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{})) + require.Error(t, err) + assert.Contains(t, err.Error(), "could not read agent-dir") +} + +// TestScanOutputFiles_QuietReadFailureKeepsPathOutOfMessage pins the quiet +// contract for a read failure: the run fails closed, and the file name — which +// can be agent-chosen — stays out of the message (ADR 0163). +func TestScanOutputFiles_QuietReadFailureKeepsPathOutOfMessage(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("permission checks do not apply to root") + } + dir := t.TempDir() + path := filepath.Join(dir, "agent-chosen-secret-name.txt") + require.NoError(t, os.WriteFile(path, []byte("Token: ghp_FAKEtesttoken000000000000000000000000"), 0o644)) + require.NoError(t, os.Chmod(path, 0o000)) + t.Cleanup(func() { _ = os.Chmod(path, 0o644) }) + if file, err := os.Open(path); err == nil { + _ = file.Close() + t.Skip("filesystem does not enforce unreadable file permissions") + } + + var output bytes.Buffer + err := scanOutputFiles(dir, "trace-id", "quiet", ui.New(&output)) + require.Error(t, err) + assert.NotContains(t, err.Error(), "agent-chosen-secret-name.txt") + assert.NotContains(t, output.String(), "agent-chosen-secret-name.txt") +} + // TestScanOutputFiles_SanitizesBOMPrefixedJSONStructurally pins that a JSON // document that starts with a UTF-8 BOM still takes the structural path. The BOM // is not JSON whitespace, so before this it fell through to the plain-text scan, From b9ea87297cb45ece812e351b9a4b231fb181ab7c Mon Sep 17 00:00:00 2001 From: anevans Date: Mon, 23 Nov 2026 16:48:39 -0500 Subject: [PATCH 39/51] fix(#5705): keep output-scan failure detail at quiet At the quiet progress level, writeFailure, readFailure, walkFailure and sanitizeFailure returned fixed text such as "could not write sanitized output file", dropping the file and the wrapped cause. Only printed lines are gated at quiet (the count warnings, failureLine and quietRunError), so the run error recorded by telemetry and the root span lost the detail too. That contradicts ADR 0163, which keeps telemetry and the run artifact complete and changes only the printed log. The four helpers now always return the file-relative path and the wrapped error, and no longer take the quiet flag. failureLine and quietRunError keep the printed line trimmed as before. The runtime guide says the counted-only behavior applies to the printed log, not the run error. Tests: the quiet write-failure test now pins the path and errors.Is on the original write error; the quiet read-failure test pins that the agent-chosen name stays out of the printed log while staying in the error. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 5 +- internal/cli/run.go | 56 +++++++++------------ internal/cli/scan_output_telemetry_test.go | 28 +++++++---- 3 files changed, 47 insertions(+), 42 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index f3913f7000..ca15d237ab 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -726,8 +726,9 @@ never reached. The unredacted file is replaced with the fail-closed marker so it bytes do not reach the uploaded artifact when the filesystem allows it; if the marker write and the fallback removal both fail, that failure is added to the joined error rather than left unreported, so the run says the unredacted file is -still on disk. In `quiet` mode the affected paths are counted, not named -(ADR 0163). +still on disk. In `quiet` mode the printed log counts the affected paths +instead of naming them (ADR 0163); the run error and telemetry keep the path +and the wrapped cause at every level, and only the printed line is trimmed. ## Agent rule layering diff --git a/internal/cli/run.go b/internal/cli/run.go index d3a0f34c00..e216939d0d 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7089,7 +7089,9 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri pipeline := security.OutputPipeline() findingCount := 0 - // At quiet, unreadable and unwritable files are counted, not named. + // At quiet, unreadable, unwritable and unsanitizable files are counted, not + // named, in the printed log. The collected failures still name each file and + // wrap its cause, so telemetry keeps the full text (ADR 0163). unreadable, unwritable, unsanitizable := 0, 0, 0 // Write and sanitizer failures are collected rather than returned from the // walk callback so every remaining file is still scanned and redacted. The @@ -7102,7 +7104,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri // An entry the walk cannot open is output that cannot be scanned: // everything under it would reach the artifact unredacted. The walk // continues and the run fails closed once it finishes (#5705). - writeErrs = append(writeErrs, walkFailure(quiet, outputDir, path, err, &unreadable)) + writeErrs = append(writeErrs, walkFailure(outputDir, path, err, &unreadable)) return nil } if d.IsDir() { @@ -7134,7 +7136,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri // A file that cannot be read cannot be scanned, so its bytes would // reach the artifact unredacted. It is contained like a write // failure and the run fails closed (#5705). - writeErrs = append(writeErrs, readFailure(quiet, path, relPath, readErr, &unreadable)) + writeErrs = append(writeErrs, readFailure(path, relPath, readErr, &unreadable)) return nil } ext := strings.ToLower(filepath.Ext(path)) @@ -7144,7 +7146,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri if ext == ".jsonl" || ext == ".ndjson" { out, jsonLineFindings, scanErr := sanitizeJSONLines(content, pipeline) if scanErr != nil { - writeErrs = append(writeErrs, sanitizeFailure(quiet, path, relPath, scanErr, &unsanitizable)) + writeErrs = append(writeErrs, sanitizeFailure(path, relPath, scanErr, &unsanitizable)) return nil } // A record that was replaced with a marker is not a whole-file @@ -7166,7 +7168,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri }) } if writeErr := writeFile(path, out, 0o644); writeErr != nil { - writeErrs = append(writeErrs, writeFailure(quiet, path, relPath, writeErr, &unwritable)) + writeErrs = append(writeErrs, writeFailure(path, relPath, writeErr, &unwritable)) } } return nil @@ -7180,7 +7182,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri if security.IsJSONDocument(content) { out, jsonFindings, jsonErr := sanitizeJSONDocument(content, pipeline) if jsonErr != nil { - writeErrs = append(writeErrs, sanitizeFailure(quiet, path, relPath, jsonErr, &unsanitizable)) + writeErrs = append(writeErrs, sanitizeFailure(path, relPath, jsonErr, &unsanitizable)) return nil } if len(jsonFindings) > 0 { @@ -7196,7 +7198,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri } alertOnOutputRemoval(printer, out) if writeErr := writeFile(path, out, 0o644); writeErr != nil { - writeErrs = append(writeErrs, writeFailure(quiet, path, relPath, writeErr, &unwritable)) + writeErrs = append(writeErrs, writeFailure(path, relPath, writeErr, &unwritable)) } } return nil @@ -7226,7 +7228,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri // report. out := result.Sanitized if writeErr := writeFile(path, []byte(out), 0o644); writeErr != nil { - writeErrs = append(writeErrs, writeFailure(quiet, path, relPath, writeErr, &unwritable)) + writeErrs = append(writeErrs, writeFailure(path, relPath, writeErr, &unwritable)) } } return nil @@ -7287,41 +7289,35 @@ func alertOnRecordRemoval(printer *ui.Printer, sanitized []byte) { } } -// writeFailure records a sanitized-output write error. At the quiet progress -// level the path is withheld because it can carry an agent-chosen name -// (ADR 0163); non-quiet callers name it. -func writeFailure(quiet bool, path, relPath string, writeErr error, unwritable *int) error { +// writeFailure records a sanitized-output write error. The returned error always +// names the file and wraps the cause, whatever the progress level: only printed +// lines are trimmed at quiet (the count warnings below, failureLine and +// quietRunError), while the run error recorded by telemetry keeps the full text +// (ADR 0163). +func writeFailure(path, relPath string, writeErr error, unwritable *int) error { *unwritable++ quarantineErr := quarantineOutput(path) - if quiet { - return errors.Join(errors.New("could not write sanitized output file"), quarantineErr) - } return errors.Join(fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr), quarantineErr) } // readFailure records an output file that could not be read. Its bytes cannot be // scanned, so it is contained like a write failure: the file is replaced with a // marker, or removed, when the filesystem allows it, and the run fails closed -// afterwards (#5705). -func readFailure(quiet bool, path, relPath string, readErr error, unreadable *int) error { +// afterwards (#5705). Like every failure here, the error names the file at every +// progress level; only the printed line is trimmed at quiet (ADR 0163). +func readFailure(path, relPath string, readErr error, unreadable *int) error { *unreadable++ quarantineErr := quarantineOutput(path) - if quiet { - return errors.Join(errors.New("could not read output file"), quarantineErr) - } return errors.Join(fmt.Errorf("could not read %s: %w", relPath, readErr), quarantineErr) } // walkFailure records an entry the walk could not open. Nothing under it was // scanned, so the run fails closed instead of shipping those bytes as an // artifact (#5705). The entry is not quarantined: it may be a directory, and the -// files it holds were never opened. -func walkFailure(quiet bool, outputDir, path string, walkErr error, unreadable *int) error { +// files it holds were never opened. The path stays in the error at every +// progress level; only the printed line is trimmed at quiet (ADR 0163). +func walkFailure(outputDir, path string, walkErr error, unreadable *int) error { *unreadable++ - if quiet { - // The path can carry an agent-chosen name (ADR 0163). - return errors.New("could not read an output entry") - } relPath, err := filepath.Rel(outputDir, path) if err != nil { relPath = path @@ -7332,13 +7328,11 @@ func walkFailure(quiet bool, outputDir, path string, walkErr error, unreadable * // sanitizeFailure records a sanitization error and contains the file it could // not sanitize, so the walk continues to the remaining files instead of leaving // them unredacted. The unredacted bytes are replaced with the marker when the -// filesystem allows it, as on a write failure (#5705). -func sanitizeFailure(quiet bool, path, relPath string, scanErr error, unsanitizable *int) error { +// filesystem allows it, as on a write failure (#5705). The error names the file +// and wraps the cause at every progress level (ADR 0163). +func sanitizeFailure(path, relPath string, scanErr error, unsanitizable *int) error { *unsanitizable++ quarantineErr := quarantineOutput(path) - if quiet { - return errors.Join(errors.New("could not sanitize output file"), quarantineErr) - } return errors.Join(fmt.Errorf("could not sanitize %s: %w", relPath, scanErr), quarantineErr) } diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 47558d004e..6c104f72da 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -549,15 +549,22 @@ func TestScanOutputFiles_NoAnnotationForPreexistingMarkerLine(t *testing.T) { assert.Equal(t, content, string(got), "a clean stream must be written back unchanged") } -func TestScanOutputFiles_QuietJSONWriteFailureIsFatal(t *testing.T) { +// TestScanOutputFiles_QuietWriteFailureKeepsPathAndCause pins that a quiet run +// still reports what failed in the error it returns: the file and the wrapped +// write error reach telemetry and the root span, and only the printed line is +// trimmed (failureLine, quietRunError) under ADR 0163. +func TestScanOutputFiles_QuietWriteFailureKeepsPathAndCause(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "secret.json") require.NoError(t, os.WriteFile(path, []byte(`{"token":"ghp_FAKEtesttoken000000000000000000000000"}`), 0o644)) + writeErr := errors.New("no space left on device") err := scanOutputFilesWithWriter(dir, "trace-id", "quiet", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { - return os.ErrPermission + return writeErr }) require.Error(t, err) - assert.EqualError(t, err, "could not write sanitized output file") + assert.Contains(t, err.Error(), "could not write sanitized secret.json", + "the run error keeps the path at quiet, so telemetry can name it") + assert.ErrorIs(t, err, writeErr, "the run error keeps the wrapped cause at quiet") } // TestScanOutputFiles_ContinuesRedactingAfterWriteFailure pins that one @@ -739,10 +746,11 @@ func TestScanOutputFiles_UnreadableDirectoryFailsClosed(t *testing.T) { assert.Contains(t, err.Error(), "could not read agent-dir") } -// TestScanOutputFiles_QuietReadFailureKeepsPathOutOfMessage pins the quiet -// contract for a read failure: the run fails closed, and the file name — which -// can be agent-chosen — stays out of the message (ADR 0163). -func TestScanOutputFiles_QuietReadFailureKeepsPathOutOfMessage(t *testing.T) { +// TestScanOutputFiles_QuietReadFailureKeepsPathInErrorOnly pins the quiet +// contract for a read failure: the file name — which can be agent-chosen +// (ADR 0163) — stays out of the printed log but stays in the run error, so +// telemetry records which file could not be scanned. +func TestScanOutputFiles_QuietReadFailureKeepsPathInErrorOnly(t *testing.T) { if os.Geteuid() == 0 { t.Skip("permission checks do not apply to root") } @@ -759,8 +767,10 @@ func TestScanOutputFiles_QuietReadFailureKeepsPathOutOfMessage(t *testing.T) { var output bytes.Buffer err := scanOutputFiles(dir, "trace-id", "quiet", ui.New(&output)) require.Error(t, err) - assert.NotContains(t, err.Error(), "agent-chosen-secret-name.txt") - assert.NotContains(t, output.String(), "agent-chosen-secret-name.txt") + assert.Contains(t, err.Error(), "agent-chosen-secret-name.txt", + "the run error keeps the path at quiet, so telemetry can name it") + assert.NotContains(t, output.String(), "agent-chosen-secret-name.txt", + "the printed log must not name an agent-chosen file at quiet") } // TestScanOutputFiles_SanitizesBOMPrefixedJSONStructurally pins that a JSON From 667e9650f1bdc0039907f6f969b85e41621bcc51 Mon Sep 17 00:00:00 2001 From: anevans Date: Tue, 24 Nov 2026 10:30:00 -0500 Subject: [PATCH 40/51] fix(#5705): post a scan count, not output names, in the status comment b9ea872 made writeFailure, readFailure, walkFailure and sanitizeFailure name the file and wrap the cause at every progress level, so telemetry and the root span keep the detail that ADR 0163 requires. The run error also reaches the completion comment statusFinalizer posts on the issue or pull request, where Actions log masking does not apply: at quiet, an output file name the agent chose was posted there, where before b9ea872 the helpers returned fixed text. redactFeedback masks runner env secrets only, and statuscomment.sanitizeDetail collapses control characters and caps the length, so nothing else stood between that name and the comment. scanOutputFilesWithWriter now returns an outputScanError that carries the per-file causes and the number of files it could not handle. statusFinalizer asks failureStatusDetail for the comment's failure detail: at quiet an error implementing quietStatusDetailer supplies fixed wording, so a failed scan posts "post-agent output scan failed: N file(s) could not be scanned". The run error keeps every path and wrapped cause at every level, and other errors post their message as before: ADR 0163 covers the job log only, and applying the level to the whole comment is #9627. Tests: TestFailureStatusDetail pins the full/quiet split and that an error without fixed wording is unchanged at quiet; TestScanOutputFiles_QuietScanFailureStatusDetailOmitsAgentName pins that a quiet write failure on an agent-named file keeps the name and cause in the run error and leaves them out of the comment detail; TestCollectPostScanSecurityArtifactsKeepsQuietStatusDetail pins that the wrap collectPostScanSecurityArtifacts adds keeps that wording reachable. The runtime guide and config reference say what the comment posts now. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 8 ++- docs/reference/config-reference.md | 4 +- internal/cli/run.go | 78 ++++++++++++++++++--- internal/cli/run_postscan_test.go | 24 +++++++ internal/cli/run_progress_test.go | 24 +++++++ internal/cli/scan_output_telemetry_test.go | 28 ++++++++ 6 files changed, 155 insertions(+), 11 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index ca15d237ab..e55cb70998 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -728,7 +728,13 @@ marker write and the fallback removal both fail, that failure is added to the joined error rather than left unreported, so the run says the unredacted file is still on disk. In `quiet` mode the printed log counts the affected paths instead of naming them (ADR 0163); the run error and telemetry keep the path -and the wrapped cause at every level, and only the printed line is trimmed. +and the wrapped cause at every level, and only the printed line is trimmed. The +completion comment on the issue or pull request counts them too: an output file +name is the agent's to choose, and Actions log masking does not apply to a +comment, so at `quiet` a failed scan posts how many files it could not handle +instead of naming one. The scan failure is the only run error the comment +rewrites today; applying the level to the rest is tracked in +[#9627](https://github.com/fullsend-ai/fullsend/issues/9627). ## Agent rule layering diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index c69e96b7b8..97e9ef678e 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -1410,7 +1410,9 @@ At `quiet`: A setup error before that, such as a config or provider error, prints in full. The level covers the job log only: the status comment on the issue or pull request still carries the full run error - ([#9627](https://github.com/fullsend-ai/fullsend/issues/9627)). + ([#9627](https://github.com/fullsend-ai/fullsend/issues/9627)), except that a + failed output scan posts how many files it could not handle rather than a + name the agent chose. **Agent CLI stderr at `quiet`.** The agent CLI (Claude Code, pi, Codex or OpenCode) writes its own diagnostics to stderr, and they can quote what the diff --git a/internal/cli/run.go b/internal/cli/run.go index e216939d0d..08e15b8b02 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -1633,7 +1633,11 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep status = "cancelled" } else if runErr != nil { status = "failure" - detail = runErr.Error() + // Actions log masking does not apply to this comment, so an + // error that can quote text the agent chose supplies fixed + // wording at quiet (failureStatusDetail). Telemetry and the + // root span keep the full error. + detail = failureStatusDetail(runErr, progressVerbosity) } else if runSkipped { status = "skipped" detail = runSkipReason @@ -5169,6 +5173,30 @@ func auditChainFailure(brokenMsg, progressVerbosity string) (string, error) { // the quiet progress level. const quietRunErrorMessage = "agent run failed (error details are not printed at progress level quiet; see telemetry or the run artifact)" +// quietStatusDetailer lets an error state the fixed text the completion comment +// may carry for it at the quiet progress level, such as a count of affected +// files in place of their agent-chosen names. +type quietStatusDetailer interface { + QuietStatusDetail() string +} + +// failureStatusDetail returns the failure detail the completion comment posts +// for err. Actions log masking does not apply to that comment, so at quiet an +// error whose text can carry something the agent chose supplies a fixed wording +// through quietStatusDetailer. Every other error posts its message as before: +// ADR 0163 covers the job log only, and applying the level to the whole comment +// is tracked in #9627. The run error keeps the full text for telemetry and the +// root span at every level. +func failureStatusDetail(err error, progressVerbosity string) string { + if config.ProgressIsQuiet(progressVerbosity) { + var detailer quietStatusDetailer + if errors.As(err, &detailer) { + return detailer.QuietStatusDetail() + } + } + return err.Error() +} + // quietRunErr is the run's final error at quiet: it prints as // quietRunErrorMessage and keeps the original for errors.Is, errors.As and // the exit code. @@ -7091,7 +7119,8 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri findingCount := 0 // At quiet, unreadable, unwritable and unsanitizable files are counted, not // named, in the printed log. The collected failures still name each file and - // wrap its cause, so telemetry keeps the full text (ADR 0163). + // wrap its cause, so telemetry keeps the full text, and the returned error's + // QuietStatusDetail gives the completion comment the count (ADR 0163). unreadable, unwritable, unsanitizable := 0, 0, 0 // Write and sanitizer failures are collected rather than returned from the // walk callback so every remaining file is still scanned and redacted. The @@ -7252,11 +7281,35 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri printer.StepDone("Output files clean — no issues found") } if err := errors.Join(writeErrs...); err != nil { - return err + return &outputScanError{err: err, files: unreadable + unwritable + unsanitizable} } return nil } +// postAgentScanFailurePrefix labels a failed post-agent output scan in the run +// error and in the fixed text the completion comment carries at quiet. +const postAgentScanFailurePrefix = "post-agent output scan failed" + +// outputScanError is the run error for a post-agent output scan that could not +// handle some output files. Its message names each file and wraps the cause, so +// telemetry and the root span keep the detail (ADR 0163). At the quiet progress +// level the completion comment gets QuietStatusDetail instead: an output file +// name is the agent's to choose, and the comment is posted where anyone who can +// see the issue or pull request reads it (#5705). +type outputScanError struct { + err error + files int +} + +func (e *outputScanError) Error() string { return e.err.Error() } +func (e *outputScanError) Unwrap() error { return e.err } + +// QuietStatusDetail is the fixed text the completion comment carries at quiet: +// how many output files the scan could not handle, never a name or a cause. +func (e *outputScanError) QuietStatusDetail() string { + return fmt.Sprintf("%s: %d file(s) could not be scanned", postAgentScanFailurePrefix, e.files) +} + // alertOnOutputRemoval emits a ::error:: workflow command when an output file // was replaced whole by a fail-closed marker. Everything the agent wrote into // that file is gone, and a lost review that only shows up as one scan line is @@ -7292,8 +7345,9 @@ func alertOnRecordRemoval(printer *ui.Printer, sanitized []byte) { // writeFailure records a sanitized-output write error. The returned error always // names the file and wraps the cause, whatever the progress level: only printed // lines are trimmed at quiet (the count warnings below, failureLine and -// quietRunError), while the run error recorded by telemetry keeps the full text -// (ADR 0163). +// quietRunError), while the run error recorded by telemetry keeps the full text. +// The completion comment posts a count instead of the agent-chosen name at quiet +// (failureStatusDetail, ADR 0163). func writeFailure(path, relPath string, writeErr error, unwritable *int) error { *unwritable++ quarantineErr := quarantineOutput(path) @@ -7304,7 +7358,8 @@ func writeFailure(path, relPath string, writeErr error, unwritable *int) error { // scanned, so it is contained like a write failure: the file is replaced with a // marker, or removed, when the filesystem allows it, and the run fails closed // afterwards (#5705). Like every failure here, the error names the file at every -// progress level; only the printed line is trimmed at quiet (ADR 0163). +// progress level; only the printed line is trimmed at quiet, and the completion +// comment gets a count (failureStatusDetail, ADR 0163). func readFailure(path, relPath string, readErr error, unreadable *int) error { *unreadable++ quarantineErr := quarantineOutput(path) @@ -7315,7 +7370,8 @@ func readFailure(path, relPath string, readErr error, unreadable *int) error { // scanned, so the run fails closed instead of shipping those bytes as an // artifact (#5705). The entry is not quarantined: it may be a directory, and the // files it holds were never opened. The path stays in the error at every -// progress level; only the printed line is trimmed at quiet (ADR 0163). +// progress level; only the printed line is trimmed at quiet, and the completion +// comment gets a count (failureStatusDetail, ADR 0163). func walkFailure(outputDir, path string, walkErr error, unreadable *int) error { *unreadable++ relPath, err := filepath.Rel(outputDir, path) @@ -7329,7 +7385,8 @@ func walkFailure(outputDir, path string, walkErr error, unreadable *int) error { // not sanitize, so the walk continues to the remaining files instead of leaving // them unredacted. The unredacted bytes are replaced with the marker when the // filesystem allows it, as on a write failure (#5705). The error names the file -// and wraps the cause at every progress level (ADR 0163). +// and wraps the cause at every progress level; the completion comment gets a +// count at quiet (failureStatusDetail, ADR 0163). func sanitizeFailure(path, relPath string, scanErr error, unsanitizable *int) error { *unsanitizable++ quarantineErr := quarantineOutput(path) @@ -7392,7 +7449,10 @@ func collectPostScanSecurityArtifacts(runDir, sandboxName string, printer *ui.Pr } } if scanErr != nil { - scanErr = fmt.Errorf("post-agent output scan failed: %w", scanErr) + // The wrap keeps a scan error's own fixed quiet wording reachable + // through errors.As, so the completion comment can post a count instead + // of the agent-chosen file names (outputScanError, ADR 0163). + scanErr = fmt.Errorf("%s: %w", postAgentScanFailurePrefix, scanErr) } return errors.Join(scanErr, chainErr) } diff --git a/internal/cli/run_postscan_test.go b/internal/cli/run_postscan_test.go index 453026d259..87fa5c3e95 100644 --- a/internal/cli/run_postscan_test.go +++ b/internal/cli/run_postscan_test.go @@ -3,11 +3,13 @@ package cli import ( "bytes" "errors" + "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/ui" ) @@ -33,3 +35,25 @@ func TestCollectPostScanSecurityArtifactsRunsOnScanFailure(t *testing.T) { assert.Contains(t, err.Error(), "post-agent output scan failed") assert.Contains(t, buf.String(), "Security findings extracted") } + +// TestCollectPostScanSecurityArtifactsKeepsQuietStatusDetail pins that the wrap +// collectPostScanSecurityArtifacts adds around the scan error keeps the scan's +// fixed quiet wording reachable, so the completion comment can post a count of +// files instead of the agent-chosen names (ADR 0163). +func TestCollectPostScanSecurityArtifactsKeepsQuietStatusDetail(t *testing.T) { + runDir := t.TempDir() + original := downloadSandboxFindings + downloadSandboxFindings = func(_, _, _ string) error { return errors.New("no findings") } + t.Cleanup(func() { downloadSandboxFindings = original }) + + const name = "@org/team-secret.json" + scanErr := &outputScanError{err: fmt.Errorf("could not read %s: denied", name), files: 1} + var buf bytes.Buffer + err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), config.ProgressVerbosityQuiet, scanErr) + + require.Error(t, err) + assert.Contains(t, err.Error(), name, "the run error keeps the path for telemetry") + assert.Equal(t, "post-agent output scan failed: 1 file(s) could not be scanned", + failureStatusDetail(err, config.ProgressVerbosityQuiet)) + assert.Contains(t, failureStatusDetail(err, ""), name, "full posts the error as before") +} diff --git a/internal/cli/run_progress_test.go b/internal/cli/run_progress_test.go index d3c436e8a5..e0d466e18a 100644 --- a/internal/cli/run_progress_test.go +++ b/internal/cli/run_progress_test.go @@ -286,6 +286,30 @@ func TestFailureLine(t *testing.T) { } } +// At quiet the completion comment must not carry text the agent can write, such +// as an output file name, so an error that quotes one supplies a fixed wording. +// Every other error posts its message as before (ADR 0163 covers the job log +// only; applying it to the whole comment is #9627), and the run error keeps the +// full text either way. +func TestFailureStatusDetail(t *testing.T) { + const agentName = "SECRET-NAME.json" + scanErr := &outputScanError{err: fmt.Errorf("could not read %s: denied", agentName), files: 2} + for _, level := range []string{"", config.ProgressVerbosityFull, config.ProgressVerbosityTools} { + assert.Equal(t, "could not read SECRET-NAME.json: denied", failureStatusDetail(scanErr, level), + "level %q posts the error as before", level) + } + for _, level := range []string{config.ProgressVerbosityQuiet, "bogus"} { + assert.Equal(t, "post-agent output scan failed: 2 file(s) could not be scanned", + failureStatusDetail(scanErr, level)) + } + + plain := fmt.Errorf("could not copy %s", agentName) + for _, level := range []string{"", config.ProgressVerbosityFull, config.ProgressVerbosityTools, config.ProgressVerbosityQuiet} { + assert.Equal(t, "could not copy SECRET-NAME.json", failureStatusDetail(plain, level), + "an error with no fixed wording posts its message as before") + } +} + func TestAuditChainFailure(t *testing.T) { const broken = "entry 2: hash mismatch: expected abc, got SECRET-HASH" for _, level := range []string{"", config.ProgressVerbosityFull, config.ProgressVerbosityTools} { diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 6c104f72da..8635594ede 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -773,6 +773,34 @@ func TestScanOutputFiles_QuietReadFailureKeepsPathInErrorOnly(t *testing.T) { "the printed log must not name an agent-chosen file at quiet") } +// TestScanOutputFiles_QuietScanFailureStatusDetailOmitsAgentName pins the +// completion-comment channel at quiet: the run error keeps the agent-chosen +// output file name for telemetry, while the detail the comment posts carries +// the count alone. Actions log masking does not apply to a comment, and the +// name is the agent's to choose (#5705, ADR 0163). +func TestScanOutputFiles_QuietScanFailureStatusDetailOmitsAgentName(t *testing.T) { + dir := t.TempDir() + const name = "@org/team-secret.json" + path := filepath.Join(dir, name) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(`{"token":"ghp_FAKEtesttoken000000000000000000000000"}`), 0o644)) + writeErr := errors.New("no space left on device") + + err := scanOutputFilesWithWriter(dir, "trace-id", "quiet", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { + return writeErr + }) + require.Error(t, err) + assert.Contains(t, err.Error(), name, "the run error keeps the path for telemetry") + assert.ErrorIs(t, err, writeErr, "the run error keeps the wrapped cause for telemetry") + + detail := failureStatusDetail(err, "quiet") + assert.NotContains(t, detail, name, "the completion comment must not post an agent-chosen name") + assert.NotContains(t, detail, "no space left on device") + assert.Equal(t, "post-agent output scan failed: 1 file(s) could not be scanned", detail) + + assert.Contains(t, failureStatusDetail(err, ""), name, "full posts the error as before") +} + // TestScanOutputFiles_SanitizesBOMPrefixedJSONStructurally pins that a JSON // document that starts with a UTF-8 BOM still takes the structural path. The BOM // is not JSON whitespace, so before this it fell through to the plain-text scan, From 1b4b82f800b95a2de969f45e2b547b3d5f289990 Mon Sep 17 00:00:00 2001 From: anevans Date: Tue, 24 Nov 2026 15:27:48 -0500 Subject: [PATCH 41/51] fix(#5705): run the post-script when a failed scan left the agent's result MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A scan failure now fails the run, and it reached postScriptGate as a plain run error, so the gate printed "Skipping post-script: agent run failed" and the deferred post-script never ran. One unreadable, unwritable or unsanitizable file anywhere under the run directory therefore suppressed a completed report — an intact agent-result.json such as an approve review was never posted. That is the silent loss #5705 set out to fix, caused by I/O rather than by a secret. postScriptGate now treats an *outputScanError like an agentFailedError: when the result file the harness names survived the scan and still holds a JSON object, the post-script runs, the result is posted, and the run still fails because the scan error stays the run error. The check reaches the scan error through the wrap and the join collectPostScanSecurityArtifacts applies. agentResultFile now refuses a file the scan replaced with a fail-closed marker. Both the security markers and the quarantine marker are valid JSON objects, so without this the gate would have posted a removal marker as the agent's review — in this new path and in the #8305 path that already ran the post-script after a failed agent. Tests: TestPostScriptGate gains a scan failure with an intact result (through the wrap and an audit-chain join), with no result, with the result replaced by each marker, and with a validation loop. A marker is never posted as a result. The runtime guide documents the interaction next to the fail-closed contract. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 10 +++++ internal/cli/run.go | 30 ++++++++++++- internal/cli/run_test.go | 48 +++++++++++++++++++++ 3 files changed, 86 insertions(+), 2 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index e55cb70998..4ab72151c7 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -736,6 +736,16 @@ instead of naming one. The scan failure is the only run error the comment rewrites today; applying the level to the rest is tracked in [#9627](https://github.com/fullsend-ai/fullsend/issues/9627). +A failed scan fails the run but does not silence the agent's own result. The +post-script runs after the scan, so when the run failed with a scan error the +gate skips it — unless the result file the harness names (`agent-result.json` +by default) survived the scan and still holds a JSON object. Then the +post-script runs, posts the result, and the run still fails, so one unreadable +or unwritable file somewhere else under the run directory cannot turn a +completed report into silence. A result file the scan replaced with a +fail-closed marker does not count: the marker is valid JSON, but it is not the +agent's result, and posting it would report a removal as the review. + ## Agent rule layering When `fullsend run` executes an agent, Claude Code loads instructions from diff --git a/internal/cli/run.go b/internal/cli/run.go index 08e15b8b02..9339d192c1 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -4344,8 +4344,9 @@ type postScriptDecision struct { // postScriptGate decides whether the post-script runs once the agent is done. // With a validation_loop it needs a validated result (ADR 0022). Without one -// it runs after a successful agent, and after a failed agent only when the -// agent left a result file that parses (#8305), so the result is still +// it runs after a successful agent, after a failed agent only when the agent +// left a result file that parses (#8305), and after a failed output scan only +// when that scan left a result file that parses, so the result is still // reported while the run fails. --no-post-script is checked by the caller. func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverride bool, runErr error, outputDir string) postScriptDecision { if h.ValidationLoop != nil && !validationPassed { @@ -4363,6 +4364,22 @@ func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverrid agentExitCode: agentErr.exitCode, } } + // A scan failure fails the run, but one unreadable, unwritable or + // unsanitizable file anywhere under the run directory must not turn a + // completed report into silence: when the agent's own result file survived + // the scan and still parses, the post-script runs and the run still fails + // (#5705). + var scanErr *outputScanError + if errors.As(runErr, &scanErr) { + resultFile, ok := agentResultFile(h, outputDir) + if !ok { + return postScriptDecision{message: "Skipping post-script: the output scan failed and left no result file that parses"} + } + return postScriptDecision{ + run: true, + message: fmt.Sprintf("The output scan failed but left %s: running the post-script; the run still fails", filepath.Base(resultFile)), + } + } if runErr != nil { return postScriptDecision{message: "Skipping post-script: agent run failed"} } @@ -4401,6 +4418,15 @@ func agentResultFile(h *harness.Harness, outputDir string) (string, bool) { if json.Unmarshal(data, &obj) != nil || obj == nil { return "", false } + // A file the output scan replaced with a fail-closed marker is valid JSON + // but not the agent's result: posting it would report a marker as the + // review (#5705). + if _, removed := security.OutputRemoval(data); removed { + return "", false + } + if bytes.Equal(bytes.TrimSpace(data), []byte(unwritableOutputMarker)) { + return "", false + } return path, true } diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index 1cdd3ca4e9..c2c60e7bab 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -5,6 +5,7 @@ import ( "context" "debug/elf" "encoding/json" + "errors" "fmt" "io" "net" @@ -5402,6 +5403,53 @@ func TestPostScriptGate(t *testing.T) { got := postScriptGate(noLoop, false, false, timedOut, writeResult(t, "agent-result.json", `{}`)) assert.False(t, got.run) }) + t.Run("no loop, output scan failed, valid result", func(t *testing.T) { + t.Parallel() + // collectPostScanSecurityArtifacts wraps the scan error, so the gate + // must find it through the wrap and the join with an audit-chain error. + scanErr := fmt.Errorf("%s: %w", postAgentScanFailurePrefix, + &outputScanError{err: errors.New("could not write sanitized notes.md: no space left on device"), files: 1}) + runErr := errors.Join(scanErr, errors.New("audit log integrity check failed: hash mismatch")) + got := postScriptGate(noLoop, false, false, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.True(t, got.run, "an intact result must still be posted when the scan fails") + assert.Zero(t, got.agentExitCode) + assert.Contains(t, got.message, "agent-result.json") + assert.Contains(t, got.message, "the run still fails") + }) + t.Run("no loop, output scan failed, no result", func(t *testing.T) { + t.Parallel() + got := postScriptGate(noLoop, false, false, &outputScanError{err: errors.New("could not read notes.md"), files: 1}, t.TempDir()) + assert.False(t, got.run) + assert.Contains(t, got.message, "left no result file that parses") + }) + t.Run("no loop, output scan quarantined the result", func(t *testing.T) { + t.Parallel() + // The quarantine marker is valid JSON, so it would otherwise pass for a + // result and be posted as the review. + for _, marker := range []string{ + unwritableOutputMarker, + `{"error":"output removed because redaction would invalidate JSON"}`, + `{"error":"output removed because a private key block spans JSON framing"}`, + } { + dir := writeResult(t, "agent-result.json", marker) + got := postScriptGate(noLoop, false, false, &outputScanError{err: errors.New("could not sanitize agent-result.json"), files: 1}, dir) + assert.False(t, got.run, marker) + assert.Contains(t, got.message, "left no result file that parses", marker) + } + }) + t.Run("no loop, failed agent, quarantined result", func(t *testing.T) { + t.Parallel() + dir := writeResult(t, "agent-result.json", unwritableOutputMarker) + assert.False(t, postScriptGate(noLoop, false, false, agentFailed, dir).run, + "a marker must never be posted as the agent's result") + }) + t.Run("loop, output scan failed with a result present", func(t *testing.T) { + t.Parallel() + got := postScriptGate(withLoop, false, false, &outputScanError{err: errors.New("could not read notes.md"), files: 1}, + writeResult(t, "agent-result.json", `{}`)) + assert.False(t, got.run, "ADR 0022 still requires a validated result") + assert.Equal(t, "Skipping post-script: validation did not pass", got.message) + }) t.Run("loop, validation passed", func(t *testing.T) { t.Parallel() assert.True(t, postScriptGate(withLoop, true, false, nil, t.TempDir()).run) From 8b976fb73f341f1d3fb7f73ebf12c9331e96b521 Mon Sep 17 00:00:00 2001 From: anevans Date: Tue, 24 Nov 2026 15:28:35 -0500 Subject: [PATCH 42/51] fix(#5705): mask a captured value even when it looks like an existing mask SecretRedactor.Scan skipped any capture that looked like a Mask placeholder: exactly seven bytes ending in "..." (after trailing backslashes) or "***". The shape of a placeholder is also the shape of a real secret. db_connection_password accepts a value of four characters or more, so "postgres://u:abcd...@host" captured "abcd..." and the scan left the real seven-character password in the output. The skip is gone, so a capture is always masked; Mask returns "***" for a value shorter than ten bytes, so a placeholder that a full Scan sees again is masked to "***" rather than left as itself. Callers that rescan bytes an earlier pass redacted use ScanWholeValueSecrets, which runs no value pattern, so the single-document and JSONL rescans are still idempotent and keep their earlier prefixes. isAlreadyMasked stays only where the value is known to have just come from Mask: the sensitive-key mask in sanitizeJSONString. The one place a full Scan sees redacted text is the content collector's retry prompt, which pattern-scans the feedback again to catch a token sanitizing or folding joined. Its doc comment and the tracing guide now say that a connection-string placeholder there is masked "***". Tests: a db_connection_password value shaped like a placeholder is masked, a full rescan masks the placeholder to "***" rather than leaving it, and a whole-value rescan leaves it intact. Signed-off-by: anevans --- docs/guides/dev/tracing.md | 2 +- internal/cli/content_collector.go | 5 +++-- internal/security/redactor.go | 23 +++++++++++++-------- internal/security/scanner_test.go | 34 +++++++++++++++++++++++++++++++ 4 files changed, 53 insertions(+), 11 deletions(-) diff --git a/docs/guides/dev/tracing.md b/docs/guides/dev/tracing.md index 6dee541cc6..af1c9b2669 100644 --- a/docs/guides/dev/tracing.md +++ b/docs/guides/dev/tracing.md @@ -357,7 +357,7 @@ characters or a URL `maskURLs` would mask, since the cut can take the `@` that marks a password (`promptHidesAlterations`) — is recorded `***` whole; the prompt the agent is sent is not changed, and the mask the first scan leaves for a connection-string password of ten or more bytes matches -its own pattern and counts a finding — +its own pattern, counts a finding, and is itself masked `***` — and sets `gen_ai.input.messages` on the span before the runtime starts, so each finalize path carries it. Its findings join the iteration's, and its encoded size is charged against diff --git a/internal/cli/content_collector.go b/internal/cli/content_collector.go index b7e5a5addd..452dddc88a 100644 --- a/internal/cli/content_collector.go +++ b/internal/cli/content_collector.go @@ -190,8 +190,9 @@ func attachContent(span trace.Span, res contentResult) { // values, once more after the fold, which can spell out a value that pass // saw in compatibility forms. The mask that first scan leaves for a // connection-string password of ten or more bytes ("abcd...") matches its -// own pattern again, so such a prompt counts a finding here; a shorter -// password is masked "***", which does not. +// own pattern again, so such a prompt counts a finding here and the +// placeholder is masked "***"; a shorter password is masked "***", which +// does not match. // The pipeline also folds compatibility characters the agent received // unfolded. Findings join the iteration's and surface through Result. // diff --git a/internal/security/redactor.go b/internal/security/redactor.go index f1024693ba..b7b52d6c02 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -227,14 +227,18 @@ func (s *SecretRedactor) scan(text string, wholeValueOnly bool) ScanResult { if len(secret) == 0 { continue } - // A captured value that is already a mask placeholder is the - // product of an earlier redaction pass, not a new leak. Re-masking - // it would discard the informative prefix for no security gain, - // and it lets the serialized-JSON backstop run on every document - // without degrading prior redactions. - if isAlreadyMasked(secret) { - continue - } + // A captured value is always masked, even when it already looks + // like a mask. The shape of a placeholder (4 characters and "...", + // or "***") is also the shape of a real short secret: + // db_connection_password accepts a value of 4 characters or more, + // so skipping every 7-byte capture that ends in "..." left a real + // password such as postgres://u:abcd...@host in the output. Callers + // that rescan bytes an earlier pass already redacted use + // ScanWholeValueSecrets, which runs no value pattern, so they never + // reach this loop; a full Scan over redacted text can therefore + // only be re-masking a placeholder into "***", never a secret into + // itself. + // // Only json_field needs the length gate here: its value pattern // matches any length, while env_assignment, auth_header and // db_connection_password enforce their own minimum in the pattern. @@ -286,6 +290,9 @@ func Mask(value string) string { // a JSON string can be followed by escape characters once the string is // re-encoded, and that tail must not turn the placeholder into a new secret // (#5705). +// +// Only callers that know the value came from Mask may use this. The shape alone +// cannot tell a placeholder from a real short secret, so Scan does not apply it. func isAlreadyMasked(value string) bool { value = strings.TrimRight(value, `\`) return value == "***" || len(value) == 7 && strings.HasSuffix(value, "...") diff --git a/internal/security/scanner_test.go b/internal/security/scanner_test.go index 39578f85ed..b44f4bdb4d 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -262,6 +262,40 @@ func TestSecretRedactor(t *testing.T) { assert.True(t, result.Safe || !hasFinding(result, "db_connection_password")) }) + // A real password can look like a mask placeholder: the placeholder shape + // (4 characters and "...") is 7 bytes, and db_connection_password accepts a + // value of 4 or more, so a shape test in the redactor skipped it and left + // the password in the output (#5705). + t.Run("db password shaped like a mask placeholder redacted", func(t *testing.T) { + result := r.Scan("postgres://user:abcd...@host:5432/db") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "db_connection_password")) + assert.Equal(t, "postgres://user:***@host:5432/db", result.Sanitized) + }) + + // Rescanning redacted text with a full Scan re-masks the placeholder: a + // seven-byte placeholder is shorter than ten, so Mask returns "***". The + // text stays redacted; only the informative prefix is lost. Callers that + // rescan bytes an earlier pass redacted use ScanWholeValueSecrets, which + // runs no value pattern and leaves the placeholder alone. + t.Run("db password placeholder remasked on a full rescan", func(t *testing.T) { + first := r.Scan("postgres://user:hunter2secret@host:5432/db") + require.False(t, first.Safe) + require.Equal(t, "postgres://user:hunt...@host:5432/db", first.Sanitized) + + second := r.Scan(first.Sanitized) + assert.Equal(t, "postgres://user:***@host:5432/db", second.Sanitized, + "a placeholder is still redacted, never left as itself") + assert.False(t, second.Safe) + }) + + t.Run("whole-value rescan leaves a placeholder intact", func(t *testing.T) { + const redacted = "postgres://user:hunt...@host:5432/db" + result := r.ScanWholeValueSecrets(redacted) + assert.True(t, result.Safe) + assert.Empty(t, result.Sanitized, "the earlier redaction must survive a whole-value rescan") + }) + t.Run("db password with multiple @ redacted", func(t *testing.T) { result := r.Scan("postgres://user:P@ss@w0rd@host:5432/db") assert.False(t, result.Safe) From cd855b3dee18a0bf829589eed44ed101d1a2c8f5 Mon Sep 17 00:00:00 2001 From: anevans Date: Wed, 25 Nov 2026 09:21:25 -0500 Subject: [PATCH 43/51] fix(#5705): mask body-line key names and keep every cause of a failed run Three findings from review. spanningPrivateKeys treated an object key between the boundary members as structure unless its name carried a marker, and the joined-run test broke at every key. A block whose body line was written as a member name therefore survived: {"":1,"MIIEow...":2,"":3} came back with the body intact, and once the markers were masked the written-bytes rescan could no longer see the block. A middle key is now masked when its own name carries key material, in both the document path and the JSONL path. A key still breaks the joined run on purpose: letting one join a group that also holds body material renamed severity/category/file and made the review fail schema validation, which is the #5705 outcome. That half is pinned by TestSanitizeJSONDocument_StructuralKeysKeepNamesNextToMaterial. postScriptGate posted a result file the scan had failed on. When the result file's write or sanitization failed and the quarantine then could not replace or remove it, the unredacted bytes stayed on disk and still parsed, so the gate posted them. Each scan failure now records the path it could not handle in outputScanError (internal, never printed or posted), and the gate skips the post-script when the harness result file is one of them or sits under a directory the walk could not open. Step 9f returned the scan failure alone, replacing an agent failure. With both, the gate missed agentFailedError and ran the post-script without FULLSEND_AGENT_EXIT_CODE. The scan error is now joined with runTerminalError, so errors.As finds both and the run error names both. Tests: body-in-key coverage for the document and JSONL paths, structural keys keeping their names next to body material, the failed-on result file being refused, and the agent failure surviving the join with FULLSEND_AGENT_EXIT_CODE set. Docs: runtime-implementation.md and run-artifacts-and-private-data.md describe the key-name rule, the joined terminal error and the refused result file. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 46 ++++++---- .../user/run-artifacts-and-private-data.md | 5 +- internal/cli/run.go | 89 +++++++++++++++++-- internal/cli/run_test.go | 44 +++++++++ internal/cli/scan_output_telemetry_test.go | 6 ++ internal/security/jsonsanitize.go | 35 +++++--- internal/security/jsonsanitize_test.go | 72 +++++++++++++++ 7 files changed, 258 insertions(+), 39 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 4ab72151c7..d2e6812451 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -660,22 +660,27 @@ shape — every required field of a review result is still present, and its enum-valued fields (`action`, `severity`, `category`) and patterned fields (`head_sha`, finding `id`) keep values `review-result.schema.json` accepts — instead of being dropped whole or rewritten into a document the schema rejects. A -key name is treated as block content only when the match starts or ends in it or -the name itself carries a marker; then it is masked too, because it cannot be -written back as structure. A value that neither carries a marker nor holds a run -of that shape keeps its content: nothing distinguishes a quoted marker pair from -a split block, so the choice is between masking free text and enum values, which -loses the review, and keeping a fragment too short to be recognized as key -material. Because one member holds only one line of a body, the values between -the boundary members are also decided on their joined text: consecutive -base64-only values are concatenated, and if the result looks like a body line — -upper case, lower case and a base64-only character — every value in that run is -masked. That catches a body split into short or digit-free chunks, while an -object key, a value with punctuation or whitespace, a hex-only run or a lowercase -word breaks the run. A hex-only run is kept for the same reason the enum values -are: a PEM body is base64, while a hex run is more likely a commit SHA or a -finding id. A single isolated fragment below the floor, with no neighbour to join -it to, is still kept. +key name is treated as block content only when the match starts or ends in it, the +name itself carries a marker, or the name is a body line of the same shape a value +is tested for; then it is masked too, because it cannot be written back as +structure. A key whose name is base64 body material is key material rather than +structure, and keeping it would write the body back after the markers were masked, +where the written-bytes rescan can no longer see the block. A value that neither +carries a marker nor holds a run of that shape keeps its content: nothing +distinguishes a quoted marker pair from a split block, so the choice is between +masking free text and enum values, which loses the review, and keeping a fragment +too short to be recognized as key material. Because one member holds only one line +of a body, the values between the boundary members are also decided on their +joined text: consecutive base64-only values are concatenated, and if the result +looks like a body line — upper case, lower case and a base64-only character — +every value in that run is masked. That catches a body split into short or +digit-free chunks, while an object key, a value with punctuation or whitespace, a +hex-only run or a lowercase word breaks the run. A key never joins the run: a key +is structure, and letting one join a group that also holds body material renames +required schema keys such as `severity` and `file`. A hex-only run is kept for the +same reason the enum values are: a PEM body is base64, while a hex run is more +likely a commit SHA or a finding id. A single isolated fragment below the floor, +with no neighbour to join it to, is still kept. `.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the record framing; a secret that spans records cannot be redacted without rewriting that framing, so only the records that carry it are replaced, and a @@ -744,7 +749,14 @@ post-script runs, posts the result, and the run still fails, so one unreadable or unwritable file somewhere else under the run directory cannot turn a completed report into silence. A result file the scan replaced with a fail-closed marker does not count: the marker is valid JSON, but it is not the -agent's result, and posting it would report a removal as the review. +agent's result, and posting it would report a removal as the review. Neither does +a result file the scan failed *on*: when its write or sanitization failed and the +quarantine then could not replace or remove it, the unredacted bytes are still on +disk and still parse, so the gate refuses to post them. The paths the scan could +not handle are kept internal for that decision and never printed or posted. The +scan error is joined with the run's own terminal outcome rather than replacing it, +so a run whose agent also failed still fails with both causes and the post-script +still receives `FULLSEND_AGENT_EXIT_CODE`. ## Agent rule layering diff --git a/docs/guides/user/run-artifacts-and-private-data.md b/docs/guides/user/run-artifacts-and-private-data.md index 184e40e061..c96ce82a65 100644 --- a/docs/guides/user/run-artifacts-and-private-data.md +++ b/docs/guides/user/run-artifacts-and-private-data.md @@ -351,8 +351,9 @@ file whose redacted content cannot be read, written or computed is replaced by such a marker and fails the run. If the marker cannot be written and the file cannot be removed either, the run's error says the unredacted file is still on disk. A private-key block that spans JSON members is handled in place instead: -the keys keep their names, and each string value that carries block text or -base64 key material becomes `[REDACTED PRIVATE KEY]`. When a +object keys keep their names unless a key name is itself a line of the key body, +and each string value — or key name — that carries block text or base64 key +material becomes `[REDACTED PRIVATE KEY]`. When a replacement happens in a run that still exits 0, the job log says so. On GitHub Actions this is an error annotation: fullsend writes a `::error::` workflow command whenever the job sets `GITHUB_ACTIONS=true`, and GitHub Actions renders diff --git a/internal/cli/run.go b/internal/cli/run.go index 9291568a69..8cb49664fa 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -3508,7 +3508,12 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // Collect the sandbox audit trail even when the scan failed: those runs // are the ones where it matters most. if err := collectPostScanSecurityArtifacts(runDir, sandboxName, printer, progressVerbosity, scanErr); err != nil { - return err + // Join the terminal outcome rather than return the scan failure + // alone. A run whose agent also failed keeps its agentFailedError, + // so the post-script gate still runs the post-script with + // FULLSEND_AGENT_EXIT_CODE set and the run error names both causes + // (#5705). + return postScanRunError(runTerminalError(h.ValidationLoop != nil, validationPassed, lastIterTimedOut, lastExitCode, agentExitReason, runCount, lastIterElapsed, timeout), err) } } @@ -4326,6 +4331,16 @@ func runTerminalError(hasLoop, validationPassed, timedOut bool, exitCode int, ex return nil } +// postScanRunError combines the run's own terminal outcome with the failure of +// the post-agent output scan and the sandbox audit collection. The scan failure +// must not replace an agent failure: the post-script gate keys off +// agentFailedError to run the post-script with FULLSEND_AGENT_EXIT_CODE set, and +// the run error has to name every cause (#5705). errors.Join keeps each cause +// reachable through errors.As even when the terminal outcome is nil. +func postScanRunError(terminalErr, scanErr error) error { + return errors.Join(terminalErr, scanErr) +} + // agentFailedError ends a run without a validation_loop whose agent failed // (#8305). The post-script gate tells it apart from other run errors. type agentFailedError struct { @@ -4377,6 +4392,12 @@ func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverrid if !ok { return postScriptDecision{message: "Skipping post-script: the output scan failed and left no result file that parses"} } + // A result file the scan could not write or sanitize is only still + // parseable because the quarantine could not replace it either: its bytes + // were never redacted, so posting it would publish them (#5705). + if scanErr.failedOn(resultFile) { + return postScriptDecision{message: "Skipping post-script: the output scan could not redact the result file"} + } return postScriptDecision{ run: true, message: fmt.Sprintf("The output scan failed but left %s: running the post-script; the run still fails", filepath.Base(resultFile)), @@ -7309,11 +7330,42 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri printer.StepDone("Output files clean — no issues found") } if err := errors.Join(writeErrs...); err != nil { - return &outputScanError{err: err, files: unreadable + unwritable + unsanitizable} + return &outputScanError{ + err: err, + files: unreadable + unwritable + unsanitizable, + failed: failedOutputPaths(writeErrs), + } } return nil } +// failedOutputPaths collects the paths of the output files the scan could not +// handle. The gate needs them to tell a result file that survived the scan from +// one the scan failed on, and the paths stay internal: they name agent-chosen +// files, so they never reach a printed line (ADR 0163). +func failedOutputPaths(errs []error) []string { + var paths []string + for _, err := range errs { + var failure *outputFileFailure + if errors.As(err, &failure) { + paths = append(paths, failure.path) + } + } + return paths +} + +// outputFileFailure records one output file the scan could not read, sanitize or +// write, with the path it could not handle. The path is not part of the message +// the quiet level prints; it is kept so the post-script gate can refuse to post a +// result file this scan could not redact (#5705). +type outputFileFailure struct { + path string + err error +} + +func (e *outputFileFailure) Error() string { return e.err.Error() } +func (e *outputFileFailure) Unwrap() error { return e.err } + // postAgentScanFailurePrefix labels a failed post-agent output scan in the run // error and in the fixed text the completion comment carries at quiet. const postAgentScanFailurePrefix = "post-agent output scan failed" @@ -7327,11 +7379,33 @@ const postAgentScanFailurePrefix = "post-agent output scan failed" type outputScanError struct { err error files int + // failed holds the paths of the output files the scan could not handle. The + // post-script gate uses it to tell a result file that survived the scan from + // one whose write or sanitization failed, which can still parse when the + // quarantine could not replace it (#5705). Like every other path here it is + // internal: never printed, never posted. + failed []string } func (e *outputScanError) Error() string { return e.err.Error() } func (e *outputScanError) Unwrap() error { return e.err } +// failedOn reports whether the scan could not handle path, or any directory that +// contains it, so the bytes at path were never guaranteed redacted. +func (e *outputScanError) failedOn(path string) bool { + for _, failed := range e.failed { + if failed == path { + return true + } + // A directory the walk could not open was never scanned, and neither was + // anything under it. + if strings.HasPrefix(path, failed+string(os.PathSeparator)) { + return true + } + } + return false +} + // QuietStatusDetail is the fixed text the completion comment carries at quiet: // how many output files the scan could not handle, never a name or a cause. func (e *outputScanError) QuietStatusDetail() string { @@ -7379,7 +7453,8 @@ func alertOnRecordRemoval(printer *ui.Printer, sanitized []byte) { func writeFailure(path, relPath string, writeErr error, unwritable *int) error { *unwritable++ quarantineErr := quarantineOutput(path) - return errors.Join(fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr), quarantineErr) + return &outputFileFailure{path: path, err: errors.Join( + fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr), quarantineErr)} } // readFailure records an output file that could not be read. Its bytes cannot be @@ -7391,7 +7466,8 @@ func writeFailure(path, relPath string, writeErr error, unwritable *int) error { func readFailure(path, relPath string, readErr error, unreadable *int) error { *unreadable++ quarantineErr := quarantineOutput(path) - return errors.Join(fmt.Errorf("could not read %s: %w", relPath, readErr), quarantineErr) + return &outputFileFailure{path: path, err: errors.Join( + fmt.Errorf("could not read %s: %w", relPath, readErr), quarantineErr)} } // walkFailure records an entry the walk could not open. Nothing under it was @@ -7406,7 +7482,7 @@ func walkFailure(outputDir, path string, walkErr error, unreadable *int) error { if err != nil { relPath = path } - return fmt.Errorf("could not read %s: %w", relPath, walkErr) + return &outputFileFailure{path: path, err: fmt.Errorf("could not read %s: %w", relPath, walkErr)} } // sanitizeFailure records a sanitization error and contains the file it could @@ -7418,7 +7494,8 @@ func walkFailure(outputDir, path string, walkErr error, unreadable *int) error { func sanitizeFailure(path, relPath string, scanErr error, unsanitizable *int) error { *unsanitizable++ quarantineErr := quarantineOutput(path) - return errors.Join(fmt.Errorf("could not sanitize %s: %w", relPath, scanErr), quarantineErr) + return &outputFileFailure{path: path, err: errors.Join( + fmt.Errorf("could not sanitize %s: %w", relPath, scanErr), quarantineErr)} } // quarantineOutput replaces path with the fail-closed marker, removing it if even diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index e67a71c4fb..ec616a95ba 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -5437,6 +5437,50 @@ func TestPostScriptGate(t *testing.T) { assert.Contains(t, got.message, "left no result file that parses", marker) } }) + t.Run("no loop, output scan could not redact the result", func(t *testing.T) { + t.Parallel() + // The scan's write or sanitize failed *and* the quarantine could not + // replace the file, so the unredacted bytes are still on disk and still + // parse. Posting them would publish exactly what the scan failed to redact. + for _, unredacted := range []string{ + `{"action":"approve","body":"token ghp_FAKEtesttoken000000000000000000000000"}`, + `{"action":"approve","body":"secret"}`, + } { + dir := writeResult(t, "agent-result.json", unredacted) + resultPath := filepath.Join(dir, "agent-result.json") + scanErr := &outputScanError{ + err: errors.New("could not write sanitized agent-result.json: no space left on device"), + files: 1, + failed: []string{resultPath}, + } + got := postScriptGate(noLoop, false, false, scanErr, dir) + assert.False(t, got.run, "a result file the scan could not redact must not be posted") + assert.Contains(t, got.message, "could not redact the result file") + + // A failure on a directory above the result file hides it the same + // way: the walk never scanned what is under it. + parent := &outputScanError{err: errors.New("could not read iteration-1"), files: 1, failed: []string{dir}} + assert.False(t, postScriptGate(noLoop, false, false, parent, dir).run) + } + }) + t.Run("no loop, failed agent and failed scan, valid result", func(t *testing.T) { + t.Parallel() + // Step 9f joins the terminal error with the scan error, so an agent that + // also failed keeps its agentFailedError through the join. + scanErr := &outputScanError{err: errors.New("could not write sanitized notes.md: no space left on device"), files: 1} + runErr := postScanRunError(agentFailed, fmt.Errorf("%s: %w", postAgentScanFailurePrefix, scanErr)) + var agentErr *agentFailedError + var scanAsErr *outputScanError + require.ErrorAs(t, runErr, &agentErr, "the agent failure must survive the join") + require.ErrorAs(t, runErr, &scanAsErr, "the scan failure must survive the join") + assert.Contains(t, runErr.Error(), "agent failed with exit code 1") + assert.Contains(t, runErr.Error(), "post-agent output scan failed") + + got := postScriptGate(noLoop, false, false, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.True(t, got.run, "an intact result is still posted") + assert.Equal(t, 1, got.agentExitCode, + "the post-script runs with FULLSEND_AGENT_EXIT_CODE after an agent failure") + }) t.Run("no loop, failed agent, quarantined result", func(t *testing.T) { t.Parallel() dir := writeResult(t, "agent-result.json", unwritableOutputMarker) diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 8635594ede..02d104e1b0 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -442,6 +442,12 @@ func TestScanOutputFiles_ReportsFailedQuarantine(t *testing.T) { assert.Contains(t, err.Error(), "could not write sanitized secret.txt") assert.Contains(t, err.Error(), "unredacted output file could not be replaced or removed", "a failed quarantine must reach the joined error") + + var scanErr *outputScanError + require.ErrorAs(t, err, &scanErr) + assert.True(t, scanErr.failedOn(path), + "the file whose write and quarantine both failed must be recorded, so the gate cannot post its unredacted bytes") + assert.False(t, scanErr.failedOn(filepath.Join(dir, "other.json")), "a file the scan handled is not recorded") } // TestScanOutputFiles_SanitizerErrorContainsFileAndContinues pins that a diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 708687f542..6fc8d9f6e5 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -255,8 +255,9 @@ type privateKeySpans struct { // covered holds the indexes of the string values that carry part of a block // spanning more than one leaf. Every covered value is replaced whole. covered map[int]bool - // maskedKeys holds the indexes of the object keys whose own name carries a - // block marker and is therefore block content rather than structure. + // maskedKeys holds the indexes of the object keys whose own name carries + // block content — a marker, or a run of base64 body material — so the name + // is key material rather than structure. maskedKeys map[int]bool // localized counts the blocks that were mapped onto leaves. localized int @@ -281,9 +282,12 @@ type privateKeySpans struct { // values between a quoted marker pair stay readable, so a review result keeps its // shape instead of failing schema validation and being dropped (#5705). An object // key keeps its name unless the match starts or ends in it, or the name itself -// carries a block marker: key names are the document's structure, and masking them -// would drop a required field such as a finding's severity, category or file and -// make the document fail schema validation. +// carries block content — a marker or a run of base64 body material: key names are +// the document's structure, and masking them would drop a required field such as a +// finding's severity, category or file and make the document fail schema +// validation. A key name that is itself a body line is not structure, though; it is +// key material, and leaving it writes the body back after the markers are masked, +// where the written-bytes rescan can no longer see the block (#5705). func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { spans := privateKeySpans{covered: map[int]bool{}, maskedKeys: map[int]bool{}} for _, match := range privateKeyRe.FindAllIndex(v.decoded.Bytes(), -1) { @@ -313,7 +317,7 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { // neither fragment matches privateKeyMarkerRe on its own. atBoundary := pos == 0 || pos == len(hit)-1 if v.keys[i] { - if atBoundary || privateKeyMarkerRe.Match(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) { + if atBoundary || v.valueCarriesKeyMaterial(i) { spans.maskedKeys[i] = true } continue @@ -332,9 +336,11 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { // is short or digit-free; a per-member test then accepts none of them and writes // the body back after the markers are masked, where the written-bytes rescan can // no longer see the block (#5705). Consecutive candidate segments are therefore -// decided together. An object key between two values breaks the run, because a -// key is structure rather than body, and a value with punctuation or whitespace -// breaks it too: those are structural tokens and free text, not body lines. +// decided together. An object key between two values breaks the run: a key is +// structure, and letting one join a run that also holds body material renames +// required schema keys (severity, category, file) and makes the review fail +// validation. A key whose own name is a body line is masked on its own instead +// (spanningPrivateKeys). func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { var group []int flush := func() { @@ -366,9 +372,9 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { flush() } -// valueCarriesKeyMaterial reports whether the string value at index i has to be -// replaced whole: it carries a block marker, or one of its runs holds base64 -// body material. +// valueCarriesKeyMaterial reports whether the decoded key or string value at +// index i has to be replaced whole: it carries a block marker, or one of its runs +// holds base64 body material. func (v *jsonProvenance) valueCarriesKeyMaterial(i int) bool { return textCarriesKeyMaterial(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) } @@ -730,7 +736,8 @@ func (v *jsonLineView) spanningRecordPrivateKeys() ([]bool, []Finding) { // body split so that every line is short or digit-free is only recognizable once // the lines are joined. An object key breaks the run, since a key is structure // rather than body, and so does a value with punctuation or whitespace: those are -// structural tokens and free text, not body lines. +// structural tokens and free text, not body lines. A key whose own name is a body +// line carries key material, so its record is covered on its own. func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { first, last := hit[0], hit[len(hit)-1] var group []int @@ -759,7 +766,7 @@ func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { text := v.decoded.Bytes()[leaf.span.start:leaf.span.end] if leaf.key { flush() - if privateKeyMarkerRe.Match(text) { + if textCarriesKeyMaterial(text) { covered[leaf.record] = true } continue diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index a6a95b5847..93e2c53be2 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -362,6 +362,47 @@ func TestJSONProvenance_KeysAreStructure(t *testing.T) { assert.False(t, spans.covered[5], "free text between the markers is not key material") } +// TestSanitizeJSONDocument_BodyLineAsKeyBetweenMarkersMasked pins that a key name +// which is itself a body line is key material, not structure. Once the boundary +// markers are masked the written-bytes rescan can no longer see the block, so a +// body kept in a key name would be written back unmasked (#5705). +func TestSanitizeJSONDocument_BodyLineAsKeyBetweenMarkersMasked(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + const body = "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + doc := []byte(`{"` + begin + `":1,"` + body + `":2,"` + end + `":3}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), body, "a body line in a key name is key material") + assert.NotContains(t, string(out), "BEGIN RSA") + assert.NotContains(t, string(out), "END RSA") +} + +// TestSanitizeJSONDocument_StructuralKeysKeepNamesNextToMaterial pins the other +// side of the same rule: a structural key between the markers keeps its name even +// when the values around it carry body material. Letting a key join the +// joined-run test would rename required schema keys and drop the review (#5705). +func TestSanitizeJSONDocument_StructuralKeysKeepNamesNextToMaterial(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + doc := []byte(`{"` + begin + `":"x","severity":"high","category":"logic-error",` + + `"body":"MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez","` + end + `":"y"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + for _, key := range []string{`"severity":`, `"category":`, `"body":`} { + assert.Contains(t, string(out), key, "a structural key keeps its name") + } + assert.NotContains(t, string(out), "x7Qz9restOfTheBodyWq1Ez", "the body material is masked") +} + // TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed pins that a // document with no leaf findings is still scanned in its written form. A // runtime secret spanning two member boundaries is visible only in the raw @@ -860,6 +901,37 @@ func TestSanitizeJSONLines_QuotedMarkersKeepCleanRecords(t *testing.T) { assert.Equal(t, `{"event":"normal record two"}`, lines[2], "a record carrying no block content must survive") } +// TestSanitizeJSONLines_BodyLineAsKeyBetweenMarkersCovered pins the record-level +// half of the body-in-key rule: a middle record whose key name is itself a body +// line carries key material and must be replaced, while a clean record between the +// markers still survives (#5705). +func TestSanitizeJSONLines_BodyLineAsKeyBetweenMarkersCovered(t *testing.T) { + p := OutputPipeline() + begin := "-----BEGIN RSA" + " PRIVATE KEY-----" + end := "-----END RSA" + " PRIVATE KEY-----" + const body = "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + content := []byte( + "{\"" + begin + "\":1}\n" + + "{\"event\":\"normal record\"}\n" + + "{\"" + body + "\":2}\n" + + "{\"" + end + "\":3}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), body, "a body line in a key name is key material") + assert.NotContains(t, string(out), begin) + assert.NotContains(t, string(out), end) + + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, i := range []int{0, 2, 3} { + assert.True(t, json.Valid([]byte(lines[i])), "each replaced record must stay valid JSON: %s", lines[i]) + assert.Contains(t, lines[i], "output removed") + } + assert.Equal(t, `{"event":"normal record"}`, lines[1], "a record carrying no block content must survive") +} + // TestSanitizeJSONLines_BodySplitAcrossRecordsCovered pins the other half: a // middle record is kept only when it really is clean. A body split so that every // record holds one short, digit-free chunk is still body material once the chunks From 61a74b757d402d206c6c897a90764ded4c32d4b4 Mon Sep 17 00:00:00 2001 From: anevans Date: Wed, 2 Dec 2026 11:55:56 -0500 Subject: [PATCH 44/51] fix(#5705): address output sanitizer review findings - Classify sensitive JSON keys after Unicode normalization and apply the #9944 author-path exemption in the structural path, so an obfuscated password field or a codex author path is handled like the text scan. - Only trust isAlreadyMasked for a value this scan rewrote; an original short secret that looks like a placeholder is still masked. - Reconstruct PEM body chunks across object keys in single documents and JSONL records instead of letting keys break the joined run. - Check scan.failedOn(resultFile) before the agent-failure gate branch so a joined agent+scan failure cannot post an unredacted result. - Inject the structural sanitizers and the findings downloader as parameters instead of mutable package globals. - Vendor the pinned review-result schema for the sanitizer tests. - Cover ndjson routing, audit-chain branches, test isolation, and shared PEM marker fixtures. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 22 +- internal/cli/run.go | 62 +-- internal/cli/run_postscan_test.go | 89 ++++- internal/cli/run_test.go | 18 + internal/cli/scan_output_telemetry_test.go | 85 ++++- internal/security/jsonsanitize.go | 84 +++- internal/security/jsonsanitize_test.go | 361 +++++++++++++----- internal/security/redactor.go | 7 + .../testdata/review-result.schema.json | 208 ++++++++++ 9 files changed, 769 insertions(+), 167 deletions(-) create mode 100644 internal/security/testdata/review-result.schema.json diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 507287c8f3..36a2b3b84b 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -684,13 +684,17 @@ of a body, the values between the boundary members are also decided on their joined text: consecutive base64-only values are concatenated, and if the result looks like a body line — upper case, lower case and a base64-only character — every value in that run is masked. That catches a body split into short or -digit-free chunks, while an object key, a value with punctuation or whitespace, a -hex-only run or a lowercase word breaks the run. A key never joins the run: a key -is structure, and letting one join a group that also holds body material renames -required schema keys such as `severity` and `file`. A hex-only run is kept for the -same reason the enum values are: a PEM body is base64, while a hex run is more -likely a commit SHA or a finding id. A single isolated fragment below the floor, -with no neighbour to join it to, is still kept. +digit-free chunks. An object key never joins the run — a key is structure, and +letting one join a group that also holds body material renames required schema +keys such as `severity` and `file` — but it does not break the run either: the +values on either side of a key are still consecutive body chunks once the key +names are ignored, so a body stored in separate object members is reconstructed +and masked. A value with punctuation or whitespace, or one shorter than four +characters, breaks the run: those are free text or a short token rather than a +body line. A hex-only value joined to base64 body material is masked with it; an +isolated hex-only run is kept, because a PEM body is base64 while a hex run is +more likely a commit SHA or a finding id. A single isolated fragment below the +floor, with no neighbour to join it to, is still kept. `.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the record framing; a secret that spans records cannot be redacted without rewriting that framing, so only the records that carry it are replaced, and a @@ -763,7 +767,9 @@ agent's result, and posting it would report a removal as the review. Neither doe a result file the scan failed *on*: when its write or sanitization failed and the quarantine then could not replace or remove it, the unredacted bytes are still on disk and still parse, so the gate refuses to post them. The paths the scan could -not handle are kept internal for that decision and never printed or posted. The +not handle are kept internal for that decision and never printed or posted. This +refusal is checked before the agent-failure branch, because a joined error can +hold both causes. The scan error is joined with the run's own terminal outcome rather than replacing it, so a run whose agent also failed still fails with both causes and the post-script still receives `FULLSEND_AGENT_EXIT_CODE`. diff --git a/internal/cli/run.go b/internal/cli/run.go index 24b1a409cf..56763469fd 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -3523,7 +3523,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep } // Collect the sandbox audit trail even when the scan failed: those runs // are the ones where it matters most. - if err := collectPostScanSecurityArtifacts(runDir, sandboxName, printer, progressVerbosity, scanErr); err != nil { + if err := collectPostScanSecurityArtifacts(runDir, sandboxName, printer, progressVerbosity, scanErr, sandbox.Download); err != nil { // Join the terminal outcome rather than return the scan failure // alone. A run whose agent also failed keeps its agentFailedError, // so the post-script gate still runs the post-script with @@ -4427,6 +4427,19 @@ func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverrid if h.ValidationLoop != nil && !validationPassed { return postScriptDecision{message: "Skipping post-script: validation did not pass"} } + // A result file the scan could not write or sanitize is only still parseable + // because the quarantine could not replace it either: its bytes were never + // redacted, so posting it would publish them (#5705). This is checked before + // the agent-failure branch because a joined error can hold both causes, and + // that branch would otherwise post the file without ever consulting the scan + // failure. + var scanErr *outputScanError + scanFailed := errors.As(runErr, &scanErr) + if scanFailed { + if resultFile, ok := agentResultFile(h, outputDir); ok && scanErr.failedOn(resultFile) { + return postScriptDecision{message: "Skipping post-script: the output scan could not redact the result file"} + } + } var agentErr *agentFailedError if errors.As(runErr, &agentErr) { resultFile, ok := agentResultFile(h, outputDir) @@ -4444,18 +4457,11 @@ func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverrid // completed report into silence: when the agent's own result file survived // the scan and still parses, the post-script runs and the run still fails // (#5705). - var scanErr *outputScanError - if errors.As(runErr, &scanErr) { + if scanFailed { resultFile, ok := agentResultFile(h, outputDir) if !ok { return postScriptDecision{message: "Skipping post-script: the output scan failed and left no result file that parses"} } - // A result file the scan could not write or sanitize is only still - // parseable because the quarantine could not replace it either: its bytes - // were never redacted, so posting it would publish them (#5705). - if scanErr.failedOn(resultFile) { - return postScriptDecision{message: "Skipping post-script: the output scan could not redact the result file"} - } return postScriptDecision{ run: true, message: fmt.Sprintf("The output scan failed but left %s: running the post-script; the run still fails", filepath.Base(resultFile)), @@ -7307,24 +7313,25 @@ func printExtractedOutputFiles(printer *ui.Printer, extracted []string, elapsed printer.StepDone(fmt.Sprintf("Extracted %d output file(s) (%.1fs)", len(extracted), elapsed.Seconds())) } -// The structural sanitizers are variables so tests can inject a sanitizer -// failure: their error path has no natural trigger, because they only fail on a -// decoder limit after json.Valid has accepted the document. -var ( - sanitizeJSONDocument = security.SanitizeJSONDocument - sanitizeJSONLines = security.SanitizeJSONLines -) - // scanOutputFiles runs the output security pipeline (unicode normalization and // secret redaction) on extracted output files, recursively walking all // subdirectories (iteration-N/output/, etc.). At the quiet progress level // (ADR 0163) it prints counts only: file paths and finding details, which // can carry agent-chosen names and matched text, stay in findings.jsonl. func scanOutputFiles(outputDir, traceID, progressVerbosity string, printer *ui.Printer) error { - return scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity, printer, os.WriteFile) + return scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity, printer, os.WriteFile, + security.SanitizeJSONDocument, security.SanitizeJSONLines) } -func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, printer *ui.Printer, writeFile func(string, []byte, os.FileMode) error) error { +// sanitizeDocumentFn sanitizes one JSON document. It is injected as a parameter +// rather than read from a package global so tests can stub the decoder-limit +// failure without introducing mutable package state. +type sanitizeDocumentFn func([]byte, *security.Pipeline) ([]byte, []security.Finding, error) + +// sanitizeLinesFn sanitizes one JSONL stream record by record. +type sanitizeLinesFn func([]byte, *security.Pipeline) ([]byte, []security.Finding, error) + +func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, printer *ui.Printer, writeFile func(string, []byte, os.FileMode) error, sanitizeDocument sanitizeDocumentFn, sanitizeLines sanitizeLinesFn) error { quiet := config.ProgressIsQuiet(progressVerbosity) if _, err := os.Stat(outputDir); os.IsNotExist(err) { printer.StepInfo("No output files to scan") @@ -7389,7 +7396,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri // JSONL and NDJSON are sanitized record by record so one record never // rewrites another (#5705). if ext == ".jsonl" || ext == ".ndjson" { - out, jsonLineFindings, scanErr := sanitizeJSONLines(content, pipeline) + out, jsonLineFindings, scanErr := sanitizeLines(content, pipeline) if scanErr != nil { writeErrs = append(writeErrs, sanitizeFailure(path, relPath, scanErr, &unsanitizable)) return nil @@ -7425,7 +7432,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri // where a redaction could still break its syntax. Non-JSON files fall // through to the plain text scan below. if security.IsJSONDocument(content) { - out, jsonFindings, jsonErr := sanitizeJSONDocument(content, pipeline) + out, jsonFindings, jsonErr := sanitizeDocument(content, pipeline) if jsonErr != nil { writeErrs = append(writeErrs, sanitizeFailure(path, relPath, jsonErr, &unsanitizable)) return nil @@ -7686,20 +7693,21 @@ func quarantineOutput(path string) error { // computed or written. It is valid JSON so downstream parsers keep working. const unwritableOutputMarker = `{"error":"output removed because it could not be redacted"}` -// downloadSandboxFindings extracts the sandbox-side findings directory. It is a -// variable so tests can observe the ordering contract of -// collectPostScanSecurityArtifacts without a sandbox. -var downloadSandboxFindings = sandbox.Download +// downloadFindingsFn extracts the sandbox-side findings directory. It is a +// parameter of collectPostScanSecurityArtifacts rather than a package global so +// tests can observe the ordering contract without a sandbox and without mutable +// package state. +type downloadFindingsFn func(sandboxName, remoteDir, localDir string) error // collectPostScanSecurityArtifacts extracts the sandbox-side security findings // and verifies the audit hash chain. scanErr is the outcome of the host output // scan; it is returned after the audit trail has been collected, so a failed // scan never skips the artifacts that explain the failure. -func collectPostScanSecurityArtifacts(runDir, sandboxName string, printer *ui.Printer, progressVerbosity string, scanErr error) error { +func collectPostScanSecurityArtifacts(runDir, sandboxName string, printer *ui.Printer, progressVerbosity string, scanErr error, downloadFindings downloadFindingsFn) error { findingsDir := filepath.Join(runDir, "security") if err := os.MkdirAll(findingsDir, 0o755); err == nil { remoteFindingsDir := sandbox.SandboxWorkspace + "/.security/" - if dlErr := downloadSandboxFindings(sandboxName, remoteFindingsDir, findingsDir); dlErr != nil { + if dlErr := downloadFindings(sandboxName, remoteFindingsDir, findingsDir); dlErr != nil { printer.StepInfo("No sandbox security findings to extract") } else { printer.StepDone("Security findings extracted") diff --git a/internal/cli/run_postscan_test.go b/internal/cli/run_postscan_test.go index 87fa5c3e95..929d79d495 100644 --- a/internal/cli/run_postscan_test.go +++ b/internal/cli/run_postscan_test.go @@ -2,14 +2,19 @@ package cli import ( "bytes" + "encoding/json" "errors" "fmt" + "os" + "path/filepath" + "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/security" "github.com/fullsend-ai/fullsend/internal/ui" ) @@ -19,16 +24,14 @@ import ( func TestCollectPostScanSecurityArtifactsRunsOnScanFailure(t *testing.T) { runDir := t.TempDir() var downloaded bool - original := downloadSandboxFindings - downloadSandboxFindings = func(_, _, _ string) error { + download := func(_, _, _ string) error { downloaded = true return nil } - t.Cleanup(func() { downloadSandboxFindings = original }) var buf bytes.Buffer scanErr := errors.New("could not write sanitized output file") - err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), "", scanErr) + err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), "", scanErr, download) require.Error(t, err) assert.True(t, downloaded, "sandbox findings must be extracted even when the scan failed") @@ -42,14 +45,12 @@ func TestCollectPostScanSecurityArtifactsRunsOnScanFailure(t *testing.T) { // files instead of the agent-chosen names (ADR 0163). func TestCollectPostScanSecurityArtifactsKeepsQuietStatusDetail(t *testing.T) { runDir := t.TempDir() - original := downloadSandboxFindings - downloadSandboxFindings = func(_, _, _ string) error { return errors.New("no findings") } - t.Cleanup(func() { downloadSandboxFindings = original }) + download := func(_, _, _ string) error { return errors.New("no findings") } const name = "@org/team-secret.json" scanErr := &outputScanError{err: fmt.Errorf("could not read %s: denied", name), files: 1} var buf bytes.Buffer - err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), config.ProgressVerbosityQuiet, scanErr) + err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), config.ProgressVerbosityQuiet, scanErr, download) require.Error(t, err) assert.Contains(t, err.Error(), name, "the run error keeps the path for telemetry") @@ -57,3 +58,75 @@ func TestCollectPostScanSecurityArtifactsKeepsQuietStatusDetail(t *testing.T) { failureStatusDetail(err, config.ProgressVerbosityQuiet)) assert.Contains(t, failureStatusDetail(err, ""), name, "full posts the error as before") } + +// TestCollectPostScanSecurityArtifactsAuditChainBranches pins the three branches +// behind the findings.jsonl guard: a valid chain is reported as verified, a +// tampered chain fails the run through chainErr, and a verification error is only +// a warning. The earlier tests use an empty run directory, so os.Stat fails and +// none of these branches runs — a regression that dropped chainErr would pass. +func TestCollectPostScanSecurityArtifactsAuditChainBranches(t *testing.T) { + download := func(_, _, _ string) error { return errors.New("no sandbox findings") } + + t.Run("valid chain is verified", func(t *testing.T) { + runDir := t.TempDir() + writeAuditChain(t, runDir, false) + + var buf bytes.Buffer + err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), "", nil, download) + require.NoError(t, err) + assert.Contains(t, buf.String(), "Audit log integrity verified (2 entries)") + }) + + t.Run("tampered chain fails the run", func(t *testing.T) { + runDir := t.TempDir() + writeAuditChain(t, runDir, true) + + var buf bytes.Buffer + err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), "", nil, download) + require.Error(t, err, "a tampered chain must reach the run error") + assert.Contains(t, err.Error(), "audit log integrity check failed") + assert.Contains(t, buf.String(), "Audit log integrity check FAILED") + }) + + t.Run("verification error is a warning only", func(t *testing.T) { + runDir := t.TempDir() + // A findings file that is a directory makes VerifyChain fail to open it, + // which the collector reports as a warning rather than a run failure. + require.NoError(t, os.MkdirAll(filepath.Join(runDir, "security", "findings.jsonl"), 0o755)) + + var buf bytes.Buffer + err := collectPostScanSecurityArtifacts(runDir, "sandbox", ui.New(&buf), "", nil, download) + require.NoError(t, err, "a verification error must not fail the run") + assert.Contains(t, buf.String(), "Audit log verification error") + }) +} + +// writeAuditChain stages runDir/security/findings.jsonl. With tamper set, the +// last record's detail is changed after the chain is written, so VerifyChain +// reports a hash mismatch. +func writeAuditChain(t *testing.T, runDir string, tamper bool) { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Join(runDir, "security"), 0o755)) + path := filepath.Join(runDir, "security", "findings.jsonl") + for _, detail := range []string{"first", "second"} { + require.NoError(t, security.AppendFinding(path, security.TracedFinding{ + TraceID: "trace-id", + Phase: "host_output", + Finding: security.Finding{Scanner: "secret_redactor", Name: "test", Severity: "low", Detail: detail}, + })) + } + if !tamper { + return + } + raw, err := os.ReadFile(path) + require.NoError(t, err) + lines := strings.Split(strings.TrimSuffix(string(raw), "\n"), "\n") + require.Len(t, lines, 2) + var entry security.TracedFinding + require.NoError(t, json.Unmarshal([]byte(lines[1]), &entry)) + entry.Detail = "TAMPERED" + newLine, err := json.Marshal(entry) + require.NoError(t, err) + lines[1] = string(newLine) + require.NoError(t, os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600)) +} diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index 9cdddea48d..e1f77ba680 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -5646,6 +5646,24 @@ func TestPostScriptGate(t *testing.T) { assert.Equal(t, 1, got.agentExitCode, "the post-script runs with FULLSEND_AGENT_EXIT_CODE after an agent failure") }) + t.Run("no loop, failed agent and failed scan that could not redact the result", func(t *testing.T) { + t.Parallel() + // The agent-failure branch must not bypass the scan's failedOn check: a + // joined error holds both causes, and the result file whose redaction + // failed (and whose quarantine could not replace it) is still unredacted. + dir := writeResult(t, "agent-result.json", `{"action":"approve","body":"token ghp_FAKEtesttoken000000000000000000000000"}`) + resultPath := filepath.Join(dir, "agent-result.json") + scanErr := &outputScanError{ + err: errors.New("could not write sanitized agent-result.json: no space left on device"), + files: 1, + failed: []string{resultPath}, + } + runErr := postScanRunError(agentFailed, fmt.Errorf("%s: %w", postAgentScanFailurePrefix, scanErr)) + + got := postScriptGate(noLoop, false, false, runErr, dir) + assert.False(t, got.run, "a joined agent+scan failure must still refuse the unredacted result") + assert.Contains(t, got.message, "could not redact the result file") + }) t.Run("no loop, failed agent, quarantined result", func(t *testing.T) { t.Parallel() dir := writeResult(t, "agent-result.json", unwritableOutputMarker) diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 02d104e1b0..14d311c81a 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -20,6 +20,22 @@ import ( "github.com/fullsend-ai/fullsend/internal/ui" ) +// pemBegin and pemEnd are the private-key markers used by the fixtures. They are +// split at definition so a source scan does not read this as key material, and +// defined once so every fixture is testing the same marker shape. +var ( + pemBegin = "-----BEGIN RSA" + " PRIVATE KEY-----" + pemEnd = "-----END RSA" + " PRIVATE KEY-----" +) + +// scanOutputFilesWithDefaults is the scanOutputFilesWithWriter call most tests +// want: real structural sanitizers and an injected writer. It keeps the +// injection seam a parameter rather than a mutable package global. +func scanOutputFilesWithDefaults(outputDir, traceID, progressVerbosity string, printer *ui.Printer, writeFile func(string, []byte, os.FileMode) error) error { + return scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity, printer, writeFile, + security.SanitizeJSONDocument, security.SanitizeJSONLines) +} + // TestScanOutputFiles_SkipsTelemetryArtifacts pins that the host-side output // redaction scan does NOT rewrite the telemetry JSONL file. It is still held // open for append during the scan, so an in-place rewrite would truncate it @@ -255,6 +271,8 @@ func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) { if _, err := exec.LookPath("jq"); err == nil { cmd := exec.Command("jq", ".", jsonFile6) assert.NoError(t, cmd.Run(), "jq must parse the sanitized incident-shaped fixture") + } else { + t.Logf("jq not found; the incident-fidelity jq parse check did not run (json.Valid was the only proxy)") } } @@ -328,8 +346,8 @@ func TestScanOutputFiles_JSONLCrossValuePrivateKeyRemainsValid(t *testing.T) { 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-----" + begin := pemBegin + end := pemEnd content := fmt.Sprintf("%s\nMIIEpAIBAAKCAQEA0123456789abcdefghijklmnop\n%s\n", begin, end) require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{}))) @@ -354,6 +372,7 @@ func TestScanOutputFiles_JSONLRawMultilinePEMRemainsValid(t *testing.T) { // the line in the step log and the exit status stays 0. func TestScanOutputFiles_EmitsAnnotationWhenOutputIsRemoved(t *testing.T) { const secret = `"v1","k2"` + security.ResetRuntimeSecretsForTest() require.True(t, security.RegisterRuntimeSecret(secret)) t.Cleanup(security.ResetRuntimeSecretsForTest) @@ -414,7 +433,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", "", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { + err := scanOutputFilesWithDefaults(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { return os.ErrPermission }) require.Error(t, err) @@ -434,8 +453,13 @@ func TestScanOutputFiles_ReportsFailedQuarantine(t *testing.T) { require.NoError(t, os.WriteFile(path, []byte("Token: ghp_FAKEtesttoken000000000000000000000000"), 0o444)) require.NoError(t, os.Chmod(dir, 0o555)) t.Cleanup(func() { _ = os.Chmod(dir, 0o755) }) + if f, err := os.Create(filepath.Join(dir, "probe")); err == nil { + _ = f.Close() + _ = os.Remove(f.Name()) + t.Skip("filesystem does not enforce unwritable directory permissions") + } - err := scanOutputFilesWithWriter(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { + err := scanOutputFilesWithDefaults(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { return os.ErrPermission }) require.Error(t, err) @@ -456,9 +480,7 @@ func TestScanOutputFiles_ReportsFailedQuarantine(t *testing.T) { // files, and the run still fails closed. The sanitizers only fail on a decoder // limit, so the failure is injected. func TestScanOutputFiles_SanitizerErrorContainsFileAndContinues(t *testing.T) { - original := sanitizeJSONDocument - t.Cleanup(func() { sanitizeJSONDocument = original }) - sanitizeJSONDocument = func([]byte, *security.Pipeline) ([]byte, []security.Finding, error) { + failingSanitizer := func([]byte, *security.Pipeline) ([]byte, []security.Finding, error) { return nil, nil, errors.New("decoder limit") } @@ -468,7 +490,7 @@ func TestScanOutputFiles_SanitizerErrorContainsFileAndContinues(t *testing.T) { later := filepath.Join(dir, "b-notes.txt") require.NoError(t, os.WriteFile(later, []byte("Token: ghp_FAKEtesttoken000000000000000000000000"), 0o644)) - err := scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{})) + err := scanOutputFilesWithWriter(dir, "trace-id", "", ui.New(&bytes.Buffer{}), os.WriteFile, failingSanitizer, security.SanitizeJSONLines) require.Error(t, err) assert.Contains(t, err.Error(), "could not sanitize a-result.json") @@ -488,8 +510,8 @@ func TestScanOutputFiles_SanitizerErrorContainsFileAndContinues(t *testing.T) { // never a whole-file marker, and without the annotation a lost record would only // show up as one scan line (#5705). func TestScanOutputFiles_EmitsAnnotationForJSONLRecordRemoval(t *testing.T) { - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd content := "{\"event\":\"start\",\"text\":\"" + begin + "\"}\n" + "{\"event\":\"body\",\"text\":\"MIIEpAIBAAKCAQEA0123456789abcdef\"}\n" + "{\"event\":\"end\",\"text\":\"" + end + "\"}\n" @@ -533,6 +555,37 @@ func TestScanOutputFiles_EmitsAnnotationForJSONLRecordRemoval(t *testing.T) { } } +// TestScanOutputFiles_HandlesJSONLAndNDJSON drives the record-scanning route over +// both extensions: .ndjson is accepted alongside .jsonl, but every other JSONL +// fixture names a .jsonl file. A multi-record .ndjson file that fell to the plain +// text scan could still have its record syntax broken by an in-place redaction, +// which is the corruption class #5705 set out to eliminate. +func TestScanOutputFiles_HandlesJSONLAndNDJSON(t *testing.T) { + content := "{\"event\":\"start\",\"text\":\"" + pemBegin + "\"}\n" + + "{\"event\":\"body\",\"text\":\"MIIEpAIBAAKCAQEA0123456789abcdef\"}\n" + + "{\"event\":\"end\",\"text\":\"" + pemEnd + "\"}\n" + + for _, ext := range []string{".jsonl", ".ndjson"} { + t.Run(ext, func(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "") + dir := t.TempDir() + path := filepath.Join(dir, "transcript"+ext) + require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) + + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&bytes.Buffer{}))) + + got, err := os.ReadFile(path) + require.NoError(t, err) + assert.NotContains(t, string(got), "MIIEpAIBAAKCAQEA", "the body must not survive in %s", ext) + lines := strings.Split(strings.TrimSuffix(string(got), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change in %s", ext) + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each record must stay valid JSON in %s: %s", ext, line) + } + }) + } +} + // TestScanOutputFiles_NoAnnotationForPreexistingMarkerLine pins that a clean // JSONL file that already holds a marker-equal line raises no error annotation: // this pass removed nothing, so an operator should not be told a record was lost. @@ -564,7 +617,7 @@ func TestScanOutputFiles_QuietWriteFailureKeepsPathAndCause(t *testing.T) { path := filepath.Join(dir, "secret.json") require.NoError(t, os.WriteFile(path, []byte(`{"token":"ghp_FAKEtesttoken000000000000000000000000"}`), 0o644)) writeErr := errors.New("no space left on device") - err := scanOutputFilesWithWriter(dir, "trace-id", "quiet", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { + err := scanOutputFilesWithDefaults(dir, "trace-id", "quiet", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { return writeErr }) require.Error(t, err) @@ -584,7 +637,7 @@ func TestScanOutputFiles_ContinuesRedactingAfterWriteFailure(t *testing.T) { require.NoError(t, os.WriteFile(first, []byte("Token: "+secret), 0o644)) require.NoError(t, os.WriteFile(second, []byte("Token: "+secret), 0o644)) - err := scanOutputFilesWithWriter(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(path string, data []byte, mode os.FileMode) error { + err := scanOutputFilesWithDefaults(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(path string, data []byte, mode os.FileMode) error { if path == first { return os.ErrPermission } @@ -676,7 +729,7 @@ func TestScanOutputFiles_WriteFailureRemovesUnredactedBytes(t *testing.T) { const secret = "ghp_FAKEtesttoken000000000000000000000000" require.NoError(t, os.WriteFile(path, []byte("Token: "+secret), 0o644)) - err := scanOutputFilesWithWriter(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { + err := scanOutputFilesWithDefaults(dir, "trace-id", "", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { return os.ErrPermission }) require.Error(t, err) @@ -792,7 +845,7 @@ func TestScanOutputFiles_QuietScanFailureStatusDetailOmitsAgentName(t *testing.T require.NoError(t, os.WriteFile(path, []byte(`{"token":"ghp_FAKEtesttoken000000000000000000000000"}`), 0o644)) writeErr := errors.New("no space left on device") - err := scanOutputFilesWithWriter(dir, "trace-id", "quiet", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { + err := scanOutputFilesWithDefaults(dir, "trace-id", "quiet", ui.New(&bytes.Buffer{}), func(string, []byte, os.FileMode) error { return writeErr }) require.Error(t, err) @@ -812,8 +865,8 @@ func TestScanOutputFiles_QuietScanFailureStatusDetailOmitsAgentName(t *testing.T // is not JSON whitespace, so before this it fell through to the plain-text scan, // which cannot guarantee the document keeps valid JSON syntax (#5705). func TestScanOutputFiles_SanitizesBOMPrefixedJSONStructurally(t *testing.T) { - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd doc := `{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `","verdict":"approve"}` dir := t.TempDir() diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 6fc8d9f6e5..20c79a2855 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -8,6 +8,7 @@ import ( "io" "regexp" "strconv" + "strings" "unicode/utf8" ) @@ -219,6 +220,12 @@ var privateKeyMaterialRe = regexp.MustCompile(`[A-Za-z0-9+/]{16,}=*`) // breaks a run of segments rather than joining one. var pemChunkCandidateRe = regexp.MustCompile(`^[A-Za-z0-9+/]+=*$`) +// minPEMChunkLen is the shortest value treated as a candidate PEM body segment +// in a joined run. A one- to three-character value between markers is more +// likely a free-text note or a short token than a body line, so it breaks the +// run rather than dragging its neighbours into a mask. +const minPEMChunkLen = 4 + // jsonProvenance accumulates an order-preserving view of the decoded strings // in a document so a private-key block that spans members can be detected after // JSON decoding. The raw bytes are not usable for this: a member may encode a @@ -336,10 +343,12 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { // is short or digit-free; a per-member test then accepts none of them and writes // the body back after the markers are masked, where the written-bytes rescan can // no longer see the block (#5705). Consecutive candidate segments are therefore -// decided together. An object key between two values breaks the run: a key is -// structure, and letting one join a run that also holds body material renames -// required schema keys (severity, category, file) and makes the review fail -// validation. A key whose own name is a body line is masked on its own instead +// decided together. An object key never joins the run — a key is structure, and +// letting one into the joined text renames required schema keys (severity, +// category, file) — but it does not break the run either: the values on either +// side of a key are still consecutive body chunks once the key names are ignored, +// so a body stored in separate object members is reconstructed and masked. A key +// whose own name is a body line is masked on its own instead // (spanningPrivateKeys). func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { var group []int @@ -359,11 +368,24 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { group = group[:0] } for pos, i := range hit { - if pos == 0 || pos == len(hit)-1 || v.keys[i] { + if pos == 0 || pos == len(hit)-1 { + flush() + continue + } + if v.keys[i] { + // The key is structure, not a body chunk: skip it without breaking + // the run (see the doc comment). + continue + } + chunk := v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end] + if v.valueCarriesKeyMaterial(i) { + // A value that is a complete body line on its own is covered by the + // main loop, and it ends the run: a structural value in the next + // member must not be joined into a mask with it. flush() continue } - if !pemChunkCandidateRe.Match(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) { + if len(chunk) < minPEMChunkLen || !pemChunkCandidateRe.Match(chunk) { flush() continue } @@ -734,10 +756,12 @@ func (v *jsonLineView) spanningRecordPrivateKeys() ([]bool, []Finding) { // records when their leaves carry key material. It is the record-level counterpart // of maskSpanBody: consecutive candidate leaves are decided together, because a // body split so that every line is short or digit-free is only recognizable once -// the lines are joined. An object key breaks the run, since a key is structure -// rather than body, and so does a value with punctuation or whitespace: those are -// structural tokens and free text, not body lines. A key whose own name is a body -// line carries key material, so its record is covered on its own. +// the lines are joined. An object key never joins the run, since a key is +// structure rather than body, but it does not break the run either: a body stored +// in separate object members of one record is still reconstructed. A value with +// punctuation or whitespace breaks the run: those are structural tokens and free +// text, not body lines. A key whose own name is a body line carries key material, +// so its record is covered on its own. func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { first, last := hit[0], hit[len(hit)-1] var group []int @@ -765,9 +789,13 @@ func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { } text := v.decoded.Bytes()[leaf.span.start:leaf.span.end] if leaf.key { - flush() + // A key name is structure: it never joins the run, but it must not + // break one either, so a body split across object members of the + // same record is still reconstructed. A key name that is itself + // body material covers the record on its own. if textCarriesKeyMaterial(text) { covered[leaf.record] = true + flush() } continue } @@ -776,7 +804,7 @@ func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { flush() continue } - if !pemChunkCandidateRe.Match(text) { + if len(text) < minPEMChunkLen || !pemChunkCandidateRe.Match(text) { flush() continue } @@ -1199,11 +1227,27 @@ func sanitizeJSONString(value, memberKey string, p *Pipeline) (string, []Finding res := p.Scan(value) out := value var findings []Finding - if len(res.Findings) > 0 { + rewritten := len(res.Findings) > 0 + if rewritten { findings = append(findings, res.Findings...) out = res.Sanitized } - if memberKey != "" && sensitiveJSONKeyRe.MatchString(memberKey) && !isAlreadyMasked(out) && + // Sensitivity is decided on the key as the leaf scan sees it: invisible + // characters stripped and compatibility forms folded, the same normalization + // sanitizeJSONKey applies when it writes the name back. Testing the original + // spelling let a key such as "pass\u200bword" be written as "password" with an + // untouched value (#5705). + key := normalizedJSONKey(memberKey) + // #9944: an "author" member holding a codex agent path is not a credential, + // although "author" contains the "auth" trigger word. The text pipeline + // honours this exemption; the structural path must too, because a codex + // transcript is a JSON document and takes that path. + exempt := strings.EqualFold(key, "author") && authorPathValue.MatchString(out) + // isAlreadyMasked is only trusted for a value this scan actually rewrote: + // the placeholder shape is also a real short-secret shape, so an original + // value must still be masked even when it looks like one (#5705). + if key != "" && !exempt && sensitiveJSONKeyRe.MatchString(key) && + !(rewritten && isAlreadyMasked(out)) && utf8.RuneCountInString(out) >= minJSONFieldLen { masked := Mask(out) findings = append(findings, Finding{ @@ -1216,3 +1260,15 @@ func sanitizeJSONString(value, memberKey string, p *Pipeline) (string, []Finding } return out, findings } + +// normalizedJSONKey returns key as the leaf scan sees it: invisible characters +// stripped and compatibility forms folded, exactly as sanitizeJSONKey normalizes +// the name it writes back. Sensitivity has to be checked on this spelling, or a +// zero-width or fullwidth obfuscated sensitive key becomes an explicitly +// sensitive field with an untouched value (#5705). +func normalizedJSONKey(key string) string { + if key == "" { + return "" + } + return decodedViewNormalizer.Scan(key).Sanitized +} diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 93e2c53be2..1a20e2eeda 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "fmt" + "os" "strings" "testing" @@ -11,6 +12,15 @@ import ( "github.com/stretchr/testify/require" ) +// pemBegin and pemEnd are the marker strings under test. They are split at +// definition so a source scan of the test files does not treat this as key +// material, and defined once so a marker-shape change cannot leave one fixture +// testing a different shape than the others. +var ( + pemBegin = "-----BEGIN RSA" + " PRIVATE KEY-----" + pemEnd = "-----END RSA" + " PRIVATE KEY-----" +) + // TestSanitizeJSONDocument_DuplicateKeyEarlierOccurrenceRedacted pins that a // secret in an earlier, overwritten duplicate-key occurrence is still found. // Map decoding drops that occurrence, so only a token-preserving walk sees it. @@ -53,8 +63,8 @@ func TestSanitizeJSONDocument_DuplicateKeysSurviveRewrite(t *testing.T) { // its verdict with it (#5705). func TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersMasksCoveredMembers(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd // Reverse the members' sort order so a map re-encode would emit END before // BEGIN and hide the block from a serialized scan. doc := []byte(`{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `","verdict":"approve"}`) @@ -79,8 +89,8 @@ func TestSanitizeJSONDocument_PrivateKeySplitAcrossMembersMasksCoveredMembers(t // written-bytes rescan could not catch it because the markers were gone (#5705). func TestSanitizeJSONDocument_HexPrefixBeforeBodyMaterialMasked(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd body := "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcw" doc := []byte(`{"a":"` + begin + `","b":"sha 0123456789abcdef0123 ` + body + `","c":"` + end + `"}`) @@ -106,8 +116,8 @@ func TestSanitizeJSONDocument_HexPrefixBeforeBodyMaterialMasked(t *testing.T) { // (#5705). func TestSanitizeJSONDocument_PathsAndProseBetweenMarkersStayReadable(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd path := "internal/security/jsonsanitize" prose := "a misconfiguration here" doc := []byte(`{"action":"comment","pr_number":12,"repo":"acme/widgets",` + @@ -209,8 +219,8 @@ func TestSanitizeJSONDocument_MarkersInSeparateFindingsKeepReview(t *testing.T) // constrains keep theirs so the review can still be posted (#5705). func TestSanitizeJSONDocument_KeyMaterialInSpanKeepsStructuralEnums(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd doc := []byte(`{"action":"request-changes","pr_number":12,"repo":"acme/widgets",` + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","findings":[` + `{"severity":"high","category":"secret-exposure","file":"a.go","description":"leaked ` + begin + `"},` + @@ -269,8 +279,8 @@ func TestSanitizeJSONDocument_MarkerSplitAcrossMembersMasked(t *testing.T) { // (#5705). func TestSanitizeJSONDocument_ChunkedBodyBetweenMarkersMasked(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd cases := map[string][]string{ "short chunks": {"MIIEowIB", "AAKCAQEA", "x9Kq2Lm"}, "digit-free chunk": {"MIIEowIBAAKCAQEA"}, @@ -304,8 +314,8 @@ func TestSanitizeJSONDocument_ChunkedBodyBetweenMarkersMasked(t *testing.T) { // hex-only run is far more likely a hash than a PEM line (#5705). func TestSanitizeJSONDocument_HexValuesInSpanKeepTheirContent(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd doc := []byte(`{"action":"comment","pr_number":12,"repo":"acme/widgets","findings":[` + `{"severity":"high","category":"logic-error","file":"a.go","id":"f_0123456789abcdef0123456789abcdef","description":"quotes the ` + begin + ` header"},` + `{"severity":"low","category":"doc-style","file":"b.go","id":"f_0123456789abcdef0123456789abcdef","description":"and the ` + end + ` footer"}],` + @@ -328,8 +338,8 @@ func TestSanitizeJSONDocument_HexValuesInSpanKeepTheirContent(t *testing.T) { // back, while a sibling key between the markers still keeps its name (#5705). func TestSanitizeJSONDocument_KeyNameCarryingMarkerIsMasked(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd doc := []byte(`{"` + begin + `":"x","severity":"high","` + end + `":"y"}`) out, findings, err := SanitizeJSONDocument(doc, p) @@ -346,8 +356,8 @@ func TestSanitizeJSONDocument_KeyNameCarryingMarkerIsMasked(t *testing.T) { // that a value between the markers is covered only when it carries key material, // so the rewrite never renames a key unless its own text carries a marker. func TestJSONProvenance_KeysAreStructure(t *testing.T) { - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd doc := []byte(`{"severity":"` + begin + `","category":"MIIEpAIBAAKCAQEA0123456789abcdef","body":"x","file":"` + end + `"}`) prov := collectJSONLeaves(doc) @@ -368,8 +378,8 @@ func TestJSONProvenance_KeysAreStructure(t *testing.T) { // body kept in a key name would be written back unmasked (#5705). func TestSanitizeJSONDocument_BodyLineAsKeyBetweenMarkersMasked(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd const body = "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" doc := []byte(`{"` + begin + `":1,"` + body + `":2,"` + end + `":3}`) @@ -388,8 +398,8 @@ func TestSanitizeJSONDocument_BodyLineAsKeyBetweenMarkersMasked(t *testing.T) { // joined-run test would rename required schema keys and drop the review (#5705). func TestSanitizeJSONDocument_StructuralKeysKeepNamesNextToMaterial(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd doc := []byte(`{"` + begin + `":"x","severity":"high","category":"logic-error",` + `"body":"MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez","` + end + `":"y"}`) @@ -429,8 +439,8 @@ func TestSanitizeJSONDocument_FramingSecretInCleanDocumentFailsClosed(t *testing // are masked while the rest of the document survives. func TestSanitizeJSONDocument_CrossMemberPrivateKeyWithLeafSecret(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd doc := []byte(`{"z_begin":"` + begin + `","m_body":"MIIEpAIBAAKCAQEA0123456789abcdef","a_end":"` + end + `",` + `"token":"ghp_FAKEtesttoken000000000000000000000000","verdict":"approve"}`) @@ -639,8 +649,8 @@ func TestSanitizeJSONDocument_KeyRemovedEntirelyIsReplaced(t *testing.T) { // record in the file. func TestSanitizeJSONLines_SingleRecordPEMKeepsCleanRecords(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd content := []byte( "{\"event\":\"clean-before\"}\n" + "{\"tool\":\"read\",\"text\":\"" + begin + "\\nMIIEpAIBAAKCAQEA0123456789abcdef\\n" + end + "\"}\n" + @@ -702,8 +712,8 @@ func TestOutputRecordRemovals(t *testing.T) { // recorded leaf range covers is reported as unmappable so the caller fails // closed instead of writing bytes that may still carry it. func TestJSONProvenance_UnmappableBlock(t *testing.T) { - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd v := &jsonProvenance{} v.decoded.WriteString(begin + "\n" + "MIIEkeymaterial" + "\n" + end + "\n") // One empty string value, which can never overlap a match. @@ -788,6 +798,8 @@ func TestSanitizeJSONDocument_CleanKeyWinsSanitizedCollision(t *testing.T) { p := OutputPipeline() doc := []byte(`{"` + secret + `":"secretkeyval","` + masked + `":"plainval"}`) + // Repeat so a map-iteration-order-dependent bug in name resolution cannot + // hide behind a single lucky ordering. for range 20 { out, findings, err := SanitizeJSONDocument(doc, p) require.NoError(t, err) @@ -845,8 +857,8 @@ func TestSanitizeJSONLines_RepeatedRecordsFailsClosed(t *testing.T) { // it. func TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd content := []byte( "[\"" + begin + "\"]\n" + "{\"value\":\"middle\"}\n" + @@ -877,8 +889,8 @@ func TestSanitizeJSONLines_RepeatedCleanRecordInsideCrossRecordMatch(t *testing. // (6dca72790, 078ffa2, b0ab1e2). func TestSanitizeJSONLines_QuotedMarkersKeepCleanRecords(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd content := []byte( "{\"event\":\"quote\",\"text\":\"" + begin + "\"}\n" + "{\"event\":\"normal record one\"}\n" + @@ -907,8 +919,8 @@ func TestSanitizeJSONLines_QuotedMarkersKeepCleanRecords(t *testing.T) { // markers still survives (#5705). func TestSanitizeJSONLines_BodyLineAsKeyBetweenMarkersCovered(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd const body = "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" content := []byte( "{\"" + begin + "\":1}\n" + @@ -938,8 +950,8 @@ func TestSanitizeJSONLines_BodyLineAsKeyBetweenMarkersCovered(t *testing.T) { // are joined, and every record carrying it must be replaced. func TestSanitizeJSONLines_BodySplitAcrossRecordsCovered(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd content := []byte( "[\"" + begin + "\"]\n" + "[\"dfghjk\"]\n" + @@ -966,8 +978,8 @@ func TestSanitizeJSONLines_BodySplitAcrossRecordsCovered(t *testing.T) { // detected in the original framing and its members are masked. func TestSanitizeJSONDocument_SensitiveBeginMemberMasksBlock(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd doc := []byte(`{"key_start":"` + begin + `","payload":"MIIEpAIBAAKCAQEA0123456789abcdef","tail":"` + end + `","verdict":"approve"}`) out, findings, err := SanitizeJSONDocument(doc, p) @@ -999,8 +1011,8 @@ func TestSanitizeJSONLines_CleanDuplicateKeyRecordPreserved(t *testing.T) { // block split over three records replaces all three. func TestSanitizeJSONLines_PrivateKeyAcrossRecordsFailsClosed(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd content := []byte(fmt.Sprintf("[%q]\n[%q]\n[%q]\n", begin, "MIIEpAIBAAKCAQEA0123456789abcdefghijklmnop", end)) out, findings, err := SanitizeJSONLines(content, p) @@ -1019,8 +1031,8 @@ func TestSanitizeJSONLines_PrivateKeyAcrossRecordsFailsClosed(t *testing.T) { // block written as raw lines rather than JSON values. func TestSanitizeJSONLines_RawMultilinePEMFailsClosed(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd content := []byte(fmt.Sprintf("%s\nMIIEpAIBAAKCAQEA0123456789abcdefghijklmnop\n%s\n", begin, end)) out, findings, err := SanitizeJSONLines(content, p) @@ -1079,8 +1091,8 @@ func TestSanitizeJSONLines_FramingSecretPreservesLineCount(t *testing.T) { // confined to one record is redacted rather than failed closed. func TestSanitizeJSONLines_SingleRecordPrivateKeyRedactedInPlace(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd content := []byte(fmt.Sprintf("{\"token\":\"ghp_FAKEtesttoken000000000000000000000000\",\"pem\":\"%s\\n%s\"}\n", begin, end)) out, findings, err := SanitizeJSONLines(content, p) @@ -1123,8 +1135,8 @@ func TestLineBounded(t *testing.T) { // document, and that neither leaves key material behind. func TestSanitizeJSONDocument_LeafAndSplitPrivateKeysMasked(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd doc := []byte(`{"note":"` + begin + `\nMIIEleafkeymaterial\n` + end + `",` + `"key_start":"` + begin + `","payload":"MIIEspanningkeymaterial0","tail":"` + end + `"}`) @@ -1141,8 +1153,8 @@ func TestSanitizeJSONDocument_LeafAndSplitPrivateKeysMasked(t *testing.T) { // a sensitive-named member removes its BEGIN marker. func TestSanitizeJSONLines_SensitiveBeginRecordFailsClosed(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd records := []string{ "{\"key_start\":\"" + begin + "\"}", "{\"payload\":\"MIIEspanningkeymaterial0\"}", @@ -1181,8 +1193,8 @@ func TestSanitizeJSONLines_SensitiveBeginRecordFailsClosed(t *testing.T) { // and decoded finding counts are not comparable. func TestSanitizeJSONDocument_EscapedLeafBlockDoesNotExemptSplitBlock(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd escapedBegin := `\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" doc := []byte(`{"note":"` + escapedBegin + `\nMIIEleafkeymaterial\n` + end + `",` + `"key_start":"` + begin + `","payload":"MIIEspanningkeymaterial0","tail":"` + end + `"}`) @@ -1200,7 +1212,7 @@ func TestSanitizeJSONDocument_EscapedLeafBlockDoesNotExemptSplitBlock(t *testing // the original record bytes. func TestSanitizeJSONLines_EscapedBeginRecordFailsClosed(t *testing.T) { p := OutputPipeline() - end := "-----END RSA" + " PRIVATE KEY-----" + end := pemEnd content := []byte(`{"key_start":"\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + `"}` + "\n" + `{"payload":"MIIEspanningkeymaterial0"}` + "\n" + `{"tail":"` + end + `"}` + "\n") @@ -1227,7 +1239,7 @@ func TestSanitizeJSONLines_EscapedBeginRecordFailsClosed(t *testing.T) { func TestSanitizeJSONLines_BOMRecordEscapedBeginFailsClosed(t *testing.T) { p := OutputPipeline() bom := "\ufeff" - end := "-----END RSA" + " PRIVATE KEY-----" + end := pemEnd content := []byte(bom + `{"a":"\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + `"}` + "\n" + `{"b":"MIIEspanningkeymaterial0"}` + "\n" + `{"c":"` + end + `"}` + "\n") @@ -1286,7 +1298,7 @@ func TestSanitizeJSONDocument_CRLFNoStrayCarriageReturn(t *testing.T) { // markers are \u-escaped in the raw bytes. func TestSanitizeJSONDocument_EscapedMarkersAcrossMembersMasked(t *testing.T) { p := OutputPipeline() - end := "-----END RSA" + " PRIVATE KEY-----" + end := pemEnd doc := []byte(`["\u002d` + "----BEGIN RSA" + " PRIVATE KEY-----" + `","MIIEspanningkeymaterial0","` + end + `"]`) @@ -1302,7 +1314,7 @@ func TestSanitizeJSONDocument_EscapedMarkersAcrossMembersMasked(t *testing.T) { // marker obfuscated with a zero-width character cannot hide a spanning block. func TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersMasked(t *testing.T) { p := OutputPipeline() - end := "-----END RSA" + " PRIVATE KEY-----" + end := pemEnd // U+200B inside the BEGIN marker: not a PEM block in any single form. doc := []byte(`{"begin":"-----\u200bBEGIN RSA` + " PRIVATE KEY-----\"" + `,"payload":"MIIEspanningkeymaterial0","end":"` + end + `"}`) @@ -1320,8 +1332,8 @@ func TestSanitizeJSONDocument_NormalizedMarkersAcrossMembersMasked(t *testing.T) // so both blocks are neutralized. func TestSanitizeJSONDocument_UnterminatedBeginBeforeCompleteBlockMasksBoth(t *testing.T) { p := OutputPipeline() - begin := "-----BEGIN RSA" + " PRIVATE KEY-----" - end := "-----END RSA" + " PRIVATE KEY-----" + begin := pemBegin + end := pemEnd doc := []byte(`{"a":"` + begin + `\nMIIEfirstkeymaterial","b":"` + begin + `\nZZZZZZZZ\n` + end + `"}`) out, findings, err := SanitizeJSONDocument(doc, p) @@ -1512,33 +1524,66 @@ func TestSanitizeJSONDocument_DuplicateKeyWithSecretKey(t *testing.T) { assert.NotContains(t, string(out), secret) } -// review-result.schema.json is authored in fullsend-ai/agents and is not -// vendored here, so the checks below mirror the constraints sanitization can -// break in a review result: the enums and patterns of the structural fields, -// additionalProperties false, and the required members. Update them when the -// schema's enums change. -var ( - reviewResultActions = []string{"approve", "request-changes", "comment", "reject", "failure"} - reviewResultSeverities = []string{"critical", "high", "medium", "low", "info"} - reviewResultCategories = []string{ - "logic-error", "nil-deref", "off-by-one", "edge-case", "api-contract", "missing-test", - "test-inadequate", "pattern-violation", "test-weakened", "test-removed", "mock-loosened", - "assertion-weakened", "coverage-reduced", "test-poisoning", "split-payload", "stale-reference", - "auth-bypass", "rbac-violation", "data-exposure", "privilege-escalation", "injection-vuln", - "sandbox-escape", "xss", "ssrf", "insecure-deserialization", "prompt-injection", - "unicode-steganography", "bidi-override", "homoglyph-attack", "instruction-smuggling", "fail-open", - "permission-expansion", "permission-reduction", "role-escalation", "workflow-permission", - "secret-exposure", "scope-exceeded", "tier-mismatch", "unauthorized-change", "scope-creep", - "missing-authorization", "misleading-label", "design-direction", "complexity-ratio", - "misplaced-abstraction", "architectural-conflict", "design-smell", "over-engineering", - "under-engineering", "scope-bundling", "naming-convention", "error-handling-idiom", "api-shape", - "code-organization", "doc-style", "pattern-inconsistency", "stale-doc", "missing-doc", - "incorrect-doc", "incomplete-doc", "breaking-api", "breaking-schema", "breaking-config", - "breaking-cli", "missing-deprecation", "missing-version-bump", "backward-incompatible", - "uxd-evaluate-code-heuristics", "protected-path", "provenance-warning", - "scope-authorization-implicit", "sub-agent-failure", +// reviewResultSchemaPath is a pinned copy of the schema authored in +// fullsend-ai/agents (schemas/review-result.schema.json, commit +// 2a41318da40a0e5d24644225650d4718db69bee7). Vendoring it ties these tests to the +// real constraints sanitization can break — the enums and patterns of the +// structural fields, additionalProperties false, and the required members — +// instead of a hand-maintained mirror that silently drifts when the upstream +// enum changes. Re-vendor and update the commit when the upstream schema changes. +const reviewResultSchemaPath = "testdata/review-result.schema.json" + +// reviewResultSchema is the subset of the vendored schema the checks below use. +type reviewResultSchema struct { + topLevel map[string]bool + findingMembers map[string]bool + actions []string + severities []string + categories []string +} + +// loadReviewResultSchema reads the pinned schema and extracts the constraints +// from it, so the test cannot accept a category or member the real harness would +// reject. +func loadReviewResultSchema(t *testing.T) reviewResultSchema { + t.Helper() + raw, err := os.ReadFile(reviewResultSchemaPath) + require.NoError(t, err, "the pinned review-result schema must be readable") + + var doc struct { + Properties map[string]json.RawMessage `json:"properties"` + Defs struct { + Finding struct { + Properties map[string]struct { + Enum []string `json:"enum"` + } `json:"properties"` + } `json:"finding"` + } `json:"$defs"` } -) + require.NoError(t, json.Unmarshal(raw, &doc), "the pinned review-result schema must decode") + + schema := reviewResultSchema{topLevel: map[string]bool{}, findingMembers: map[string]bool{}} + for key := range doc.Properties { + schema.topLevel[key] = true + } + for key := range doc.Defs.Finding.Properties { + schema.findingMembers[key] = true + } + + var action struct { + Enum []string `json:"enum"` + } + require.NoError(t, json.Unmarshal(doc.Properties["action"], &action)) + schema.actions = action.Enum + + findingProps := doc.Defs.Finding.Properties + schema.severities = findingProps["severity"].Enum + schema.categories = findingProps["category"].Enum + require.NotEmpty(t, schema.actions, "action enum must be present in the schema") + require.NotEmpty(t, schema.severities, "severity enum must be present in the schema") + require.NotEmpty(t, schema.categories, "category enum must be present in the schema") + return schema +} // assertReviewResultSchemaValid checks doc against the review-result schema // constraints sanitization can break. A review the harness rejects is not posted, @@ -1546,22 +1591,18 @@ var ( // satisfy these. func assertReviewResultSchemaValid(t *testing.T, doc []byte) { t.Helper() + schema := loadReviewResultSchema(t) var result map[string]json.RawMessage require.NoError(t, json.Unmarshal(doc, &result), "sanitized review must decode: %s", doc) - topLevel := map[string]bool{ - "action": true, "pr_number": true, "repo": true, "head_sha": true, "body": true, - "findings": true, "reason": true, "dispositions": true, "label_actions": true, - "risk_assessment": true, "risk_gated": true, - } for key := range result { - assert.True(t, topLevel[key], "unexpected top-level member %q", key) + assert.True(t, schema.topLevel[key], "unexpected top-level member %q", key) } var action string require.NoError(t, json.Unmarshal(result["action"], &action), "action is required") - assert.Contains(t, reviewResultActions, action, "action must be one of the schema enums") + assert.Contains(t, schema.actions, action, "action must be one of the schema enums") var repo string require.NoError(t, json.Unmarshal(result["repo"], &repo), "repo is required") @@ -1588,21 +1629,17 @@ func assertReviewResultSchemaValid(t *testing.T, doc []byte) { require.NoError(t, json.Unmarshal(rawFindings, &findings), "findings must be an array of objects") require.NotEmpty(t, findings, "findings must not be empty") - allowedFinding := map[string]bool{ - "severity": true, "category": true, "file": true, "line": true, "description": true, - "remediation": true, "actionable": true, "id": true, "dimension": true, - } for i, finding := range findings { for key := range finding { - assert.True(t, allowedFinding[key], "finding %d has unexpected member %q", i, key) + assert.True(t, schema.findingMembers[key], "finding %d has unexpected member %q", i, key) } var severity, category, file, description string require.NoError(t, json.Unmarshal(finding["severity"], &severity), "finding %d requires severity", i) require.NoError(t, json.Unmarshal(finding["category"], &category), "finding %d requires category", i) require.NoError(t, json.Unmarshal(finding["file"], &file), "finding %d requires file", i) require.NoError(t, json.Unmarshal(finding["description"], &description), "finding %d requires description", i) - assert.Contains(t, reviewResultSeverities, severity, "finding %d severity must be one of the schema enums", i) - assert.Contains(t, reviewResultCategories, category, "finding %d category must be one of the schema enums", i) + assert.Contains(t, schema.severities, severity, "finding %d severity must be one of the schema enums", i) + assert.Contains(t, schema.categories, category, "finding %d category must be one of the schema enums", i) assert.NotEmpty(t, file, "finding %d file must be at least one character", i) assert.NotEmpty(t, description, "finding %d description must be at least one character", i) } @@ -1639,3 +1676,139 @@ func TestOutputRemoval_NoPlainTextReason(t *testing.T) { assert.False(t, removed, "the removed plain-text marker must not be recognized") assert.Empty(t, reason) } + +// TestSanitizeJSONDocument_NormalizedSensitiveKeyMasksValue pins that a +// sensitive key obfuscated with a zero-width or fullwidth character is still +// recognized after sanitizeJSONKey writes its normalized spelling. Deciding +// sensitivity on the original key produced an explicit "password" field with an +// untouched opaque value, and the whole-value rescan does not apply json_field +// (#5705). +func TestSanitizeJSONDocument_NormalizedSensitiveKeyMasksValue(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"pass\u200bword":"opaque-value-12345","password":"another-opaque-1"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "opaque-value-12345", "a normalized sensitive key must mask its value") + assert.NotContains(t, string(out), "another-opaque-1", "a compatibility-obfuscated sensitive key must mask its value") + assert.Contains(t, string(out), `"password":`, "the normalized key is written") +} + +// TestSanitizeJSONLines_NormalizedSensitiveKeyMasksValue is the JSONL half: a +// record whose sensitive key is obfuscated must still mask its value. +func TestSanitizeJSONLines_NormalizedSensitiveKeyMasksValue(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"pass\\u200bword\":\"opaque-value-12345\"}\n" + + "{\"event\":\"clean\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "opaque-value-12345") + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 2, "record count must not change") + assert.Equal(t, `{"event":"clean"}`, lines[1], "a clean record must survive") +} + +// TestSanitizeJSONDocument_AuthorPathExemption pins that the structural path +// honours the #9944 exemption the text scan applies: an "author" member holding a +// codex agent path is not a credential, even though "author" contains "auth". +func TestSanitizeJSONDocument_AuthorPathExemption(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"author":"/root/agent_one/child","messages":[{"author":"/root/agent_one/child"}]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + assert.Empty(t, findings, "a codex agent path under author is exempt") + assert.Equal(t, string(doc), string(out), "an exempt document must be returned unchanged") +} + +// TestSanitizeJSONLines_AuthorPathExemption is the JSONL half of the #9944 +// exemption: a codex transcript record is a JSON document and takes the +// structural path. +func TestSanitizeJSONLines_AuthorPathExemption(t *testing.T) { + p := OutputPipeline() + content := []byte("{\"author\":\"/root/agent_one/child\"}\n" + + "{\"author\":\"/root/agent_two/child\"}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + assert.Empty(t, findings, "codex agent paths under author are exempt") + assert.Equal(t, string(content), string(out), "an exempt stream must be returned unchanged") +} + +// TestSanitizeJSONDocument_MaskShapedRealSecretStillMasked pins that a real short +// credential that happens to look like a mask placeholder is still masked when it +// is the original value. isAlreadyMasked is only trusted for a value this scan +// rewrote; otherwise an eight-character password ending in "..." and a backslash +// was written back unchanged (#5705). +func TestSanitizeJSONDocument_MaskShapedRealSecretStillMasked(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"password":"abcd...\\"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "abcd...", "a real secret shaped like a placeholder must still be masked") +} + +// TestSanitizeJSONDocument_BodyChunksSplitAcrossObjectKeysMasked pins the +// regression a reviewer found: a PEM body split into short chunks stored in +// separate object members lost its markers but kept every chunk, because each +// intervening key flushed the joined-run test. Object keys are structure and never +// join the run, but they must not break it either (#5705). +func TestSanitizeJSONDocument_BodyChunksSplitAcrossObjectKeysMasked(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + doc := []byte(`{"` + begin + `":"MIIEowIB","k1":"AAKCAQEA","k2":"x9Kq2Lm","` + end + `":"tail"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + for _, chunk := range []string{"MIIEowIB", "AAKCAQEA", "x9Kq2Lm"} { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } + assert.NotContains(t, string(out), "BEGIN RSA") + assert.NotContains(t, string(out), "END RSA") +} + +// TestSanitizeJSONLines_BodyChunksSplitAcrossObjectKeysCovered is the JSONL half: +// a middle record whose body chunks are stored in separate object members must be +// replaced once the chunks are joined across the intervening keys. +func TestSanitizeJSONLines_BodyChunksSplitAcrossObjectKeysCovered(t *testing.T) { + p := OutputPipeline() + begin := pemBegin + end := pemEnd + content := []byte( + "{\"" + begin + "\":1}\n" + + "{\"a\":\"MIIEowIB\",\"b\":\"AAKCAQEA\",\"c\":\"x9Kq2Lm\"}\n" + + "{\"" + end + "\":2}\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + for _, chunk := range []string{"MIIEowIB", "AAKCAQEA", "x9Kq2Lm"} { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + assert.Contains(t, line, "output removed") + } +} + +// The error return of SanitizeJSONDocument and SanitizeJSONLines is only +// reachable on a decoder limit after IsJSONDocument has accepted the bytes, and +// no input produces one: json.Valid and the token decoder share the same limits, +// so a document the decoder rejects is rejected before the structural path and +// falls back to the text scan. The wrap text ("could not sanitize JSON document" +// / "could not sanitize JSONL record") is therefore pinned at the CLI layer by +// TestScanOutputFiles_SanitizerErrorContainsFileAndContinues, which injects the +// error through the sanitizer parameter rather than depending on a natural +// trigger. diff --git a/internal/security/redactor.go b/internal/security/redactor.go index 9c51170251..082731e0c6 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -312,6 +312,13 @@ func isExemptJSONField(text string, matchStart, matchEnd int, secret string) boo } // Mask returns a redacted representation of a secret value. +// +// The returned text is safe to splice into a JSON or YAML string value, but not +// into arbitrary byte ranges: it keeps the first four bytes unless they contain +// an escape or a quote delimiter, in which case it returns "***". Callers that +// write it back must place it inside a string literal (writeJSONString does this +// for the structural path); a caller that rebuilds raw framing must re-escape +// the surrounding text itself. func Mask(value string) string { if len(value) < 10 { return "***" diff --git a/internal/security/testdata/review-result.schema.json b/internal/security/testdata/review-result.schema.json new file mode 100644 index 0000000000..2a41318da4 --- /dev/null +++ b/internal/security/testdata/review-result.schema.json @@ -0,0 +1,208 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "review-result.schema.json", + "title": "Review Agent Result", + "description": "Structured output from the review agent, validated by the harness before the post-script runs (ADR 0022).", + "type": "object", + "additionalProperties": false, + "required": ["action", "pr_number", "repo"], + "properties": { + "action": { + "type": "string", + "enum": ["approve", "request-changes", "comment", "reject", "failure"] + }, + "pr_number": { "type": "integer", "minimum": 1 }, + "repo": { "type": "string", "pattern": "^[a-zA-Z0-9._-]+(/[a-zA-Z0-9._-]+)+$" }, + "head_sha": { "type": "string", "pattern": "^[0-9a-fA-F]{40}$|^[0-9a-fA-F]{64}$" }, + "body": { "type": "string", "minLength": 1 }, + "findings": { + "type": "array", + "items": { "$ref": "#/$defs/finding" }, + "minItems": 1 + }, + "reason": { + "type": "string", + "enum": ["tool-failure", "missing-context", "ambiguous-findings", "token-limit", "time-budget"] + }, + "dispositions": { + "type": "array", + "description": "One entry for every open finding id from the prior projection (status absent, open, or reclassified). Ids already resolved or dismissed by a human are closed and must not be answered. A reclassified entry needs a finding with the same id in findings; a dismissed_by_human entry is accepted only when the post-script verifies a resolved review thread from an eligible reviewer, and never for a high or critical finding. Omit on a first review.", + "items": { "$ref": "#/$defs/disposition" } + }, + "label_actions": { + "$ref": "#/$defs/label_actions" + }, + "risk_assessment": { + "description": "Score and level must be consistent: 1=low, 2=moderate, 3=elevated, 4=high, 5=critical.", + "type": "object", + "required": ["score", "level", "rationale"], + "properties": { + "score": { "type": "integer", "minimum": 1, "maximum": 5 }, + "level": { + "type": "string", + "enum": ["low", "moderate", "elevated", "high", "critical"] + }, + "tier1_signals": { + "type": "array", + "items": { "$ref": "#/$defs/risk_signal" } + }, + "tier2_signals": { + "type": "array", + "items": { "$ref": "#/$defs/risk_signal" } + }, + "tier3_signals": { + "type": "array", + "items": { "$ref": "#/$defs/risk_signal" } + }, + "rationale": { "type": "string", "minLength": 1 }, + "degraded": { "type": "string", "minLength": 1 } + }, + "additionalProperties": false, + "allOf": [ + { "if": { "properties": { "score": { "const": 1 } } }, "then": { "properties": { "level": { "const": "low" } } } }, + { "if": { "properties": { "score": { "const": 2 } } }, "then": { "properties": { "level": { "const": "moderate" } } } }, + { "if": { "properties": { "score": { "const": 3 } } }, "then": { "properties": { "level": { "const": "elevated" } } } }, + { "if": { "properties": { "score": { "const": 4 } } }, "then": { "properties": { "level": { "const": "high" } } } }, + { "if": { "properties": { "score": { "const": 5 } } }, "then": { "properties": { "level": { "const": "critical" } } } } + ] + }, + "risk_gated": { + "type": "boolean", + "description": "Set by post-processing when a risk assessment downgrades the verdict. Not present in agent output — added by the harness post-script." + } + }, + "allOf": [ + { + "if": { "properties": { "action": { "const": "approve" } }, "required": ["action"] }, + "then": { "required": ["body", "head_sha"] } + }, + { + "if": { "properties": { "action": { "const": "request-changes" } }, "required": ["action"] }, + "then": { "required": ["body", "head_sha", "findings"] } + }, + { + "if": { "properties": { "action": { "const": "comment" } }, "required": ["action"] }, + "then": { "required": ["body", "head_sha"] } + }, + { + "if": { "properties": { "action": { "const": "reject" } }, "required": ["action"] }, + "then": { "required": ["body", "head_sha", "findings"] } + }, + { + "if": { "properties": { "action": { "const": "failure" } }, "required": ["action"] }, + "then": { "required": ["reason"] } + }, + { + "if": { + "properties": { "action": { "const": "approve" } }, + "required": ["action"] + }, + "then": { + "not": { + "properties": { + "findings": { + "contains": { + "properties": { "category": { "const": "protected-path" } }, + "required": ["category"] + } + } + }, + "required": ["findings"] + } + } + } + ], + "$defs": { + "finding": { + "type": "object", + "required": ["severity", "category", "file", "description"], + "properties": { + "severity": { "type": "string", "enum": ["critical", "high", "medium", "low", "info"] }, + "category": { + "type": "string", + "description": "Canonical dimension categories (the dimension table in skills/pr-review/references/re-review.md, mirrored by allowed_category in pre-review and post-review) plus the non-dimensional categories. Keep all copies in sync.", + "enum": [ + "logic-error", "nil-deref", "off-by-one", "edge-case", "api-contract", "missing-test", "test-inadequate", "pattern-violation", "test-weakened", "test-removed", "mock-loosened", "assertion-weakened", "coverage-reduced", "test-poisoning", "split-payload", "stale-reference", + "auth-bypass", "rbac-violation", "data-exposure", "privilege-escalation", "injection-vuln", "sandbox-escape", "xss", "ssrf", "insecure-deserialization", "prompt-injection", "unicode-steganography", "bidi-override", "homoglyph-attack", "instruction-smuggling", "fail-open", "permission-expansion", "permission-reduction", "role-escalation", "workflow-permission", "secret-exposure", + "scope-exceeded", "tier-mismatch", "unauthorized-change", "scope-creep", "missing-authorization", "misleading-label", "design-direction", "complexity-ratio", "misplaced-abstraction", "architectural-conflict", "design-smell", "over-engineering", "under-engineering", "scope-bundling", + "naming-convention", "error-handling-idiom", "api-shape", "code-organization", "doc-style", "pattern-inconsistency", + "stale-doc", "missing-doc", "incorrect-doc", "incomplete-doc", + "breaking-api", "breaking-schema", "breaking-config", "breaking-cli", "missing-deprecation", "missing-version-bump", "backward-incompatible", + "uxd-evaluate-code-heuristics", + "protected-path", "provenance-warning", "scope-authorization-implicit", "sub-agent-failure" + ] + }, + "file": { "type": "string", "minLength": 1 }, + "line": { "type": "integer", "minimum": 1 }, + "description": { "type": "string", "minLength": 1 }, + "remediation": { "type": "string" }, + "actionable": { + "type": "boolean", + "description": "When true with a non-empty remediation, routes the verdict to request-changes so the fix agent can address the finding automatically." + }, + "id": { + "type": "string", + "pattern": "^f_[a-zA-Z0-9]+$", + "description": "Stable id copied from the prior projection. Omit on a new finding; the post-script assigns f_ plus random hex. Do not derive it from the file, line, or text." + }, + "dimension": { + "type": "string", + "description": "Name of the pr-review persona that produced the finding. Orchestrator-only findings omit it." + } + }, + "additionalProperties": false + }, + "disposition": { + "type": "object", + "required": ["id", "status", "rationale", "evidence"], + "properties": { + "id": { "type": "string", "pattern": "^f_[a-zA-Z0-9]+$" }, + "status": { + "type": "string", + "enum": ["open", "resolved_by_change", "reclassified", "dismissed_by_human"] + }, + "rationale": { "type": "string", "minLength": 1 }, + "evidence": { + "type": "string", + "description": "Code change or human resolution that supports the status. Empty only for open." + } + }, + "additionalProperties": false + }, + "label_actions": { + "type": "object", + "required": ["reason", "actions"], + "properties": { + "reason": { + "type": "string", + "minLength": 1, + "description": "Single sentence explaining why these labels are being applied or removed" + }, + "actions": { + "type": "array", + "minItems": 1, + "maxItems": 20, + "items": { + "type": "object", + "required": ["action", "label"], + "properties": { + "action": { "type": "string", "enum": ["add", "remove"] }, + "label": { "type": "string", "minLength": 1, "pattern": "^[a-zA-Z0-9._/: +-]+$" } + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "risk_signal": { + "type": "object", + "required": ["dimension", "value"], + "properties": { + "dimension": { "type": "string", "minLength": 1 }, + "value": { "type": "string", "minLength": 1 } + }, + "additionalProperties": false + } + } +} From 874468c3ffacaae0a8ebab0c368ce9a270c1614b Mon Sep 17 00:00:00 2001 From: anevans Date: Wed, 2 Dec 2026 14:05:03 -0500 Subject: [PATCH 45/51] fix(#5705): skip the post-script when the scan is not the only failure postScriptGate treated any joined output-scan failure as grounds to post the agent's result whenever the result file survived the scan. Because step 9f joins the scan error with the run's terminal outcome and the audit-chain failure, a timed-out run, a run with a broken audit chain, and one whose validation loop passed but whose transcript reported an error all posted their result instead of skipping. Keep the causes apart in the run error instead of flattening them into one join: collectPostScanSecurityArtifacts returns a postScanArtifactsError and postScanRunError builds a postScanError holding the terminal, scan and chain causes. postScriptGate now allows the scan-only path only when nothing but the scan (and optionally a failed agent) failed the run and the transcript override is unset. Add TestPostScriptGate cases for chain+scan, timeout+scan, override+scan and agent+chain+scan, and update the runtime docs. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 14 ++- internal/cli/run.go | 112 ++++++++++++++++++-- internal/cli/run_test.go | 62 ++++++++++- 3 files changed, 170 insertions(+), 18 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 36a2b3b84b..0f002b8db2 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -757,11 +757,15 @@ rewrites today; applying the level to the rest is tracked in A failed scan fails the run but does not silence the agent's own result. The post-script runs after the scan, so when the run failed with a scan error the -gate skips it — unless the result file the harness names (`agent-result.json` -by default) survived the scan and still holds a JSON object. Then the -post-script runs, posts the result, and the run still fails, so one unreadable -or unwritable file somewhere else under the run directory cannot turn a -completed report into silence. A result file the scan replaced with a +gate skips it — unless that scan failure is the run's only failure and the result +file the harness names (`agent-result.json` by default) survived the scan and +still holds a JSON object. Then the post-script runs, posts the result, and the +run still fails, so one unreadable or unwritable file somewhere else under the +run directory cannot turn a completed report into silence. A run that also timed +out, broke its audit chain or reported a transcript error keeps that cause's +outcome: the scan does not turn it into a post-script run, and each cause is kept +separate in the run error (`postScanError`) rather than flattened into one join, +so the gate can tell a scan-only failure from a joined one. A result file the scan replaced with a fail-closed marker does not count: the marker is valid JSON, but it is not the agent's result, and posting it would report a removal as the review. Neither does a result file the scan failed *on*: when its write or sanitization failed and the diff --git a/internal/cli/run.go b/internal/cli/run.go index 56763469fd..ba6ef2410c 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -4393,10 +4393,66 @@ func runTerminalError(hasLoop, validationPassed, timedOut bool, exitCode int, ex // the post-agent output scan and the sandbox audit collection. The scan failure // must not replace an agent failure: the post-script gate keys off // agentFailedError to run the post-script with FULLSEND_AGENT_EXIT_CODE set, and -// the run error has to name every cause (#5705). errors.Join keeps each cause -// reachable through errors.As even when the terminal outcome is nil. -func postScanRunError(terminalErr, scanErr error) error { - return errors.Join(terminalErr, scanErr) +// the run error has to name every cause (#5705). Each cause also stays +// identifiable, so postScriptGate can tell a scan-only failure, which may still +// post the result the scan left intact, from one joined with a timeout or a +// broken audit chain, which must skip. +func postScanRunError(terminalErr, artifactsErr error) error { + e := &postScanError{terminal: terminalErr} + var artifacts *postScanArtifactsError + if errors.As(artifactsErr, &artifacts) { + e.scan, e.chain = artifacts.scan, artifacts.chain + } else { + e.scan = artifactsErr + } + return e +} + +// postScanError is the run error once the post-agent scan has run. It keeps the +// run's terminal outcome, the output-scan failure and the audit-chain failure +// apart instead of flattening them into one join, because the post-script gate +// treats a scan-only failure differently from a run that also timed out or broke +// its audit chain (#5705). Every cause stays reachable through errors.As. +type postScanError struct { + terminal error + scan error + chain error +} + +func (e *postScanError) Error() string { + return errors.Join(e.terminal, e.scan, e.chain).Error() +} + +func (e *postScanError) Unwrap() []error { + errs := make([]error, 0, 3) + for _, err := range []error{e.terminal, e.scan, e.chain} { + if err != nil { + errs = append(errs, err) + } + } + return errs +} + +// postScanArtifactsError is what collectPostScanSecurityArtifacts returns: the +// output-scan failure and the audit-chain failure kept apart so postScanRunError +// can preserve the distinction (#5705). +type postScanArtifactsError struct { + scan error + chain error +} + +func (e *postScanArtifactsError) Error() string { + return errors.Join(e.scan, e.chain).Error() +} + +func (e *postScanArtifactsError) Unwrap() []error { + errs := make([]error, 0, 2) + for _, err := range []error{e.scan, e.chain} { + if err != nil { + errs = append(errs, err) + } + } + return errs } // agentFailedError ends a run without a validation_loop whose agent failed @@ -4421,8 +4477,9 @@ type postScriptDecision struct { // With a validation_loop it needs a validated result (ADR 0022). Without one // it runs after a successful agent, after a failed agent only when the agent // left a result file that parses (#8305), and after a failed output scan only -// when that scan left a result file that parses, so the result is still -// reported while the run fails. --no-post-script is checked by the caller. +// when that scan is the run's only failure and it left a result file that +// parses, so the result is still reported while the run fails. --no-post-script +// is checked by the caller. func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverride bool, runErr error, outputDir string) postScriptDecision { if h.ValidationLoop != nil && !validationPassed { return postScriptDecision{message: "Skipping post-script: validation did not pass"} @@ -4440,8 +4497,16 @@ func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverrid return postScriptDecision{message: "Skipping post-script: the output scan could not redact the result file"} } } + // A scan-only failure may still report the result it left intact, but a run + // that also timed out, broke its audit chain or reported a transcript error + // keeps that cause's outcome: the scan must not turn it into a post-script + // run (#5705). + scanOnly := scanFailed && scanOnlyRunError(runErr) var agentErr *agentFailedError if errors.As(runErr, &agentErr) { + if scanFailed && !scanOnly { + return postScriptDecision{message: "Skipping post-script: agent run failed"} + } resultFile, ok := agentResultFile(h, outputDir) if !ok { return postScriptDecision{message: fmt.Sprintf("Skipping post-script: agent failed with exit code %d and left no result file that parses", agentErr.exitCode)} @@ -4457,7 +4522,7 @@ func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverrid // completed report into silence: when the agent's own result file survived // the scan and still parses, the post-script runs and the run still fails // (#5705). - if scanFailed { + if scanOnly && !transcriptErrorOverride { resultFile, ok := agentResultFile(h, outputDir) if !ok { return postScriptDecision{message: "Skipping post-script: the output scan failed and left no result file that parses"} @@ -4476,6 +4541,34 @@ func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverrid return postScriptDecision{run: true} } +// scanOnlyRunError reports whether the output scan is the run's only failure, or +// shares it with nothing worse than a failed agent, which the gate handles on its +// own. A timeout, a broken audit chain or any other joined cause makes a scan +// failure ineligible to run the post-script: on main a broken chain returned the +// chain error alone and skipped it (#5705). +func scanOnlyRunError(runErr error) bool { + var postScan *postScanError + if errors.As(runErr, &postScan) { + if postScan.chain != nil { + return false + } + if postScan.terminal == nil { + return true + } + var agentErr *agentFailedError + return errors.As(postScan.terminal, &agentErr) + } + // A run error that did not come through postScanRunError holds no separate + // causes to inspect, so it counts as scan-only only when it is a single + // error chain: a bare scan failure or one wrapped for the quiet wording. + var scanErr *outputScanError + if !errors.As(runErr, &scanErr) { + return false + } + _, joined := runErr.(interface{ Unwrap() []error }) + return !joined +} + // agentResultMaxBytes caps how much of the sandbox-written result file the // runner reads; a larger file counts as no result. const agentResultMaxBytes = 4 << 20 @@ -7734,7 +7827,10 @@ func collectPostScanSecurityArtifacts(runDir, sandboxName string, printer *ui.Pr // of the agent-chosen file names (outputScanError, ADR 0163). scanErr = fmt.Errorf("%s: %w", postAgentScanFailurePrefix, scanErr) } - return errors.Join(scanErr, chainErr) + if scanErr == nil && chainErr == nil { + return nil + } + return &postScanArtifactsError{scan: scanErr, chain: chainErr} } func injectTraceID(sandboxName, traceID string) error { diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index e1f77ba680..5b158aa742 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -5571,16 +5571,68 @@ func TestPostScriptGate(t *testing.T) { t.Run("no loop, output scan failed, valid result", func(t *testing.T) { t.Parallel() // collectPostScanSecurityArtifacts wraps the scan error, so the gate - // must find it through the wrap and the join with an audit-chain error. - scanErr := fmt.Errorf("%s: %w", postAgentScanFailurePrefix, - &outputScanError{err: errors.New("could not write sanitized notes.md: no space left on device"), files: 1}) - runErr := errors.Join(scanErr, errors.New("audit log integrity check failed: hash mismatch")) + // must find it through the wrap and the post-scan join. + scanErr := &outputScanError{err: errors.New("could not write sanitized notes.md: no space left on device"), files: 1} + var buf bytes.Buffer + artifactsErr := collectPostScanSecurityArtifacts(t.TempDir(), "sandbox", ui.New(&buf), "", + scanErr, func(_, _, _ string) error { return errors.New("no findings") }) + runErr := postScanRunError(nil, artifactsErr) got := postScriptGate(noLoop, false, false, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) - assert.True(t, got.run, "an intact result must still be posted when the scan fails") + assert.True(t, got.run, "an intact result must still be posted when the scan is the only failure") assert.Zero(t, got.agentExitCode) assert.Contains(t, got.message, "agent-result.json") assert.Contains(t, got.message, "the run still fails") }) + t.Run("no loop, output scan and audit chain both failed", func(t *testing.T) { + t.Parallel() + // A broken chain skipped the post-script on main; a scan failure joined + // with it must not turn that into a posted result (#5705). + scanErr := fmt.Errorf("%s: %w", postAgentScanFailurePrefix, + &outputScanError{err: errors.New("could not write sanitized notes.md"), files: 1}) + runErr := postScanRunError(nil, &postScanArtifactsError{ + scan: scanErr, + chain: errors.New("audit log integrity check failed: hash mismatch"), + }) + got := postScriptGate(noLoop, false, false, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.False(t, got.run, "a broken audit chain must still skip the post-script") + assert.Contains(t, got.message, "agent run failed") + }) + t.Run("no loop, timeout and scan failed", func(t *testing.T) { + t.Parallel() + // A timeout alone skips with "agent run failed"; the scan must not + // override it just because an intact result file exists (#5705). + timedOut := runTerminalError(false, false, true, -1, "", 1, time.Hour, time.Hour) + scanErr := fmt.Errorf("%s: %w", postAgentScanFailurePrefix, + &outputScanError{err: errors.New("could not read notes.md"), files: 1}) + runErr := postScanRunError(timedOut, &postScanArtifactsError{scan: scanErr}) + got := postScriptGate(noLoop, false, false, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.False(t, got.run) + assert.Contains(t, got.message, "agent run failed") + }) + t.Run("no loop, transcript error override and scan failed", func(t *testing.T) { + t.Parallel() + // The transcript override alone skips the post-script; a scan failure + // joined with it must not post the result anyway (#5705). + scanErr := fmt.Errorf("%s: %w", postAgentScanFailurePrefix, + &outputScanError{err: errors.New("could not read notes.md"), files: 1}) + runErr := postScanRunError(nil, &postScanArtifactsError{scan: scanErr}) + got := postScriptGate(noLoop, false, true, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.False(t, got.run) + }) + t.Run("no loop, failed agent and broken audit chain", func(t *testing.T) { + t.Parallel() + // The agent-failure branch reports a result, but a joined chain failure + // still skips it the way it did on main (#5705). + scanErr := fmt.Errorf("%s: %w", postAgentScanFailurePrefix, + &outputScanError{err: errors.New("could not read notes.md"), files: 1}) + runErr := postScanRunError(agentFailed, &postScanArtifactsError{ + scan: scanErr, + chain: errors.New("audit log integrity check failed: hash mismatch"), + }) + got := postScriptGate(noLoop, false, false, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.False(t, got.run) + assert.Contains(t, got.message, "agent run failed") + }) t.Run("no loop, output scan failed, no result", func(t *testing.T) { t.Parallel() got := postScriptGate(noLoop, false, false, &outputScanError{err: errors.New("could not read notes.md"), files: 1}, t.TempDir()) From 5743d8ff125b9027155643e1659c93d6fdb56074 Mon Sep 17 00:00:00 2001 From: anevans Date: Wed, 2 Dec 2026 14:54:42 -0500 Subject: [PATCH 46/51] fix(#5705): keep schema fields readable and mask short PEM chunks A quoted BEGIN/END marker pair is not proof that the text between the members is key material, and two of the localization rules were wrong in opposite directions. The joined-run test accepted any concatenation of base64-only values, so a finding's severity, category and file joined into "criticalssrfMakefile" and were all masked. The review then failed schema validation and was dropped, which is the outcome this change exists to prevent. A joined run now has to carry a digit or a run of adjacent capitals, which base64 of binary key material does and concatenated schema words do not. The per-chunk length floor did the reverse: a body split into one- to three-character chunks was written back intact once the boundary markers were masked. Chunks join a run at any length, and the joined text decides. OutputRemoval trims whitespace but not the UTF-8 BOM that SanitizeJSONDocument restores on its fail-closed returns and that a replaced first JSONL record keeps, so a BOM-prefixed file or record that lost everything raised no ::error:: annotation and was not treated as removed. The comparison now strips the mark before matching. Tests: schema-preservation fixtures for the single-document and JSONL paths, short-chunk fixtures for both, a BOM case in TestOutputRemoval and TestOutputRecordRemovals, and a CLI test that a BOM-prefixed file replaced whole still raises the annotation. Signed-off-by: anevans --- docs/contributing/runtime-implementation.md | 24 +++-- internal/cli/scan_output_telemetry_test.go | 28 +++++ internal/security/jsonsanitize.go | 88 +++++++++++----- internal/security/jsonsanitize_test.go | 110 ++++++++++++++++++++ 4 files changed, 216 insertions(+), 34 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 0f002b8db2..86231bc7a5 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -682,19 +682,21 @@ masking free text and enum values, which loses the review, and keeping a fragmen too short to be recognized as key material. Because one member holds only one line of a body, the values between the boundary members are also decided on their joined text: consecutive base64-only values are concatenated, and if the result -looks like a body line — upper case, lower case and a base64-only character — -every value in that run is masked. That catches a body split into short or -digit-free chunks. An object key never joins the run — a key is structure, and +looks like a body line — upper case, lower case and a base64-only character, plus +a digit or a run of adjacent capitals — every value in that run is masked. That +catches a body split into short or digit-free chunks, while a run of schema values +such as `critical` + `ssrf` + `Makefile` reads as concatenated words and keeps its +content. An object key never joins the run — a key is structure, and letting one join a group that also holds body material renames required schema keys such as `severity` and `file` — but it does not break the run either: the values on either side of a key are still consecutive body chunks once the key names are ignored, so a body stored in separate object members is reconstructed -and masked. A value with punctuation or whitespace, or one shorter than four -characters, breaks the run: those are free text or a short token rather than a -body line. A hex-only value joined to base64 body material is masked with it; an -isolated hex-only run is kept, because a PEM body is base64 while a hex run is -more likely a commit SHA or a finding id. A single isolated fragment below the -floor, with no neighbour to join it to, is still kept. +and masked. A value with punctuation or whitespace breaks the run: those are free +text or a structural token rather than a body line, while a short base64-only +value joins it at any length. A hex-only value joined to base64 body material is +masked with it; an isolated hex-only run is kept, because a PEM body is base64 +while a hex run is more likely a commit SHA or a finding id. A single isolated +fragment below the floor, with no neighbour to join it to, is still kept. `.jsonl`/`.ndjson` files are sanitized one record at a time to preserve the record framing; a secret that spans records cannot be redacted without rewriting that framing, so only the records that carry it are replaced, and a @@ -730,7 +732,9 @@ as findings in `security/findings.jsonl`. Because a replaced file or record lose everything the agent wrote into it, and because the run still exits 0, the reason a marker states is also emitted as a `::error::` workflow command whenever the job sets `GITHUB_ACTIONS=true`: one line for a file replaced whole, and one per -distinct reason for a JSONL file whose records were replaced. GitHub Actions +distinct reason for a JSONL file whose records were replaced. A leading UTF-8 BOM +does not hide a marker: the comparison strips it, so a BOM-prefixed file or record +that lost everything is still reported as removed. GitHub Actions renders these as error annotations. Forgejo Actions also sets `GITHUB_ACTIONS=true`, so its runner writes the same lines, but Forgejo has no annotation view: the runner prints them in the step log and the exit status stays 0. diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 14d311c81a..9c7d39df7b 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -418,6 +418,34 @@ func TestScanOutputFiles_EmitsAnnotationWhenOutputIsRemoved(t *testing.T) { } } +// TestScanOutputFiles_EmitsAnnotationForBOMPrefixedRemoval pins that the UTF-8 +// BOM a replaced file keeps does not hide the loss. The mark is framing, not +// content, so a BOM-prefixed document that was replaced whole is still announced; +// before this the marker read as ordinary content and the run stayed silent +// (#5705). +func TestScanOutputFiles_EmitsAnnotationForBOMPrefixedRemoval(t *testing.T) { + const secret = `"v1","k2"` + security.ResetRuntimeSecretsForTest() + require.True(t, security.RegisterRuntimeSecret(secret)) + t.Cleanup(security.ResetRuntimeSecretsForTest) + t.Setenv("GITHUB_ACTIONS", "true") + + dir := t.TempDir() + path := filepath.Join(dir, "agent-result.json") + content := append([]byte("\ufeff"), []byte(`{"k1":"v1","k2":"v2"}`)...) + require.NoError(t, os.WriteFile(path, content, 0o644)) + + var output bytes.Buffer + require.NoError(t, scanOutputFiles(dir, "trace-id", "", ui.New(&output))) + + got, err := os.ReadFile(path) + require.NoError(t, err) + assert.True(t, bytes.HasPrefix(got, []byte("\ufeff")), "the encoding mark must survive: %q", got) + assert.True(t, json.Valid(bytes.TrimPrefix(got, []byte("\ufeff"))), "a replaced file must still be valid JSON: %s", got) + assert.NotContains(t, string(got), secret) + assert.Contains(t, output.String(), "::error::Output file replaced with a fail-closed marker") +} + func TestScanOutputFiles_QuietJSONFallbackDoesNotPrintPath(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "agent-chosen-secret-name.json") diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 20c79a2855..cd0e134fc2 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -68,8 +68,13 @@ var outputRemovalMarkers = []struct { // returns the reason it states. A replaced file loses the content the agent // wrote into it, so callers alert operators rather than let that loss pass // silently (#5705). +// +// A leading UTF-8 BOM is framing, not content. SanitizeJSONDocument restores the +// mark on its fail-closed returns and a replaced JSONL record keeps the mark its +// line carried, so the comparison strips it: otherwise a BOM-prefixed file or +// record that lost everything would read as ordinary content and raise no alert. func OutputRemoval(sanitized []byte) (string, bool) { - trimmed := string(bytes.TrimSpace(sanitized)) + trimmed := string(bytes.TrimSpace(bytes.TrimPrefix(bytes.TrimSpace(sanitized), utf8BOM))) for _, marker := range outputRemovalMarkers { if trimmed == marker.document { return marker.reason, true @@ -217,15 +222,11 @@ var privateKeyMaterialRe = regexp.MustCompile(`[A-Za-z0-9+/]{16,}=*`) // pemChunkCandidateRe matches a string value that could be one segment of a PEM // body: every byte is in the base64 alphabet. A value with whitespace, a hyphen, // a period or any other punctuation is free text or a structural token, so it -// breaks a run of segments rather than joining one. +// breaks a run of segments rather than joining one. Short segments are candidates +// too: a body can be split so that every member holds only a few characters, and +// the run is judged on its joined text rather than on any one segment. var pemChunkCandidateRe = regexp.MustCompile(`^[A-Za-z0-9+/]+=*$`) -// minPEMChunkLen is the shortest value treated as a candidate PEM body segment -// in a joined run. A one- to three-character value between markers is more -// likely a free-text note or a short token than a body line, so it breaks the -// run rather than dragging its neighbours into a mask. -const minPEMChunkLen = 4 - // jsonProvenance accumulates an order-preserving view of the decoded strings // in a document so a private-key block that spans members can be detected after // JSON decoding. The raw bytes are not usable for this: a member may encode a @@ -343,8 +344,10 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { // is short or digit-free; a per-member test then accepts none of them and writes // the body back after the markers are masked, where the written-bytes rescan can // no longer see the block (#5705). Consecutive candidate segments are therefore -// decided together. An object key never joins the run — a key is structure, and -// letting one into the joined text renames required schema keys (severity, +// decided together, whatever their individual length: a segment is a candidate +// when it is made only of base64 characters, and the joined run is what has to +// look like a body line. An object key never joins the run — a key is structure, +// and letting one into the joined text renames required schema keys (severity, // category, file) — but it does not break the run either: the values on either // side of a key are still consecutive body chunks once the key names are ignored, // so a body stored in separate object members is reconstructed and masked. A key @@ -385,7 +388,7 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { flush() continue } - if len(chunk) < minPEMChunkLen || !pemChunkCandidateRe.Match(chunk) { + if len(chunk) == 0 || !pemChunkCandidateRe.Match(chunk) { flush() continue } @@ -454,15 +457,27 @@ func pemBodyRun(run []byte) bool { // segments looks like PEM body material. It is the check maskSpanBody applies to // a body split across members: a chunk on its own may be shorter than the // material floor or carry no digit, but the joined body reconstructs both. It -// does not require a digit, because a single chunk can legitimately be digit-free -// and a body split so that every digit lands in another chunk would otherwise be -// written back. It still requires upper case, lower case and a base64-only -// character, which a hex SHA, a lowercase word, a path and free text do not have. +// still requires upper case, lower case and a base64-only character, which a hex +// SHA, a lowercase word, a path and free text do not have. +// +// A joined run is not automatically a body, though: consecutive schema values +// read as concatenated words — a finding's "critical", "ssrf" and "Makefile" join +// to "criticalssrfMakefile", which carries the case and base64 mix on its own. A +// body line is base64 of binary key material, so it scatters digits and runs of +// adjacent upper-case letters through the text, while the enum and path values +// the schema constrains are lowercase words with one leading capital at most. A +// digit anywhere in the run settles it; without one, the run must carry at least +// two adjacent upper-case letters to be body material. A body split so that every +// digit landed in a segment that broke the run, and that also has no adjacent +// capitals, is not recognized here; such a body is still caught member by member +// when a member is a whole body line (pemBodyRun), and the alternative — joining +// every value between quoted markers — masked required schema fields and lost the +// review (#5705). func pemBodyJoined(joined []byte) bool { if len(joined) < 16 { return false } - var upper, lower, base64Only bool + var upper, lower, digit, base64Only bool for _, b := range joined { switch { case b >= 'a' && b <= 'z': @@ -471,11 +486,35 @@ func pemBodyJoined(joined []byte) bool { case b >= 'A' && b <= 'Z': upper = true base64Only = base64Only || b > 'F' + case b >= '0' && b <= '9': + digit = true case b == '+' || b == '/' || b == '=': base64Only = true } } - return upper && lower && base64Only + if !upper || !lower || !base64Only { + return false + } + return digit || hasUpperRun(joined, 2) +} + +// hasUpperRun reports whether text contains min consecutive upper-case letters. +// Base64 of binary material produces those runs often; a concatenation of schema +// words ("critical", "ssrf", "Makefile") produces none, and free text does not +// reach the joined-run test because whitespace and punctuation break the run. +func hasUpperRun(text []byte, min int) bool { + run := 0 + for _, b := range text { + if b < 'A' || b > 'Z' { + run = 0 + continue + } + run++ + if run >= min { + return true + } + } + return false } // leafContaining returns the index of the leaf that fully contains [start, end), @@ -756,12 +795,13 @@ func (v *jsonLineView) spanningRecordPrivateKeys() ([]bool, []Finding) { // records when their leaves carry key material. It is the record-level counterpart // of maskSpanBody: consecutive candidate leaves are decided together, because a // body split so that every line is short or digit-free is only recognizable once -// the lines are joined. An object key never joins the run, since a key is -// structure rather than body, but it does not break the run either: a body stored -// in separate object members of one record is still reconstructed. A value with -// punctuation or whitespace breaks the run: those are structural tokens and free -// text, not body lines. A key whose own name is a body line carries key material, -// so its record is covered on its own. +// the lines are joined. A leaf joins a run at any length, since the joined text is +// what has to look like a body line. An object key never joins the run, since a key +// is structure rather than body, but it does not break the run either: a body +// stored in separate object members of one record is still reconstructed. A value +// with punctuation or whitespace breaks the run: those are structural tokens and +// free text, not body lines. A key whose own name is a body line carries key +// material, so its record is covered on its own. func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { first, last := hit[0], hit[len(hit)-1] var group []int @@ -804,7 +844,7 @@ func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { flush() continue } - if len(text) < minPEMChunkLen || !pemChunkCandidateRe.Match(text) { + if len(text) == 0 || !pemChunkCandidateRe.Match(text) { flush() continue } diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 1a20e2eeda..7b6517f511 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -271,6 +271,56 @@ func TestSanitizeJSONDocument_MarkerSplitAcrossMembersMasked(t *testing.T) { assert.NotContains(t, string(out), "PRIVATE KEY-----") } +// TestSanitizeJSONDocument_SchemaFieldsBetweenQuotedMarkersKept pins the other +// side of the joined-run rule: the values between a quoted header and footer are +// not body material just because they are consecutive. A finding's severity, +// category and file join into "criticalssrfMakefile", which carries the case and +// base64 mix a body line has, and masking them failed the review schema and lost +// the review — the outcome this change exists to prevent (#5705). +func TestSanitizeJSONDocument_SchemaFieldsBetweenQuotedMarkersKept(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"action":"comment","repo":"acme/widgets","pr_number":12,` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","body":"quotes a key",` + + `"findings":[` + + `{"severity":"high","category":"logic-error","file":"a.go","description":"quotes the ` + pemBegin + ` header"},` + + `{"severity":"critical","category":"ssrf","file":"Makefile","description":"quotes the ` + pemEnd + ` footer"}]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----", "the markers themselves are masked") + assert.Contains(t, string(out), `"severity":"critical"`, "a schema value is not body material") + assert.Contains(t, string(out), `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, string(out), `"file":"Makefile"`, "a schema value is not body material") + assertReviewResultSchemaValid(t, out) +} + +// TestSanitizeJSONDocument_ShortBodyChunksMasked pins that a body split into +// chunks shorter than the material floor is still masked. Each chunk is too short +// for the per-value test, so the run is decided on its joined text and every +// contributing chunk is covered; a length floor per chunk let the body survive +// once the boundary markers were masked (#5705). +func TestSanitizeJSONDocument_ShortBodyChunksMasked(t *testing.T) { + p := OutputPipeline() + chunks := []string{"MII", "Eow", "IB", "AAK", "CAQ", "EA"} + quoted := []string{`"` + pemBegin + `"`} + for _, chunk := range chunks { + quoted = append(quoted, `"`+chunk+`"`) + } + quoted = append(quoted, `"`+pemEnd+`"`) + doc := []byte(`{"lines":[` + strings.Join(quoted, ",") + `]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + for _, chunk := range chunks { + assert.NotContains(t, string(out), chunk, "a short body chunk must not survive") + } + assert.NotContains(t, string(out), "PRIVATE KEY-----") +} + // TestSanitizeJSONDocument_ChunkedBodyBetweenMarkersMasked pins the regression a // reviewer found: a body split across members into chunks that are each short, // digit-free, or hex-looking was written back after the boundary markers were @@ -680,6 +730,8 @@ func TestOutputRemoval(t *testing.T) { "invalid json": {failClosedInvalidJSON + "\n", "redaction would invalidate JSON", true}, "cross-record": {failClosedCrossRecordJSON, "a secret spanned multiple records", true}, "spans members": {failClosedSpansMembersJSON, "a private key block spans JSON framing", true}, + "bom prefixed": {"\ufeff" + failClosedSpansMembersJSON, "a private key block spans JSON framing", true}, + "bom and space": {"\ufeff " + failClosedInvalidJSON + "\r\n", "redaction would invalidate JSON", true}, "ordinary doc": {`{"error":"not a removal marker"}`, "", false}, "not json": {"plain prose", "", false}, "empty": {"", "", false}, @@ -708,6 +760,16 @@ func TestOutputRecordRemovals(t *testing.T) { assert.Empty(t, OutputRecordRemovals([]byte(`{"event":"clean"}`+"\n"))) } +// TestOutputRecordRemovals_BOMFirstRecord pins that a replaced first record keeps +// the BOM its line carried, and that the mark does not hide the loss: the record +// is still reported, so the operator alert is not skipped (#5705). +func TestOutputRecordRemovals_BOMFirstRecord(t *testing.T) { + stream := []byte("\ufeff" + failClosedCrossRecordJSON + "\n" + `{"event":"clean"}` + "\n") + assert.Equal(t, + []string{"a secret spanned multiple records"}, + OutputRecordRemovals(stream)) +} + // TestJSONProvenance_UnmappableBlock pins the defensive fallback: a block that no // recorded leaf range covers is reported as unmappable so the caller fails // closed instead of writing bytes that may still carry it. @@ -1777,6 +1839,54 @@ func TestSanitizeJSONDocument_BodyChunksSplitAcrossObjectKeysMasked(t *testing.T assert.NotContains(t, string(out), "END RSA") } +// TestSanitizeJSONLines_SchemaFieldsBetweenQuotedMarkersKept is the record-level +// half of the joined-run rule: a middle record whose values are schema fields +// joins into "criticalssrfMakefile" and must keep its content, so the review the +// transcript describes is not discarded (#5705). +func TestSanitizeJSONLines_SchemaFieldsBetweenQuotedMarkersKept(t *testing.T) { + p := OutputPipeline() + content := []byte( + `{"note":"quotes the ` + pemBegin + ` header"}` + "\n" + + `{"severity":"critical","category":"ssrf","file":"Makefile"}` + "\n" + + `{"note":"quotes the ` + pemEnd + ` footer"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + assert.Contains(t, lines[1], `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, lines[1], `"file":"Makefile"`, "a schema value is not body material") + assert.NotContains(t, lines[0], "PRIVATE KEY-----") + assert.NotContains(t, lines[2], "PRIVATE KEY-----") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "every record must stay valid JSON: %s", line) + } +} + +// TestSanitizeJSONLines_ShortBodyChunksCovered pins that a middle record holding +// a body in chunks shorter than the material floor is replaced, not written back +// with its body intact (#5705). +func TestSanitizeJSONLines_ShortBodyChunksCovered(t *testing.T) { + p := OutputPipeline() + content := []byte( + `{"note":"` + pemBegin + `"}` + "\n" + + `["MII","Eow","IB","AAK","CAQ","EA"]` + "\n" + + `{"note":"` + pemEnd + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + for _, chunk := range []string{"MII", "Eow", "IB", "AAK", "CAQ", "EA"} { + assert.NotContains(t, string(out), `"`+chunk+`"`, "a short body chunk must not survive") + } + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + } +} + // TestSanitizeJSONLines_BodyChunksSplitAcrossObjectKeysCovered is the JSONL half: // a middle record whose body chunks are stored in separate object members must be // replaced once the chunks are joined across the intervening keys. From abc24a18da1e72a7232570e5eb56c439c85bd014 Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 3 Dec 2026 05:34:32 -0500 Subject: [PATCH 47/51] fix(#5705): address remaining output sanitizer review findings Post-script gate: a broken audit chain joined with an agent failure no longer posts the result just because the output scan was clean. On main the chain error was the run error by itself and skipped the post-script, so the agent-failure branch must refuse it too. json_field: add the bounded double-quoted fallbacks the single-quoted branch already has, so a double-quoted value ending in a literal backslash and a value folded across physical lines are redacted again. PEM localization: a joined run is body material only when it carries a multi-letter upper-case run followed by lower case, so a trailing digit ("Makefile2") or an all-capitals word ("README") no longer masks schema-required review fields. ASCII whitespace inside a body chunk is line framing and is stripped before joining, so a body split into short chunks that each carry their newline is still masked. Also correct the pinned review-result schema commit to the real upstream commit. Signed-off-by: Andrew Evans Signed-off-by: anevans --- internal/cli/run.go | 27 +++++ internal/cli/run_test.go | 13 +++ internal/security/jsonsanitize.go | 132 ++++++++++++++++--------- internal/security/jsonsanitize_test.go | 120 ++++++++++++++++------ internal/security/redactor.go | 20 ++-- internal/security/scanner_test.go | 29 ++++++ 6 files changed, 258 insertions(+), 83 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index ba6ef2410c..791fc87aec 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -4507,6 +4507,13 @@ func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverrid if scanFailed && !scanOnly { return postScriptDecision{message: "Skipping post-script: agent run failed"} } + // A broken audit chain or any other terminal cause joined with the + // agent failure must skip the post-script even when the output scan was + // clean: on main that chain error was the run error by itself, so the + // result was never posted (#5705). + if postScanBlocksAgentFailure(runErr) { + return postScriptDecision{message: "Skipping post-script: agent run failed"} + } resultFile, ok := agentResultFile(h, outputDir) if !ok { return postScriptDecision{message: fmt.Sprintf("Skipping post-script: agent failed with exit code %d and left no result file that parses", agentErr.exitCode)} @@ -4541,6 +4548,26 @@ func postScriptGate(h *harness.Harness, validationPassed, transcriptErrorOverrid return postScriptDecision{run: true} } +// postScanBlocksAgentFailure reports whether a post-scan run error carries, next +// to an agent failure, a cause that must skip the post-script: a broken audit +// chain or any terminal cause other than the agent failure itself. A scan-only +// post-scan error around the agent failure does not block; postScriptGate handles +// that case itself so the intact result is still reported (#5705). +func postScanBlocksAgentFailure(runErr error) bool { + var postScan *postScanError + if !errors.As(runErr, &postScan) { + return false + } + if postScan.chain != nil { + return true + } + if postScan.terminal == nil { + return false + } + var agentErr *agentFailedError + return !errors.As(postScan.terminal, &agentErr) +} + // scanOnlyRunError reports whether the output scan is the run's only failure, or // shares it with nothing worse than a failed agent, which the gate handles on its // own. A timeout, a broken audit chain or any other joined cause makes a scan diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index 5b158aa742..c0be68e32f 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -5633,6 +5633,19 @@ func TestPostScriptGate(t *testing.T) { assert.False(t, got.run) assert.Contains(t, got.message, "agent run failed") }) + t.Run("no loop, failed agent and broken audit chain without a scan failure", func(t *testing.T) { + t.Parallel() + // The scan succeeded but the audit chain is broken. On main the chain + // error alone was the run error and skipped the post-script; the + // agent-failure branch must not post the result just because + // agent-result.json parses (#5705). + runErr := postScanRunError(agentFailed, &postScanArtifactsError{ + chain: errors.New("audit log integrity check failed: hash mismatch"), + }) + got := postScriptGate(noLoop, false, false, runErr, writeResult(t, "agent-result.json", `{"action":"approve"}`)) + assert.False(t, got.run, "a broken audit chain must skip the post-script even without a scan failure") + assert.Contains(t, got.message, "agent run failed") + }) t.Run("no loop, output scan failed, no result", func(t *testing.T) { t.Parallel() got := postScriptGate(noLoop, false, false, &outputScanError{err: errors.New("could not read notes.md"), files: 1}, t.TempDir()) diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index cd0e134fc2..c41e06f3af 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -220,13 +220,44 @@ var privateKeyMarkerRe = regexp.MustCompile(`-----BEGIN|-----END|PRIVATE KEY---- var privateKeyMaterialRe = regexp.MustCompile(`[A-Za-z0-9+/]{16,}=*`) // pemChunkCandidateRe matches a string value that could be one segment of a PEM -// body: every byte is in the base64 alphabet. A value with whitespace, a hyphen, -// a period or any other punctuation is free text or a structural token, so it -// breaks a run of segments rather than joining one. Short segments are candidates -// too: a body can be split so that every member holds only a few characters, and -// the run is judged on its joined text rather than on any one segment. +// body: every byte is in the base64 alphabet. A value with a hyphen, a period or +// any other punctuation is free text or a structural token, so it breaks a run of +// segments rather than joining one. Short segments are candidates too: a body can +// be split so that every member holds only a few characters, and the run is +// judged on its joined text rather than on any one segment. var pemChunkCandidateRe = regexp.MustCompile(`^[A-Za-z0-9+/]+=*$`) +// pemChunkMaterial returns the base64 material of a candidate body segment, or +// nil when the segment cannot be one. +// +// A PEM body line is 64 columns wide, and an agent can store the line together +// with the newline that ended it inside the decoded string value, so whitespace +// inside a segment is framing rather than body. It is stripped before the +// segment is tested and joined, and must not break a run: otherwise a body split +// into short chunks that each carry a newline slipped through as neither a +// whole-line match nor a joined run, and the body was written back after the +// markers were masked (#5705). Anything outside the base64 alphabet and ASCII +// whitespace keeps the segment out of the run. +func pemChunkMaterial(text []byte) []byte { + if len(text) == 0 { + return nil + } + if pemChunkCandidateRe.Match(text) { + return text + } + stripped := make([]byte, 0, len(text)) + for _, b := range text { + if b == ' ' || b == '\t' || b == '\r' || b == '\n' { + continue + } + stripped = append(stripped, b) + } + if len(stripped) == 0 || !pemChunkCandidateRe.Match(stripped) { + return nil + } + return stripped +} + // jsonProvenance accumulates an order-preserving view of the decoded strings // in a document so a private-key block that spans members can be detected after // JSON decoding. The raw bytes are not usable for this: a member may encode a @@ -345,8 +376,9 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { // the body back after the markers are masked, where the written-bytes rescan can // no longer see the block (#5705). Consecutive candidate segments are therefore // decided together, whatever their individual length: a segment is a candidate -// when it is made only of base64 characters, and the joined run is what has to -// look like a body line. An object key never joins the run — a key is structure, +// when it is made only of base64 characters and ASCII whitespace (stripped as +// framing, see pemChunkMaterial), and the joined run is what has to look like a +// body line. An object key never joins the run — a key is structure, // and letting one into the joined text renames required schema keys (severity, // category, file) — but it does not break the run either: the values on either // side of a key are still consecutive body chunks once the key names are ignored, @@ -355,20 +387,18 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { // (spanningPrivateKeys). func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { var group []int + var joined []byte flush := func() { if len(group) == 0 { return } - joined := make([]byte, 0, len(group)*16) - for _, i := range group { - joined = append(joined, v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]...) - } if pemBodyJoined(joined) { for _, i := range group { spans.covered[i] = true } } group = group[:0] + joined = joined[:0] } for pos, i := range hit { if pos == 0 || pos == len(hit)-1 { @@ -380,7 +410,6 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { // the run (see the doc comment). continue } - chunk := v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end] if v.valueCarriesKeyMaterial(i) { // A value that is a complete body line on its own is covered by the // main loop, and it ends the run: a structural value in the next @@ -388,11 +417,13 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { flush() continue } - if len(chunk) == 0 || !pemChunkCandidateRe.Match(chunk) { + material := pemChunkMaterial(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) + if material == nil { flush() continue } group = append(group, i) + joined = append(joined, material...) } flush() } @@ -463,21 +494,24 @@ func pemBodyRun(run []byte) bool { // A joined run is not automatically a body, though: consecutive schema values // read as concatenated words — a finding's "critical", "ssrf" and "Makefile" join // to "criticalssrfMakefile", which carries the case and base64 mix on its own. A -// body line is base64 of binary key material, so it scatters digits and runs of -// adjacent upper-case letters through the text, while the enum and path values -// the schema constrains are lowercase words with one leading capital at most. A -// digit anywhere in the run settles it; without one, the run must carry at least -// two adjacent upper-case letters to be body material. A body split so that every -// digit landed in a segment that broke the run, and that also has no adjacent -// capitals, is not recognized here; such a body is still caught member by member -// when a member is a whole body line (pemBodyRun), and the alternative — joining -// every value between quoted markers — masked required schema fields and lost the -// review (#5705). +// body line is base64 of binary key material, so it scatters separate runs of +// upper-case letters through the text, while an enum or a filename the schema +// constrains is a word with a single upper-case run at most ("Makefile", +// "README", "Makefile2"). A digit alone does not separate the two: the trailing +// "2" of "Makefile2" is also a digit, and treating it as proof of key material +// masked a finding's severity, category and file. A joined run therefore needs a +// multi-letter upper-case run that is followed by lower case (hasMixedUpperRun) +// to be body material. A body split so that every such run fell into one segment +// that broke the run is not recognized +// here; such a body is still caught member by member when a member is a whole +// body line (pemBodyRun), and the alternative — treating every value between +// quoted markers as body — masked required schema fields and lost the review +// (#5705). func pemBodyJoined(joined []byte) bool { if len(joined) < 16 { return false } - var upper, lower, digit, base64Only bool + var upper, lower, base64Only bool for _, b := range joined { switch { case b >= 'a' && b <= 'z': @@ -486,8 +520,6 @@ func pemBodyJoined(joined []byte) bool { case b >= 'A' && b <= 'Z': upper = true base64Only = base64Only || b > 'F' - case b >= '0' && b <= '9': - digit = true case b == '+' || b == '/' || b == '=': base64Only = true } @@ -495,23 +527,31 @@ func pemBodyJoined(joined []byte) bool { if !upper || !lower || !base64Only { return false } - return digit || hasUpperRun(joined, 2) + return hasMixedUpperRun(joined) } -// hasUpperRun reports whether text contains min consecutive upper-case letters. -// Base64 of binary material produces those runs often; a concatenation of schema -// words ("critical", "ssrf", "Makefile") produces none, and free text does not -// reach the joined-run test because whitespace and punctuation break the run. -func hasUpperRun(text []byte, min int) bool { +// hasMixedUpperRun reports whether text carries a run of at least two upper-case +// letters that is immediately followed by a lower-case letter. That is the shape +// base64 of binary material scatters through a line ("MIIEow", "QWERTYuiop"): +// capitals recur inside a word and are followed by lower case. A schema word or +// filename produces a single leading capital ("Makefile"), a trailing digit that +// resets the run ("Makefile2"), or an all-capitals token at the end of the word +// ("README"), and none of those is followed by lower case after a multi-letter +// run. A digit alone therefore no longer settles the question, which is what let +// "Makefile2" mask required schema fields (#5705). +func hasMixedUpperRun(text []byte) bool { run := 0 for _, b := range text { - if b < 'A' || b > 'Z' { + switch { + case b >= 'A' && b <= 'Z': + run++ + case b >= 'a' && b <= 'z': + if run >= 2 { + return true + } + run = 0 + default: run = 0 - continue - } - run++ - if run >= min { - return true } } return false @@ -798,27 +838,27 @@ func (v *jsonLineView) spanningRecordPrivateKeys() ([]bool, []Finding) { // the lines are joined. A leaf joins a run at any length, since the joined text is // what has to look like a body line. An object key never joins the run, since a key // is structure rather than body, but it does not break the run either: a body -// stored in separate object members of one record is still reconstructed. A value -// with punctuation or whitespace breaks the run: those are structural tokens and +// stored in separate object members of one record is still reconstructed. ASCII +// whitespace inside a leaf is the line framing an agent kept with the body line, +// so it is stripped before the leaf is tested (pemChunkMaterial); punctuation +// outside the base64 alphabet breaks the run: those are structural tokens and // free text, not body lines. A key whose own name is a body line carries key // material, so its record is covered on its own. func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { first, last := hit[0], hit[len(hit)-1] var group []int + var joined []byte flush := func() { if len(group) == 0 { return } - joined := make([]byte, 0, len(group)*16) - for _, i := range group { - joined = append(joined, v.decoded.Bytes()[v.leaves[i].span.start:v.leaves[i].span.end]...) - } if pemBodyJoined(joined) { for _, i := range group { covered[v.leaves[i].record] = true } } group = group[:0] + joined = joined[:0] } for i, leaf := range v.leaves { // The boundary records are already covered, and their leaves neither @@ -844,11 +884,13 @@ func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { flush() continue } - if len(text) == 0 || !pemChunkCandidateRe.Match(text) { + material := pemChunkMaterial(text) + if material == nil { flush() continue } group = append(group, i) + joined = append(joined, material...) } flush() } diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 7b6517f511..1463b5c2e5 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -279,21 +279,29 @@ func TestSanitizeJSONDocument_MarkerSplitAcrossMembersMasked(t *testing.T) { // the review — the outcome this change exists to prevent (#5705). func TestSanitizeJSONDocument_SchemaFieldsBetweenQuotedMarkersKept(t *testing.T) { p := OutputPipeline() - doc := []byte(`{"action":"comment","repo":"acme/widgets","pr_number":12,` + - `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","body":"quotes a key",` + - `"findings":[` + - `{"severity":"high","category":"logic-error","file":"a.go","description":"quotes the ` + pemBegin + ` header"},` + - `{"severity":"critical","category":"ssrf","file":"Makefile","description":"quotes the ` + pemEnd + ` footer"}]}`) + // A filename is a word, not key material: a trailing digit ("Makefile2") or + // an all-capitals name ("README") must not tip the joined run into a mask + // that drops severity, category and file and fails schema validation + // (#5705). + for _, file := range []string{"Makefile", "Makefile2", "README"} { + t.Run(file, func(t *testing.T) { + doc := []byte(`{"action":"comment","repo":"acme/widgets","pr_number":12,` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","body":"quotes a key",` + + `"findings":[` + + `{"severity":"high","category":"logic-error","file":"a.go","description":"quotes the ` + pemBegin + ` header"},` + + `{"severity":"critical","category":"ssrf","file":"` + file + `","description":"quotes the ` + pemEnd + ` footer"}]}`) - out, findings, err := SanitizeJSONDocument(doc, p) - require.NoError(t, err) - require.NotEmpty(t, findings) - assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) - assert.NotContains(t, string(out), "PRIVATE KEY-----", "the markers themselves are masked") - assert.Contains(t, string(out), `"severity":"critical"`, "a schema value is not body material") - assert.Contains(t, string(out), `"category":"ssrf"`, "a schema value is not body material") - assert.Contains(t, string(out), `"file":"Makefile"`, "a schema value is not body material") - assertReviewResultSchemaValid(t, out) + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----", "the markers themselves are masked") + assert.Contains(t, string(out), `"severity":"critical"`, "a schema value is not body material") + assert.Contains(t, string(out), `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, string(out), `"file":"`+file+`"`, "a schema value is not body material") + assertReviewResultSchemaValid(t, out) + }) + } } // TestSanitizeJSONDocument_ShortBodyChunksMasked pins that a body split into @@ -1588,7 +1596,7 @@ func TestSanitizeJSONDocument_DuplicateKeyWithSecretKey(t *testing.T) { // reviewResultSchemaPath is a pinned copy of the schema authored in // fullsend-ai/agents (schemas/review-result.schema.json, commit -// 2a41318da40a0e5d24644225650d4718db69bee7). Vendoring it ties these tests to the +// cec09212b99fcd78bf7afc7637d8fe0b2007e109). Vendoring it ties these tests to the // real constraints sanitization can break — the enums and patterns of the // structural fields, additionalProperties false, and the required members — // instead of a hand-maintained mirror that silently drifts when the upstream @@ -1839,28 +1847,56 @@ func TestSanitizeJSONDocument_BodyChunksSplitAcrossObjectKeysMasked(t *testing.T assert.NotContains(t, string(out), "END RSA") } +// TestSanitizeJSONDocument_BodyChunksWithLineFramingMasked pins that a body split +// into short chunks that each carry the newline that ended the line is still +// masked. The whitespace is line framing, not body: it must not break the joined +// run, where each chunk on its own is below the material floor (#5705). +func TestSanitizeJSONDocument_BodyChunksWithLineFramingMasked(t *testing.T) { + p := OutputPipeline() + chunks := []string{`MIIEowIB\n`, `AAKCAQEA\n`, `x9Kq2Lm0\n`} + quoted := []string{`"` + pemBegin + `"`} + for _, chunk := range chunks { + quoted = append(quoted, `"`+chunk+`"`) + } + quoted = append(quoted, `"`+pemEnd+`"`) + doc := []byte(`{"lines":[` + strings.Join(quoted, ",") + `]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----") + for _, chunk := range []string{"MIIEowIB", "AAKCAQEA", "x9Kq2Lm0"} { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } +} + // TestSanitizeJSONLines_SchemaFieldsBetweenQuotedMarkersKept is the record-level // half of the joined-run rule: a middle record whose values are schema fields // joins into "criticalssrfMakefile" and must keep its content, so the review the // transcript describes is not discarded (#5705). func TestSanitizeJSONLines_SchemaFieldsBetweenQuotedMarkersKept(t *testing.T) { p := OutputPipeline() - content := []byte( - `{"note":"quotes the ` + pemBegin + ` header"}` + "\n" + - `{"severity":"critical","category":"ssrf","file":"Makefile"}` + "\n" + - `{"note":"quotes the ` + pemEnd + ` footer"}` + "\n") + for _, file := range []string{"Makefile", "Makefile2", "README"} { + t.Run(file, func(t *testing.T) { + content := []byte( + `{"note":"quotes the ` + pemBegin + ` header"}` + "\n" + + `{"severity":"critical","category":"ssrf","file":"` + file + `"}` + "\n" + + `{"note":"quotes the ` + pemEnd + ` footer"}` + "\n") - out, findings, err := SanitizeJSONLines(content, p) - require.NoError(t, err) - require.NotEmpty(t, findings) - lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") - require.Len(t, lines, 3, "record count must not change") - assert.Contains(t, lines[1], `"category":"ssrf"`, "a schema value is not body material") - assert.Contains(t, lines[1], `"file":"Makefile"`, "a schema value is not body material") - assert.NotContains(t, lines[0], "PRIVATE KEY-----") - assert.NotContains(t, lines[2], "PRIVATE KEY-----") - for _, line := range lines { - assert.True(t, json.Valid([]byte(line)), "every record must stay valid JSON: %s", line) + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + assert.Contains(t, lines[1], `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, lines[1], `"file":"`+file+`"`, "a schema value is not body material") + assert.NotContains(t, lines[0], "PRIVATE KEY-----") + assert.NotContains(t, lines[2], "PRIVATE KEY-----") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "every record must stay valid JSON: %s", line) + } + }) } } @@ -1887,6 +1923,30 @@ func TestSanitizeJSONLines_ShortBodyChunksCovered(t *testing.T) { } } +// TestSanitizeJSONLines_BodyChunksWithLineFramingCovered is the record-level half +// of TestSanitizeJSONDocument_BodyChunksWithLineFramingMasked: each middle record +// holds a short body chunk together with the newline that ended the line, and the +// framing must not stop the chunks from being joined and masked (#5705). +func TestSanitizeJSONLines_BodyChunksWithLineFramingCovered(t *testing.T) { + p := OutputPipeline() + content := []byte( + `{"note":"` + pemBegin + `"}` + "\n" + + `["MIIEowIB\n","AAKCAQEA\n","x9Kq2Lm0\n"]` + "\n" + + `{"note":"` + pemEnd + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + for _, chunk := range []string{"MIIEowIB", "AAKCAQEA", "x9Kq2Lm0"} { + assert.NotContains(t, string(out), chunk, "a body chunk must not survive") + } + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + } +} + // TestSanitizeJSONLines_BodyChunksSplitAcrossObjectKeysCovered is the JSONL half: // a middle record whose body chunks are stored in separate object members must be // replaced once the chunks are joined across the intervening keys. diff --git a/internal/security/redactor.go b/internal/security/redactor.go index 082731e0c6..256ce6c768 100644 --- a/internal/security/redactor.go +++ b/internal/security/redactor.go @@ -411,14 +411,18 @@ func defaultStructuralPatterns() []secretPattern { // 'api_key': 'secret\' in a YAML flow mapping as an escape, running on to // the next quote on the same line and swallowing the field that follows. // That branch therefore matches only when the quote after the backslash is - // followed by a field or line boundary. The double-quoted branch likewise - // stops at a raw newline: a JSON double-quoted string cannot contain one, so - // a value ending in \" cannot run on to the next line's quote and swallow - // the field there (#9944). The last branch keeps a raw newline - // inside a single-quoted value matchable, as it was before the escape - // handling was added: it cannot cross a quote, so it never swallows the - // field that follows. The minimum length is enforced in scan, not here. - {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\[\s\S]|[^"\\\r\n])*)"|'((?:''|[^'\r\n])*\\)'[ \t]*(?:,|\}|\]|$)|'((?:''|\\\r?\n|\\.|[^'\r\n\\])*[^'\r\n\\])'|'([^']*)')`}, + // followed by a field or line boundary. The strict double-quoted branch + // stops at a raw newline, so a JSON value ending in \" cannot run on to the + // next line's quote and swallow the field there (#9944). A double-quoted + // value that ends in a literal backslash right before its closing quote + // needs the same bounded fallback the single-quoted branch has, and a + // value folded across physical lines (a YAML or log string, not JSON) still + // needs to be matchable when its closing quote ends the field or the line: + // that last branch allows raw newlines but only at that boundary, so it + // cannot run on to a later field's quote. The single-quoted branch keeps a + // raw newline inside the value matchable, as it was before the escape + // handling was added. The minimum length is enforced in scan, not here. + {"json_field", `(?i)(?:"[^"]*(?:key|token|secret|password|credential|auth)[^"]*"|'[^']*(?:key|token|secret|password|credential|auth)[^']*')\s*:\s*(?:"((?:\\[\s\S]|[^"\\\r\n])*)"|"([^"\r\n]*\\)"[ \t]*(?:,|\}|\]|$)|'((?:''|[^'\r\n])*\\)'[ \t]*(?:,|\}|\]|$)|'((?:''|\\\r?\n|\\.|[^'\r\n\\])*[^'\r\n\\])'|'([^']*)'|"((?:\\[\s\S]|[^"\\])*)"[ \t]*(?:,|\}|\]|$))`}, // The optional quote covers YAML: authorization: "Bearer ". {"auth_header", `(?i)(?:Authorization|X-Api-Key|X-Auth-Token)\s*:\s*['"]?(?:(?:Basic|Bearer|Token)\s+)?([^\s"'}\]),;]{12,})`}, {"private_key", `-----BEGIN\s+(?:RSA\s+|EC\s+|OPENSSH\s+)?PRIVATE KEY-----[\s\S]*?-----END\s+(?:RSA\s+|EC\s+|OPENSSH\s+)?PRIVATE KEY-----`}, diff --git a/internal/security/scanner_test.go b/internal/security/scanner_test.go index b44f4bdb4d..8564b6ef33 100644 --- a/internal/security/scanner_test.go +++ b/internal/security/scanner_test.go @@ -550,6 +550,35 @@ func TestSecretRedactor(t *testing.T) { assert.NotContains(t, result.Sanitized, "abcdefg") }) + t.Run("json_field redacts a double-quoted value ending in a literal backslash", func(t *testing.T) { + // The strict double-quoted branch reads \" as an escaped quote and then + // needs another quote to close, so a value that ends in one literal + // backslash right before its closing quote matched no branch at all. + // Main's `"([^"]{8,})"` masked it, and a log line can carry a password + // with a trailing backslash (#5705). + result := r.Scan("\"password\": \"Abc123xyzQ\\\"\nnext line\n") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "Abc123xyzQ") + }) + + t.Run("json_field redacts a double-quoted value ending in a literal backslash before a field", func(t *testing.T) { + result := r.Scan(`{"password": "Abc123xyzQ\"}`) + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "Abc123xyzQ") + }) + + t.Run("json_field redacts a double-quoted value folded across lines", func(t *testing.T) { + // A YAML or log string can fold a double-quoted value across physical + // lines. The strict branch excludes raw CR/LF, so the value must still be + // matchable when its closing quote ends the field or the line (#5705). + result := r.Scan("\"password\": \"line1\nline2line3\"\nnext line\n") + assert.False(t, result.Safe) + assert.True(t, hasFinding(result, "json_field")) + assert.NotContains(t, result.Sanitized, "line2line3") + }) + t.Run("json_field handles doubled apostrophe in YAML scalar", func(t *testing.T) { result := r.Scan("'password': 'abcdefgh''remaining_secret'") assert.True(t, hasFinding(result, "json_field")) From 197a941b680a0f1408e6dd59c51051e9c3ddaa13 Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 3 Dec 2026 05:40:56 -0500 Subject: [PATCH 48/51] fix(#5705): harden PEM body localization across leaves A private-key body can be split across members or records in shapes the localization did not reconstruct: a short fragment beside a recognized body line, and a fragment embedded in surrounding text or a prefixed key ("part: MIIEowIB"). Join the base64 runs embedded in a leaf instead of requiring the whole value to be base64, so line framing and a prefix do not break the run. A recognized body line still ends the preceding run so structural values before it (severity, category, file) are not masked, but it restarts one so a short fragment after it is covered. A lowercase word after a recognized body line breaks the run, so an enum value beside key material is not joined into a mask; before a body line a lowercase fragment may still join. Update the schema-preservation regressions to cover LICENSE and add document and JSONL regressions for the short-fragment-after-body-line and prefixed-fragment cases. Signed-off-by: Andrew Evans Signed-off-by: anevans --- internal/security/jsonsanitize.go | 131 +++++++++++++++---------- internal/security/jsonsanitize_test.go | 82 +++++++++++++++- 2 files changed, 160 insertions(+), 53 deletions(-) diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index c41e06f3af..1bb2118c53 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -219,43 +219,29 @@ var privateKeyMarkerRe = regexp.MustCompile(`-----BEGIN|-----END|PRIVATE KEY---- // instead (maskSpanBody). var privateKeyMaterialRe = regexp.MustCompile(`[A-Za-z0-9+/]{16,}=*`) -// pemChunkCandidateRe matches a string value that could be one segment of a PEM -// body: every byte is in the base64 alphabet. A value with a hyphen, a period or -// any other punctuation is free text or a structural token, so it breaks a run of -// segments rather than joining one. Short segments are candidates too: a body can -// be split so that every member holds only a few characters, and the run is -// judged on its joined text rather than on any one segment. -var pemChunkCandidateRe = regexp.MustCompile(`^[A-Za-z0-9+/]+=*$`) +// pemBodyRunRe matches a maximal run of base64 characters inside a leaf. A body +// fragment can be embedded in surrounding text or line framing — "part: MIIEowIB", +// or a chunk stored together with the newline that ended the line — so the runs, +// not the whole value, are what join a body. The run is kept at any length: a +// body split into one- to three-character chunks is only recognizable once the +// chunks are joined, and pemBodyJoined decides whether the joined text is key +// material or a concatenation of schema words. +var pemBodyRunRe = regexp.MustCompile(`[A-Za-z0-9+/]+=*`) -// pemChunkMaterial returns the base64 material of a candidate body segment, or -// nil when the segment cannot be one. -// -// A PEM body line is 64 columns wide, and an agent can store the line together -// with the newline that ended it inside the decoded string value, so whitespace -// inside a segment is framing rather than body. It is stripped before the -// segment is tested and joined, and must not break a run: otherwise a body split -// into short chunks that each carry a newline slipped through as neither a -// whole-line match nor a joined run, and the body was written back after the -// markers were masked (#5705). Anything outside the base64 alphabet and ASCII -// whitespace keeps the segment out of the run. -func pemChunkMaterial(text []byte) []byte { - if len(text) == 0 { +// pemBodyRuns returns the base64 runs of a leaf's text concatenated, or nil when +// the leaf carries no run at all. Surrounding prose, punctuation and whitespace +// stay out of the joined text, while an embedded body fragment (a "part:" prefix, +// a trailing newline) is still collected instead of breaking the run (#5705). +func pemBodyRuns(text []byte) []byte { + runs := pemBodyRunRe.FindAll(text, -1) + if len(runs) == 0 { return nil } - if pemChunkCandidateRe.Match(text) { - return text + var material []byte + for _, run := range runs { + material = append(material, run...) } - stripped := make([]byte, 0, len(text)) - for _, b := range text { - if b == ' ' || b == '\t' || b == '\r' || b == '\n' { - continue - } - stripped = append(stripped, b) - } - if len(stripped) == 0 || !pemChunkCandidateRe.Match(stripped) { - return nil - } - return stripped + return material } // jsonProvenance accumulates an order-preserving view of the decoded strings @@ -375,10 +361,11 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { // is short or digit-free; a per-member test then accepts none of them and writes // the body back after the markers are masked, where the written-bytes rescan can // no longer see the block (#5705). Consecutive candidate segments are therefore -// decided together, whatever their individual length: a segment is a candidate -// when it is made only of base64 characters and ASCII whitespace (stripped as -// framing, see pemChunkMaterial), and the joined run is what has to look like a -// body line. An object key never joins the run — a key is structure, +// decided together, whatever their individual length: the base64 runs embedded in +// a member are collected (pemBodyRuns), so surrounding prose, a "part:" prefix or +// the newline an agent kept with a body line does not break the run, and the +// joined text is what has to look like a body line. An object key never joins the +// run — a key is structure, // and letting one into the joined text renames required schema keys (severity, // category, file) — but it does not break the run either: the values on either // side of a key are still consecutive body chunks once the key names are ignored, @@ -388,8 +375,13 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { var group []int var joined []byte + // bodySeeded says the current run was restarted at a recognized body line. + // Only then does a lowercase word break the run: before a body line, a + // lowercase fragment can still be part of a body split across members. + bodySeeded := false flush := func() { if len(group) == 0 { + bodySeeded = false return } if pemBodyJoined(joined) { @@ -399,6 +391,7 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { } group = group[:0] joined = joined[:0] + bodySeeded = false } for pos, i := range hit { if pos == 0 || pos == len(hit)-1 { @@ -410,15 +403,23 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { // the run (see the doc comment). continue } + material := pemBodyRuns(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) if v.valueCarriesKeyMaterial(i) { // A value that is a complete body line on its own is covered by the - // main loop, and it ends the run: a structural value in the next - // member must not be joined into a mask with it. + // main loop. It ends the preceding run — the structural values before + // it ("severity", "category", "file") must not be joined into a mask + // with it — but the run restarts at this leaf, so a short fragment + // that follows it ("AQAB", or "part: MIIEowIB") is still + // reconstructed and masked instead of surviving once the markers are + // gone (#5705). + spans.covered[i] = true flush() - continue + bodySeeded = true } - material := pemChunkMaterial(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) - if material == nil { + if material == nil || (bodySeeded && isLowerWord(material)) { + // A lowercase word after a recognized body line is a schema value or + // free text, not a body chunk: it breaks the run instead of joining + // it (#5705). flush() continue } @@ -428,6 +429,22 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { flush() } +// isLowerWord reports whether text is made only of lower-case ASCII letters, the +// shape of a schema enum ("high", "critical", "ssrf") or a path segment. Such a +// value cannot be a body chunk on its own — pemBodyJoined needs upper case — and +// letting it join a run beside a recognized body line masked it (#5705). +func isLowerWord(text []byte) bool { + if len(text) == 0 { + return false + } + for _, b := range text { + if b < 'a' || b > 'z' { + return false + } + } + return true +} + // valueCarriesKeyMaterial reports whether the decoded key or string value at // index i has to be replaced whole: it carries a block marker, or one of its runs // holds base64 body material. @@ -838,18 +855,22 @@ func (v *jsonLineView) spanningRecordPrivateKeys() ([]bool, []Finding) { // the lines are joined. A leaf joins a run at any length, since the joined text is // what has to look like a body line. An object key never joins the run, since a key // is structure rather than body, but it does not break the run either: a body -// stored in separate object members of one record is still reconstructed. ASCII -// whitespace inside a leaf is the line framing an agent kept with the body line, -// so it is stripped before the leaf is tested (pemChunkMaterial); punctuation -// outside the base64 alphabet breaks the run: those are structural tokens and -// free text, not body lines. A key whose own name is a body line carries key -// material, so its record is covered on its own. +// stored in separate object members of one record is still reconstructed. Only the +// base64 runs embedded in a leaf join the run (pemBodyRuns), so line framing, a +// "part:" prefix and the punctuation around a fragment do not break it, while a +// leaf with no base64 run at all breaks it. A key whose own name is a body line +// carries key material, so its record is covered on its own. func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { first, last := hit[0], hit[len(hit)-1] var group []int var joined []byte + // bodySeeded says the current run was restarted at a recognized body line. + // Only then does a lowercase word break the run: before a body line, a + // lowercase fragment can still be part of a body split across records. + bodySeeded := false flush := func() { if len(group) == 0 { + bodySeeded = false return } if pemBodyJoined(joined) { @@ -859,6 +880,7 @@ func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { } group = group[:0] joined = joined[:0] + bodySeeded = false } for i, leaf := range v.leaves { // The boundary records are already covered, and their leaves neither @@ -879,13 +901,20 @@ func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { } continue } + material := pemBodyRuns(text) if textCarriesKeyMaterial(text) { + // A recognized body line covers its own record and ends the preceding + // run, so structural values before it are not joined into a mask with + // it. The run restarts at this leaf, so a short fragment that follows + // is reconstructed and its record masked with it (#5705). covered[leaf.record] = true flush() - continue + bodySeeded = true } - material := pemChunkMaterial(text) - if material == nil { + if material == nil || (bodySeeded && isLowerWord(material)) { + // A lowercase word after a recognized body line is a schema value or + // free text, not a body chunk: it breaks the run instead of joining + // it (#5705). flush() continue } diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 1463b5c2e5..46f0a069d9 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -283,7 +283,7 @@ func TestSanitizeJSONDocument_SchemaFieldsBetweenQuotedMarkersKept(t *testing.T) // an all-capitals name ("README") must not tip the joined run into a mask // that drops severity, category and file and fails schema validation // (#5705). - for _, file := range []string{"Makefile", "Makefile2", "README"} { + for _, file := range []string{"Makefile", "Makefile2", "README", "LICENSE"} { t.Run(file, func(t *testing.T) { doc := []byte(`{"action":"comment","repo":"acme/widgets","pr_number":12,` + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","body":"quotes a key",` + @@ -1847,6 +1847,38 @@ func TestSanitizeJSONDocument_BodyChunksSplitAcrossObjectKeysMasked(t *testing.T assert.NotContains(t, string(out), "END RSA") } +// TestSanitizeJSONDocument_ShortFragmentAfterBodyLineMasked pins that a recognized +// body line does not end the run: a short final fragment beside it must be masked +// too, or it survives once the markers are gone (#5705). +func TestSanitizeJSONDocument_ShortFragmentAfterBodyLineMasked(t *testing.T) { + p := OutputPipeline() + longLine := "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + doc := []byte(`{"a":"` + pemBegin + `","b":"` + longLine + `","c":"AQAB","d":"` + pemEnd + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), longLine) + assert.NotContains(t, string(out), "AQAB", "a short fragment beside a body line must not survive") +} + +// TestSanitizeJSONDocument_PrefixedBodyFragmentsMasked pins that body fragments +// embedded in surrounding text are masked. The "part:" prefix and the whitespace +// used to break the run, so each 8-character fragment stayed below the material +// floor and survived after the markers were masked (#5705). +func TestSanitizeJSONDocument_PrefixedBodyFragmentsMasked(t *testing.T) { + p := OutputPipeline() + doc := []byte(`{"a":"` + pemBegin + `","b":"part: MIIEowIB","c":"part: AAKCAQEA","d":"` + pemEnd + `"}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "MIIEowIB", "a prefixed body fragment must not survive") + assert.NotContains(t, string(out), "AAKCAQEA", "a prefixed body fragment must not survive") +} + // TestSanitizeJSONDocument_BodyChunksWithLineFramingMasked pins that a body split // into short chunks that each carry the newline that ended the line is still // masked. The whitespace is line framing, not body: it must not break the joined @@ -1877,7 +1909,7 @@ func TestSanitizeJSONDocument_BodyChunksWithLineFramingMasked(t *testing.T) { // transcript describes is not discarded (#5705). func TestSanitizeJSONLines_SchemaFieldsBetweenQuotedMarkersKept(t *testing.T) { p := OutputPipeline() - for _, file := range []string{"Makefile", "Makefile2", "README"} { + for _, file := range []string{"Makefile", "Makefile2", "README", "LICENSE"} { t.Run(file, func(t *testing.T) { content := []byte( `{"note":"quotes the ` + pemBegin + ` header"}` + "\n" + @@ -1923,6 +1955,52 @@ func TestSanitizeJSONLines_ShortBodyChunksCovered(t *testing.T) { } } +// TestSanitizeJSONLines_ShortFragmentAfterBodyLineCovered is the record-level half +// of TestSanitizeJSONDocument_ShortFragmentAfterBodyLineMasked: a short fragment +// beside a recognized body line must be covered with it (#5705). +func TestSanitizeJSONLines_ShortFragmentAfterBodyLineCovered(t *testing.T) { + p := OutputPipeline() + longLine := "MIIEowIBAAKCAQEAx7Qz9restOfTheBodyWq1Ez" + content := []byte( + `{"note":"` + pemBegin + `"}` + "\n" + + `{"line":"` + longLine + `"}` + "\n" + + `{"tail":"AQAB"}` + "\n" + + `{"note":"` + pemEnd + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), longLine) + assert.NotContains(t, string(out), "AQAB", "a short fragment beside a body line must not survive") + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + } +} + +// TestSanitizeJSONLines_PrefixedBodyFragmentsCovered is the record-level half of +// TestSanitizeJSONDocument_PrefixedBodyFragmentsMasked (#5705). +func TestSanitizeJSONLines_PrefixedBodyFragmentsCovered(t *testing.T) { + p := OutputPipeline() + content := []byte( + `{"note":"` + pemBegin + `"}` + "\n" + + `{"part":"part: MIIEowIB"}` + "\n" + + `{"part":"part: AAKCAQEA"}` + "\n" + + `{"note":"` + pemEnd + `"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.NotContains(t, string(out), "MIIEowIB", "a prefixed body fragment must not survive") + assert.NotContains(t, string(out), "AAKCAQEA", "a prefixed body fragment must not survive") + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 4, "record count must not change") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "each replaced record must stay valid JSON: %s", line) + } +} + // TestSanitizeJSONLines_BodyChunksWithLineFramingCovered is the record-level half // of TestSanitizeJSONDocument_BodyChunksWithLineFramingMasked: each middle record // holds a short body chunk together with the newline that ended the line, and the From d82974110a913f62c2dafed88c6ec993c25b3bc1 Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 3 Dec 2026 06:09:16 -0500 Subject: [PATCH 49/51] fix(#5705): protect schema fields by structure and route multi-doc JSON Address review findings: - Distinguish schema-constrained review fields (severity, category, action, file, repo, etc.) in JSON and JSONL provenance views so they never join candidate PEM body chunks, guaranteeing schema fields survive regardless of key order without relying on character-mix heuristics like isLowerWord. - Route multi-document JSON streams (detected via IsJSONLines) through per-record sanitization even when the file does not have a .jsonl/.ndjson extension, preventing plain-text redactions from breaking stream framing. - Unify FailClosedUnwritableJSON into OutputRemoval's marker table so all removal predicates and alert handlers recognize it consistently. - Write sanitized JSON and JSONL whenever byte content was modified, even if findings slice is empty, preventing silent data drops. - Replace pointer arithmetic in scan counters with explicit assignment. Signed-off-by: Andrew Evans Signed-off-by: anevans --- internal/cli/run.go | 22 ++-- internal/cli/scan_output_telemetry_test.go | 19 ++- internal/security/jsonsanitize.go | 138 ++++++++++++++------- internal/security/jsonsanitize_test.go | 67 ++++++++++ 4 files changed, 189 insertions(+), 57 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index 791fc87aec..4e3fa6faba 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -7514,8 +7514,12 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri ext := strings.ToLower(filepath.Ext(path)) // JSONL and NDJSON are sanitized record by record so one record never - // rewrites another (#5705). - if ext == ".jsonl" || ext == ".ndjson" { + // rewrites another (#5705). Multi-document streams in files with other + // extensions (such as a .json file holding multiple records) are also + // recognized by content and handled per record rather than falling + // through to the plain-text scan. + isLines := ext == ".jsonl" || ext == ".ndjson" || (!security.IsJSONDocument(content) && security.IsJSONLines(content)) + if isLines { out, jsonLineFindings, scanErr := sanitizeLines(content, pipeline) if scanErr != nil { writeErrs = append(writeErrs, sanitizeFailure(path, relPath, scanErr, &unsanitizable)) @@ -7527,7 +7531,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri // contains a marker-equal line (a re-scanned artifact, a fixture, // or a line the agent wrote on purpose) does not raise a false // error when this pass removed nothing. - if len(jsonLineFindings) > 0 { + if len(jsonLineFindings) > 0 || !bytes.Equal(out, content) { alertOnRecordRemoval(printer, out) findingCount += len(jsonLineFindings) for _, f := range jsonLineFindings { @@ -7557,7 +7561,7 @@ func scanOutputFilesWithWriter(outputDir, traceID, progressVerbosity string, pri writeErrs = append(writeErrs, sanitizeFailure(path, relPath, jsonErr, &unsanitizable)) return nil } - if len(jsonFindings) > 0 { + if len(jsonFindings) > 0 || !bytes.Equal(out, content) { findingCount += len(jsonFindings) for _, f := range jsonFindings { if !quiet { @@ -7745,7 +7749,7 @@ func alertOnRecordRemoval(printer *ui.Printer, sanitized []byte) { // The completion comment posts a count instead of the agent-chosen name at quiet // (failureStatusDetail, ADR 0163). func writeFailure(path, relPath string, writeErr error, unwritable *int) error { - *unwritable++ + *unwritable = *unwritable + 1 quarantineErr := quarantineOutput(path) return &outputFileFailure{path: path, err: errors.Join( fmt.Errorf("could not write sanitized %s: %w", relPath, writeErr), quarantineErr)} @@ -7758,7 +7762,7 @@ func writeFailure(path, relPath string, writeErr error, unwritable *int) error { // progress level; only the printed line is trimmed at quiet, and the completion // comment gets a count (failureStatusDetail, ADR 0163). func readFailure(path, relPath string, readErr error, unreadable *int) error { - *unreadable++ + *unreadable = *unreadable + 1 quarantineErr := quarantineOutput(path) return &outputFileFailure{path: path, err: errors.Join( fmt.Errorf("could not read %s: %w", relPath, readErr), quarantineErr)} @@ -7771,7 +7775,7 @@ func readFailure(path, relPath string, readErr error, unreadable *int) error { // progress level; only the printed line is trimmed at quiet, and the completion // comment gets a count (failureStatusDetail, ADR 0163). func walkFailure(outputDir, path string, walkErr error, unreadable *int) error { - *unreadable++ + *unreadable = *unreadable + 1 relPath, err := filepath.Rel(outputDir, path) if err != nil { relPath = path @@ -7786,7 +7790,7 @@ func walkFailure(outputDir, path string, walkErr error, unreadable *int) error { // and wraps the cause at every progress level; the completion comment gets a // count at quiet (failureStatusDetail, ADR 0163). func sanitizeFailure(path, relPath string, scanErr error, unsanitizable *int) error { - *unsanitizable++ + *unsanitizable = *unsanitizable + 1 quarantineErr := quarantineOutput(path) return &outputFileFailure{path: path, err: errors.Join( fmt.Errorf("could not sanitize %s: %w", relPath, scanErr), quarantineErr)} @@ -7811,7 +7815,7 @@ func quarantineOutput(path string) error { // unwritableOutputMarker replaces a file whose sanitized content could not be // computed or written. It is valid JSON so downstream parsers keep working. -const unwritableOutputMarker = `{"error":"output removed because it could not be redacted"}` +const unwritableOutputMarker = security.FailClosedUnwritableJSON // downloadFindingsFn extracts the sandbox-side findings directory. It is a // parameter of collectPostScanSecurityArtifacts rather than a package global so diff --git a/internal/cli/scan_output_telemetry_test.go b/internal/cli/scan_output_telemetry_test.go index 9c7d39df7b..d41e9dbec6 100644 --- a/internal/cli/scan_output_telemetry_test.go +++ b/internal/cli/scan_output_telemetry_test.go @@ -593,7 +593,7 @@ func TestScanOutputFiles_HandlesJSONLAndNDJSON(t *testing.T) { "{\"event\":\"body\",\"text\":\"MIIEpAIBAAKCAQEA0123456789abcdef\"}\n" + "{\"event\":\"end\",\"text\":\"" + pemEnd + "\"}\n" - for _, ext := range []string{".jsonl", ".ndjson"} { + for _, ext := range []string{".jsonl", ".ndjson", ".json"} { t.Run(ext, func(t *testing.T) { t.Setenv("GITHUB_ACTIONS", "") dir := t.TempDir() @@ -614,6 +614,23 @@ func TestScanOutputFiles_HandlesJSONLAndNDJSON(t *testing.T) { } } +// TestScanOutputFiles_WritesWhenBytesModifiedEvenWithZeroFindings pins that +// any byte change produced by the structural sanitizer is written to disk, +// even if findings slice is empty, preventing silent data drops (#5705). +func TestScanOutputFiles_WritesWhenBytesModifiedEvenWithZeroFindings(t *testing.T) { + dir := t.TempDir() + docPath := filepath.Join(dir, "doc.json") + require.NoError(t, os.WriteFile(docPath, []byte(`{"a": 1}`), 0o644)) + + stubDoc := func(in []byte, p *security.Pipeline) ([]byte, []security.Finding, error) { + return []byte(`{"a": 2}`), nil, nil + } + require.NoError(t, scanOutputFilesWithWriter(dir, "trace", "", ui.New(&bytes.Buffer{}), os.WriteFile, stubDoc, security.SanitizeJSONLines)) + got, err := os.ReadFile(docPath) + require.NoError(t, err) + assert.Equal(t, `{"a": 2}`, string(got)) +} + // TestScanOutputFiles_NoAnnotationForPreexistingMarkerLine pins that a clean // JSONL file that already holds a marker-equal line raises no error annotation: // this pass removed nothing, so an operator should not be told a record was lost. diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 1bb2118c53..627b4fadc5 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -22,6 +22,7 @@ const ( failClosedInvalidJSON = `{"error":"output removed because redaction would invalidate JSON"}` failClosedCrossRecordJSON = `{"error":"output removed because output contained a cross-record secret"}` failClosedSpansMembersJSON = `{"error":"output removed because a private key block spans JSON framing"}` + FailClosedUnwritableJSON = `{"error":"output removed because it could not be redacted"}` ) // privateKeyMask replaces each JSON string value that carries key material from a @@ -43,6 +44,25 @@ func IsJSONDocument(doc []byte) bool { return json.Valid(bytes.TrimSpace(bytes.TrimPrefix(doc, utf8BOM))) } +// IsJSONLines reports whether content consists of two or more non-empty lines +// where every non-empty line is a valid JSON document. Callers use it to detect +// a multi-document JSON stream regardless of file extension (#5705). +func IsJSONLines(content []byte) bool { + lines := bytes.Split(content, []byte("\n")) + nonEmpty := 0 + for _, line := range lines { + trimmed := bytes.TrimSpace(bytes.TrimPrefix(bytes.TrimSpace(line), utf8BOM)) + if len(trimmed) == 0 { + continue + } + if !json.Valid(trimmed) { + return false + } + nonEmpty++ + } + return nonEmpty >= 2 +} + // restoreBOM puts back the UTF-8 BOM the structural path strips, so a // BOM-prefixed file keeps its encoding mark. func restoreBOM(original, sanitized []byte) []byte { @@ -62,6 +82,7 @@ var outputRemovalMarkers = []struct { {failClosedInvalidJSON, "redaction would invalidate JSON"}, {failClosedCrossRecordJSON, "a secret spanned multiple records"}, {failClosedSpansMembersJSON, "a private key block spans JSON framing"}, + {FailClosedUnwritableJSON, "it could not be redacted"}, } // OutputRemoval reports whether sanitized is a whole-file removal marker and @@ -244,6 +265,37 @@ func pemBodyRuns(text []byte) []byte { return material } +// schemaConstrainedFields is the set of review schema keys whose values are +// structural (enums, file paths, repository identifiers) rather than key material. +// When a quoted marker pair covers a review result, these fields are protected +// from joining candidate PEM body runs so schema validation is not broken (#5705). +var schemaConstrainedFields = map[string]bool{ + "action": true, + "category": true, + "severity": true, + "file": true, + "repo": true, + "head_sha": true, + "id": true, + "dimension": true, + "reason": true, + "pr_number": true, + "line": true, + "actionable": true, +} + +// isSchemaConstrainedField reports whether a value under memberKey is a +// schema-constrained review field rather than candidate key material. +func isSchemaConstrainedField(memberKey, value string) bool { + if !schemaConstrainedFields[memberKey] { + return false + } + if textCarriesKeyMaterial([]byte(value)) { + return false + } + return true +} + // jsonProvenance accumulates an order-preserving view of the decoded strings // in a document so a private-key block that spans members can be detected after // JSON decoding. The raw bytes are not usable for this: a member may encode a @@ -255,7 +307,8 @@ type jsonProvenance struct { // keys marks the entries in ranges that are object keys rather than string // values. Key names are the document's structure, so a block that spans // them is neutralized differently from a block that spans values. - keys []bool + keys []bool + memberKeys []string } // decodedViewNormalizer normalizes decoded JSON text before it is matched for @@ -265,13 +318,14 @@ var decodedViewNormalizer = NewUnicodeNormalizer() // addString appends one decoded key or string value to the view and records its // byte range so a match can be mapped back to the leaves that carry it. -func (v *jsonProvenance) addString(s string, isKey bool) { +func (v *jsonProvenance) addString(s string, isKey bool, memberKey string) { s = decodedViewNormalizer.Scan(s).Sanitized start := v.decoded.Len() v.decoded.WriteString(s) v.decoded.WriteByte('\n') v.ranges = append(v.ranges, recordSpan{start: start, end: v.decoded.Len() - 1}) v.keys = append(v.keys, isKey) + v.memberKeys = append(v.memberKeys, memberKey) } // privateKeySpans is the result of looking for private-key blocks that span the @@ -376,15 +430,13 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { var group []int var joined []byte // bodySeeded says the current run was restarted at a recognized body line. - // Only then does a lowercase word break the run: before a body line, a - // lowercase fragment can still be part of a body split across members. bodySeeded := false flush := func() { if len(group) == 0 { bodySeeded = false return } - if pemBodyJoined(joined) { + if bodySeeded || pemBodyJoined(joined) { for _, i := range group { spans.covered[i] = true } @@ -403,7 +455,14 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { // the run (see the doc comment). continue } - material := pemBodyRuns(v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]) + valBytes := v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end] + if isSchemaConstrainedField(v.memberKeys[i], string(valBytes)) { + // A schema-constrained field (severity, category, file, etc.) is + // review structure, not key material: it never joins a candidate + // run and breaks any pending run (#5705). + flush() + continue + } if v.valueCarriesKeyMaterial(i) { // A value that is a complete body line on its own is covered by the // main loop. It ends the preceding run — the structural values before @@ -416,10 +475,8 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { flush() bodySeeded = true } - if material == nil || (bodySeeded && isLowerWord(material)) { - // A lowercase word after a recognized body line is a schema value or - // free text, not a body chunk: it breaks the run instead of joining - // it (#5705). + material := pemBodyRuns(valBytes) + if len(material) < 2 { flush() continue } @@ -429,22 +486,6 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { flush() } -// isLowerWord reports whether text is made only of lower-case ASCII letters, the -// shape of a schema enum ("high", "critical", "ssrf") or a path segment. Such a -// value cannot be a body chunk on its own — pemBodyJoined needs upper case — and -// letting it join a run beside a recognized body line masked it (#5705). -func isLowerWord(text []byte) bool { - if len(text) == 0 { - return false - } - for _, b := range text { - if b < 'a' || b > 'z' { - return false - } - } - return true -} - // valueCarriesKeyMaterial reports whether the decoded key or string value at // index i has to be replaced whole: it carries a block marker, or one of its runs // holds base64 body material. @@ -771,9 +812,10 @@ type jsonLineView struct { // jsonLineLeaf is one decoded object key or string value in a jsonLineView. type jsonLineLeaf struct { - record int - span recordSpan - key bool + record int + span recordSpan + key bool + memberKey string } // newJSONLineView builds the decoded view of a stream whose non-empty records @@ -790,9 +832,10 @@ func newJSONLineView(content []byte, spans []recordSpan) *jsonLineView { view.decoded.Write(prov.decoded.Bytes()) for j, r := range prov.ranges { view.leaves = append(view.leaves, jsonLineLeaf{ - record: i, - span: recordSpan{start: start + r.start, end: start + r.end}, - key: prov.keys[j], + record: i, + span: recordSpan{start: start + r.start, end: start + r.end}, + key: prov.keys[j], + memberKey: prov.memberKeys[j], }) } } else { @@ -865,15 +908,13 @@ func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { var group []int var joined []byte // bodySeeded says the current run was restarted at a recognized body line. - // Only then does a lowercase word break the run: before a body line, a - // lowercase fragment can still be part of a body split across records. bodySeeded := false flush := func() { if len(group) == 0 { bodySeeded = false return } - if pemBodyJoined(joined) { + if bodySeeded || pemBodyJoined(joined) { for _, i := range group { covered[v.leaves[i].record] = true } @@ -901,7 +942,12 @@ func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { } continue } - material := pemBodyRuns(text) + if isSchemaConstrainedField(leaf.memberKey, string(text)) { + // Schema-constrained review fields never join candidate runs and + // break any pending run (#5705). + flush() + continue + } if textCarriesKeyMaterial(text) { // A recognized body line covers its own record and ends the preceding // run, so structural values before it are not joined into a mask with @@ -911,10 +957,8 @@ func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { flush() bodySeeded = true } - if material == nil || (bodySeeded && isLowerWord(material)) { - // A lowercase word after a recognized body line is a schema value or - // free text, not a body chunk: it breaks the run instead of joining - // it (#5705). + material := pemBodyRuns(text) + if len(material) < 2 { flush() continue } @@ -940,8 +984,8 @@ func collectJSONLeaves(doc []byte) *jsonProvenance { prov := &jsonProvenance{} dec := json.NewDecoder(bytes.NewReader(doc)) dec.UseNumber() - var walkValue func() - walkValue = func() { + var walkValue func(memberKey string) + walkValue = func(memberKey string) { tok, err := dec.Token() if err != nil { return @@ -959,21 +1003,21 @@ func collectJSONLeaves(doc []byte) *jsonProvenance { if !ok { return } - prov.addString(key, true) - walkValue() + prov.addString(key, true, "") + walkValue(key) } _, _ = dec.Token() // consume the closing delimiter case '[': for dec.More() { - walkValue() + walkValue("") } _, _ = dec.Token() // consume the closing delimiter } case string: - prov.addString(t, false) + prov.addString(t, false, memberKey) } } - walkValue() + walkValue("") return prov } diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 46f0a069d9..22bc6d515d 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -304,6 +304,34 @@ func TestSanitizeJSONDocument_SchemaFieldsBetweenQuotedMarkersKept(t *testing.T) } } +// TestSanitizeJSONDocument_SchemaFieldsInReversedOrderKept pins that schema +// fields appearing in any key order (for example, "file" before "category" and +// "severity") are recognized as structure rather than candidate key material, +// so an all-caps filename like README before an enum like ssrf does not join into +// an apparent mixed-upper run (#5705). +func TestSanitizeJSONDocument_SchemaFieldsInReversedOrderKept(t *testing.T) { + p := OutputPipeline() + for _, file := range []string{"README", "LICENSE", "Makefile", "Makefile2"} { + t.Run(file, func(t *testing.T) { + doc := []byte(`{"action":"comment","repo":"acme/widgets","pr_number":12,` + + `"head_sha":"abcdef0123456789abcdef0123456789abcdef01","body":"quotes a key",` + + `"findings":[` + + `{"description":"quotes the ` + pemBegin + ` header","file":"a.go","category":"logic-error","severity":"high"},` + + `{"file":"` + file + `","category":"ssrf","severity":"critical","description":"quotes the ` + pemEnd + ` footer"}]}`) + + out, findings, err := SanitizeJSONDocument(doc, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + assert.True(t, json.Valid(out), "sanitized JSON must stay valid: %s", out) + assert.NotContains(t, string(out), "PRIVATE KEY-----", "the markers themselves are masked") + assert.Contains(t, string(out), `"severity":"critical"`, "a schema value is not body material") + assert.Contains(t, string(out), `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, string(out), `"file":"`+file+`"`, "a schema value is not body material") + assertReviewResultSchemaValid(t, out) + }) + } +} + // TestSanitizeJSONDocument_ShortBodyChunksMasked pins that a body split into // chunks shorter than the material floor is still masked. Each chunk is too short // for the per-value test, so the run is decided on its joined text and every @@ -738,6 +766,7 @@ func TestOutputRemoval(t *testing.T) { "invalid json": {failClosedInvalidJSON + "\n", "redaction would invalidate JSON", true}, "cross-record": {failClosedCrossRecordJSON, "a secret spanned multiple records", true}, "spans members": {failClosedSpansMembersJSON, "a private key block spans JSON framing", true}, + "unwritable": {FailClosedUnwritableJSON, "it could not be redacted", true}, "bom prefixed": {"\ufeff" + failClosedSpansMembersJSON, "a private key block spans JSON framing", true}, "bom and space": {"\ufeff " + failClosedInvalidJSON + "\r\n", "redaction would invalidate JSON", true}, "ordinary doc": {`{"error":"not a removal marker"}`, "", false}, @@ -1433,6 +1462,16 @@ func TestSanitizeJSONDocument_LeavesUnsupportedInputAlone(t *testing.T) { } } +// TestIsJSONLines pins multi-document detection. +func TestIsJSONLines(t *testing.T) { + assert.True(t, IsJSONLines([]byte("{\"a\":1}\n{\"b\":2}\n"))) + assert.True(t, IsJSONLines([]byte("\ufeff{\"a\":1}\r\n{\"b\":2}\r\n"))) + assert.False(t, IsJSONLines([]byte("{\"a\":1}\n")), "single record is not a multi-document stream") + assert.False(t, IsJSONLines([]byte("{\"a\":1}")), "single record without newline is not a stream") + assert.False(t, IsJSONLines([]byte("{\"a\":1}\nnot json\n")), "stream with non-JSON line is rejected") + assert.False(t, IsJSONLines([]byte("")), "empty content is not a stream") +} + // TestSanitizeJSONLines_NonJSONRecordsRedacted pins the text fallback for // records that are not valid JSON. func TestSanitizeJSONLines_NonJSONRecordsRedacted(t *testing.T) { @@ -1932,6 +1971,34 @@ func TestSanitizeJSONLines_SchemaFieldsBetweenQuotedMarkersKept(t *testing.T) { } } +// TestSanitizeJSONLines_SchemaFieldsInReversedOrderKept is the JSONL record +// counterpart of TestSanitizeJSONDocument_SchemaFieldsInReversedOrderKept. +func TestSanitizeJSONLines_SchemaFieldsInReversedOrderKept(t *testing.T) { + p := OutputPipeline() + for _, file := range []string{"README", "LICENSE", "Makefile", "Makefile2"} { + t.Run(file, func(t *testing.T) { + content := []byte( + `{"note":"quotes the ` + pemBegin + ` header"}` + "\n" + + `{"file":"` + file + `","category":"ssrf","severity":"critical"}` + "\n" + + `{"note":"quotes the ` + pemEnd + ` footer"}` + "\n") + + out, findings, err := SanitizeJSONLines(content, p) + require.NoError(t, err) + require.NotEmpty(t, findings) + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + require.Len(t, lines, 3, "record count must not change") + assert.Contains(t, lines[1], `"category":"ssrf"`, "a schema value is not body material") + assert.Contains(t, lines[1], `"file":"`+file+`"`, "a schema value is not body material") + assert.Contains(t, lines[1], `"severity":"critical"`, "a schema value is not body material") + assert.NotContains(t, lines[0], "PRIVATE KEY-----") + assert.NotContains(t, lines[2], "PRIVATE KEY-----") + for _, line := range lines { + assert.True(t, json.Valid([]byte(line)), "every record must stay valid JSON: %s", line) + } + }) + } +} + // TestSanitizeJSONLines_ShortBodyChunksCovered pins that a middle record holding // a body in chunks shorter than the material floor is replaced, not written back // with its body intact (#5705). From 40973ad82a106bbe285491e8028c486ebba1114f Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 3 Dec 2026 06:31:34 -0500 Subject: [PATCH 50/51] fix(#5705): redact single-character PEM body runs and keep clean JSON framing A private-key body stored one character per member or record was written back after the boundary markers were masked, because the joined-run builder dropped any leaf whose base64 run was shorter than two bytes. Track whether a run is all single-character: a one-character value now extends only an empty or all-single run, so a body split one character at a time is decided on its joined text, while an isolated single-character free-text value after a body line still keeps its content. A clean JSON document that ended in more than one newline was rewritten by the trailing-newline adjustment even though nothing changed, which contradicted the byte-for-byte guarantee. Return the document unchanged when the sanitizer produced no edits. Signed-off-by: anevans --- internal/security/jsonsanitize.go | 40 +++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index 627b4fadc5..d4af8e3ad3 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -182,6 +182,13 @@ func SanitizeJSONDocument(doc []byte, p *Pipeline) ([]byte, []Finding, error) { // JSON framing (for example a PEM block split across members) and so cannot // be mapped back to a single leaf. sanitizedOut, outputFindings := redactJSONOutput(out, p) + if bytes.Equal(sanitizedOut, body) { + // Nothing changed: hand the document back exactly as received. Running + // the trailing-newline adjustment on unchanged bytes would collapse a + // document that ends in more than one newline, rewriting a clean file + // and contradicting the byte-for-byte guarantee (#5705). + return restoreBOM(doc, body), append(findings, outputFindings...), nil + } return restoreBOM(doc, preserveTrailingNewline(sanitizedOut, body)), append(findings, outputFindings...), nil } @@ -431,6 +438,13 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { var joined []byte // bodySeeded says the current run was restarted at a recognized body line. bodySeeded := false + // allSingle says every member of the current run carried a one-character + // base64 run. A one-character value cannot be told from free text, so it + // only joins a run that is still empty or all-single: a run of many + // single-character values is a body stored one character per member and is + // decided on its joined text (pemBodyJoined), while an isolated + // single-character value following a body line stays free text (#5705). + allSingle := true flush := func() { if len(group) == 0 { bodySeeded = false @@ -444,6 +458,7 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { group = group[:0] joined = joined[:0] bodySeeded = false + allSingle = true } for pos, i := range hit { if pos == 0 || pos == len(hit)-1 { @@ -476,10 +491,18 @@ func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { bodySeeded = true } material := pemBodyRuns(valBytes) - if len(material) < 2 { + if len(material) == 0 { flush() continue } + if len(material) == 1 && !allSingle { + // A one-character value must not extend a run that already holds a + // longer member, or a lone free-text character after a body line + // would be masked. Flush and restart so a body stored one character + // per member is still decided on its own joined text. + flush() + } + allSingle = allSingle && len(material) == 1 group = append(group, i) joined = append(joined, material...) } @@ -909,6 +932,11 @@ func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { var joined []byte // bodySeeded says the current run was restarted at a recognized body line. bodySeeded := false + // allSingle is the JSONL counterpart of the single-document tracker: a + // one-character value only joins a run that is empty or all-single, so a + // body stored one character per record is reconstructed while an isolated + // one-character value after a body line stays free text (#5705). + allSingle := true flush := func() { if len(group) == 0 { bodySeeded = false @@ -922,6 +950,7 @@ func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { group = group[:0] joined = joined[:0] bodySeeded = false + allSingle = true } for i, leaf := range v.leaves { // The boundary records are already covered, and their leaves neither @@ -958,10 +987,17 @@ func (v *jsonLineView) maskMiddleRecordBody(hit []int, covered []bool) { bodySeeded = true } material := pemBodyRuns(text) - if len(material) < 2 { + if len(material) == 0 { flush() continue } + if len(material) == 1 && !allSingle { + // See maskSpanBody: a lone one-character value must not extend a run + // that already holds a longer member, or free text after a body line + // would be masked. + flush() + } + allSingle = allSingle && len(material) == 1 group = append(group, i) joined = append(joined, material...) } From a7bfefc244c85ad55517f073cfe7af15d483c2b1 Mon Sep 17 00:00:00 2001 From: anevans Date: Thu, 3 Dec 2026 06:40:05 -0500 Subject: [PATCH 51/51] chore(#5705): add review-result schema pin drift check and correct chunk docs Record the upstream repo, commit and path for the vendored review-result schema in testdata/review-result.schema.pin. scripts/check-review-schema-pin.sh compares the vendored copy with upstream at the pinned commit (semantically, so reformatting is not drift) and reports drift; its stubbed test runs in make script-test, and release.yml runs the check alongside the existing informational gate pin drift check. Correct the pemBodyRunRe and joined-run comments, and the runtime-implementation guide, to describe the all-single-character rule: a body stored one character per member is reconstructed, an isolated single-character value is kept, and a body whose one-character and longer chunks interleave is a known residual. Signed-off-by: anevans --- .github/workflows/release.yml | 10 ++ Makefile | 1 + docs/contributing/runtime-implementation.md | 10 +- internal/security/jsonsanitize.go | 25 ++- internal/security/jsonsanitize_test.go | 14 +- .../testdata/review-result.schema.pin | 10 ++ scripts/check-review-schema-pin-test.sh | 155 ++++++++++++++++++ scripts/check-review-schema-pin.sh | 71 ++++++++ 8 files changed, 282 insertions(+), 14 deletions(-) create mode 100644 internal/security/testdata/review-result.schema.pin create mode 100755 scripts/check-review-schema-pin-test.sh create mode 100755 scripts/check-review-schema-pin.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bb6b73ae0c..0b78964463 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -179,6 +179,16 @@ jobs: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: bash scripts/check-agents-gate-pin.sh + - name: Review-result schema pin drift check (informational) + # The vendored review-result schema is a test fixture, not a release + # input, so a stale pin only weakens a test. Re-vendoring is a + # maintainer decision, so this annotates the run instead of blocking + # it (scripts/check-review-schema-pin.sh). + continue-on-error: true + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: bash scripts/check-review-schema-pin.sh + recheck-tag: # Second half of the tag-move guard. validate-agents clones fullsend by # tag name — the called workflow only accepts `main` or a `v*` ref and diff --git a/Makefile b/Makefile index 6e8d860500..c40dd6ca62 100644 --- a/Makefile +++ b/Makefile @@ -199,6 +199,7 @@ script-test: $(call run-timed,bash .github/scripts/report-agent-startup-failure-test.sh) $(call run-timed,bash .github/scripts/retry-with-backoff-test.sh) $(call run-timed,bash scripts/check-agents-gate-pin-test.sh) + $(call run-timed,bash scripts/check-review-schema-pin-test.sh) $(call run-timed,bash scripts/semgrep-scan-test.sh) $(call run-timed,bash scripts/verify-release-tag-test.sh) $(call run-timed,bash skills/cutting-releases/scripts/prepend-release-highlights-test.sh) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 86231bc7a5..0b18696601 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -684,7 +684,12 @@ of a body, the values between the boundary members are also decided on their joined text: consecutive base64-only values are concatenated, and if the result looks like a body line — upper case, lower case and a base64-only character, plus a digit or a run of adjacent capitals — every value in that run is masked. That -catches a body split into short or digit-free chunks, while a run of schema values +catches a body split into short or digit-free chunks, including a body stored one +character per member: a single-character value joins only while the run is still +empty or entirely single-character, so a run of them is reconstructed while an +isolated single-character free-text value keeps its content. A body whose +one-character and longer chunks interleave is a known residual and is not +reconstructed. A run of schema values such as `critical` + `ssrf` + `Makefile` reads as concatenated words and keeps its content. An object key never joins the run — a key is structure, and letting one join a group that also holds body material renames required schema @@ -708,7 +713,8 @@ can remove its BEGIN marker. The boundary records always carry marker text, so they are always replaced; a record between them is replaced only when its leaves hold a block marker or PEM body material, decided the same way as in a single document — including the joined run of consecutive -base64-only values, which catches a body split into short or digit-free chunks. +base64-only values, which catches a body split into short or digit-free chunks and +a body stored one character per record. After the per-record pass the rebuilt stream is rescanned, but only for whole-value secrets — registered runtime values and private-key blocks, the same set the single-document path scans in its written diff --git a/internal/security/jsonsanitize.go b/internal/security/jsonsanitize.go index d4af8e3ad3..08108282fc 100644 --- a/internal/security/jsonsanitize.go +++ b/internal/security/jsonsanitize.go @@ -250,10 +250,15 @@ var privateKeyMaterialRe = regexp.MustCompile(`[A-Za-z0-9+/]{16,}=*`) // pemBodyRunRe matches a maximal run of base64 characters inside a leaf. A body // fragment can be embedded in surrounding text or line framing — "part: MIIEowIB", // or a chunk stored together with the newline that ended the line — so the runs, -// not the whole value, are what join a body. The run is kept at any length: a -// body split into one- to three-character chunks is only recognizable once the -// chunks are joined, and pemBodyJoined decides whether the joined text is key -// material or a concatenation of schema words. +// not the whole value, are what join a body. A run of two or more characters +// joins the candidate body directly. A run of exactly one character is +// ambiguous — it is as likely to be free text as a body fragment — so it joins +// only while the candidate run is still empty or entirely single-character: +// a body stored one character per member is reconstructed and decided on its +// joined text (pemBodyJoined), while an isolated single-character free-text +// value between a quoted marker pair keeps its content. A body split so that +// one-character and longer chunks alternate is not reconstructed (a known +// residual); uniform chunks and whole body lines are. var pemBodyRunRe = regexp.MustCompile(`[A-Za-z0-9+/]+=*`) // pemBodyRuns returns the base64 runs of a leaf's text concatenated, or nil when @@ -430,7 +435,12 @@ func (v *jsonProvenance) spanningPrivateKeys() privateKeySpans { // and letting one into the joined text renames required schema keys (severity, // category, file) — but it does not break the run either: the values on either // side of a key are still consecutive body chunks once the key names are ignored, -// so a body stored in separate object members is reconstructed and masked. A key +// so a body stored in separate object members is reconstructed and masked. A +// member that carries a single base64 character joins only while the run is +// empty or entirely single-character, so a body stored one character per member +// is reconstructed while an isolated single-character value keeps its content; a +// body whose one-character and longer chunks interleave is a known residual and +// is not reconstructed. A key // whose own name is a body line is masked on its own instead // (spanningPrivateKeys). func (v *jsonProvenance) maskSpanBody(hit []int, spans *privateKeySpans) { @@ -919,7 +929,10 @@ func (v *jsonLineView) spanningRecordPrivateKeys() ([]bool, []Finding) { // of maskSpanBody: consecutive candidate leaves are decided together, because a // body split so that every line is short or digit-free is only recognizable once // the lines are joined. A leaf joins a run at any length, since the joined text is -// what has to look like a body line. An object key never joins the run, since a key +// what has to look like a body line, except that a single-character leaf joins +// only while the run is empty or entirely single-character (see maskSpanBody), so +// an isolated single-character value keeps its content and a body stored one +// character per record is still reconstructed. An object key never joins the run, since a key // is structure rather than body, but it does not break the run either: a body // stored in separate object members of one record is still reconstructed. Only the // base64 runs embedded in a leaf join the run (pemBodyRuns), so line framing, a diff --git a/internal/security/jsonsanitize_test.go b/internal/security/jsonsanitize_test.go index 22bc6d515d..1a96f3c93c 100644 --- a/internal/security/jsonsanitize_test.go +++ b/internal/security/jsonsanitize_test.go @@ -1634,12 +1634,14 @@ func TestSanitizeJSONDocument_DuplicateKeyWithSecretKey(t *testing.T) { } // reviewResultSchemaPath is a pinned copy of the schema authored in -// fullsend-ai/agents (schemas/review-result.schema.json, commit -// cec09212b99fcd78bf7afc7637d8fe0b2007e109). Vendoring it ties these tests to the -// real constraints sanitization can break — the enums and patterns of the -// structural fields, additionalProperties false, and the required members — -// instead of a hand-maintained mirror that silently drifts when the upstream -// enum changes. Re-vendor and update the commit when the upstream schema changes. +// fullsend-ai/agents (schemas/review-result.schema.json). Vendoring it ties these +// tests to the real constraints sanitization can break — the enums and patterns +// of the structural fields, additionalProperties false, and the required members +// — instead of a hand-maintained mirror that silently drifts when the upstream +// enum changes. The upstream repo, commit and path are recorded in +// testdata/review-result.schema.pin; re-vendor the schema together with that pin, +// and scripts/check-review-schema-pin.sh reports when this copy drifts from +// upstream at the pinned commit. const reviewResultSchemaPath = "testdata/review-result.schema.json" // reviewResultSchema is the subset of the vendored schema the checks below use. diff --git a/internal/security/testdata/review-result.schema.pin b/internal/security/testdata/review-result.schema.pin new file mode 100644 index 0000000000..c256b91513 --- /dev/null +++ b/internal/security/testdata/review-result.schema.pin @@ -0,0 +1,10 @@ +# Pin for internal/security/testdata/review-result.schema.json. +# +# The vendored review-result schema is a test fixture copied from +# fullsend-ai/agents. Re-vendor the schema and update this pin together whenever +# the upstream schema changes. scripts/check-review-schema-pin.sh compares the +# vendored copy against upstream at the commit below and reports drift, so the +# jsonsanitize tests cannot silently validate against an outdated schema. +repo=fullsend-ai/agents +commit=cec09212b99fcd78bf7afc7637d8fe0b2007e109 +path=schemas/review-result.schema.json diff --git a/scripts/check-review-schema-pin-test.sh b/scripts/check-review-schema-pin-test.sh new file mode 100755 index 0000000000..fc17b87b04 --- /dev/null +++ b/scripts/check-review-schema-pin-test.sh @@ -0,0 +1,155 @@ +#!/usr/bin/env bash +# check-review-schema-pin-test.sh — Tests for check-review-schema-pin.sh +# +# Run from the repo root: +# bash scripts/check-review-schema-pin-test.sh + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT="${SCRIPT_DIR}/check-review-schema-pin.sh" +FAILURES=0 + +TMPDIR="$(mktemp -d)" +trap 'rm -rf "${TMPDIR}"' EXIT + +# build_pin writes a pin file. +# $1 — commit (or "invalid") +build_pin() { + local commit="$1" + local dir + dir="$(mktemp -d "${TMPDIR}/pin.XXXXXX")" + + if [[ "${commit}" == "invalid" ]]; then + commit="not-a-sha" + fi + + cat > "${dir}/review-result.schema.pin" < "${dir}/review-result.schema.json" + echo "${dir}/review-result.schema.json" +} + +# build_mock creates a mock gh that prints content for any api call. +# $1 — content file to print +# $2 — "fail" to simulate an API error (optional) +build_mock() { + local content_file="$1" + local fail_mode="${2:-}" + local mock_bin="${TMPDIR}/bin" + + rm -rf "${mock_bin}" + mkdir -p "${mock_bin}" + + cat > "${mock_bin}/gh" <&2 + exit 1 + fi + cat "${content_file}" + exit 0 +fi +echo "mock gh: unexpected command: \$*" >&2 +exit 1 +MOCKEOF + + chmod +x "${mock_bin}/gh" + echo "${mock_bin}" +} + +# run_test runs the check script and asserts exit code and output. +# $1 — test name +# $2 — expected exit code +# $3 — pin path +# $4 — schema path +# $5 — mock content file +# $6 — expected output substring (optional) +# $7 — mock fail mode (optional, "fail") +run_test() { + local name="$1" expected_exit="$2" pin="$3" schema="$4" content="$5" + local expected_output="${6:-}" fail_mode="${7:-}" + + local mock_bin + mock_bin="$(build_mock "${content}" "${fail_mode}")" + + local actual_exit=0 output + output=$( + PATH="${mock_bin}:${PATH}" \ + REVIEW_SCHEMA_PIN="${pin}" \ + REVIEW_SCHEMA_PATH="${schema}" \ + GH_TOKEN="fake" \ + bash "${SCRIPT}" 2>&1 + ) || actual_exit=$? + + if [[ "${actual_exit}" -ne "${expected_exit}" ]]; then + echo "FAIL: ${name} — expected exit ${expected_exit}, got ${actual_exit}" + echo " output: ${output}" + FAILURES=$((FAILURES + 1)) + return + fi + + if [[ -n "${expected_output}" ]] && [[ "${output}" != *"${expected_output}"* ]]; then + echo "FAIL: ${name} — expected '${expected_output}' not found in output" + echo " output: ${output}" + FAILURES=$((FAILURES + 1)) + return + fi + + echo "PASS: ${name}" +} + +echo "=== check-review-schema-pin tests ===" + +VENDORED='{"title":"Review Agent Result","action":{"enum":["approve","comment"]},"required":["action"]}' + +# Upstream is the same document with different spacing and key order — no drift. +pin="$(build_pin "cec09212b99fcd78bf7afc7637d8fe0b2007e109")" +schema="$(write_schema "${VENDORED}")" +reformatted='{ + "required": ["action"], + "action": { "enum": ["approve", "comment"] }, + "title": "Review Agent Result" +}' +upstream_file="${TMPDIR}/upstream-same.json" +printf '%s' "${reformatted}" > "${upstream_file}" +run_test "upstream matches semantically" 0 "${pin}" "${schema}" "${upstream_file}" "pin is current" + +# Upstream added an enum value — drift. +upstream_drift="${TMPDIR}/upstream-drift.json" +printf '%s' '{"title":"Review Agent Result","action":{"enum":["approve","comment","request-changes"]},"required":["action"]}' > "${upstream_drift}" +run_test "upstream drift is reported" 1 "${pin}" "${schema}" "${upstream_drift}" "schema drift" + +# Missing pin file. +run_test "missing pin file" 1 "${TMPDIR}/does-not-exist.pin" "${schema}" "${upstream_file}" "pin file not found" + +# Invalid commit in the pin. +bad_pin="$(build_pin "invalid")" +run_test "invalid commit" 1 "${bad_pin}" "${schema}" "${upstream_file}" "invalid commit" + +# gh API failure. +run_test "gh api failure" 1 "${pin}" "${schema}" "${upstream_file}" "Failed to fetch" "fail" + +# Missing vendored schema. +run_test "missing vendored schema" 1 "${pin}" "${TMPDIR}/does-not-exist.json" "${upstream_file}" "Vendored review-result schema not found" + +if [[ "${FAILURES}" -ne 0 ]]; then + echo "${FAILURES} test(s) failed" + exit 1 +fi + +echo "All check-review-schema-pin tests passed" diff --git a/scripts/check-review-schema-pin.sh b/scripts/check-review-schema-pin.sh new file mode 100755 index 0000000000..f689fb74da --- /dev/null +++ b/scripts/check-review-schema-pin.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# check-review-schema-pin.sh — Report drift between the vendored review-result +# schema and the upstream copy at the pinned commit. +# +# The jsonsanitize tests validate their output against a vendored copy of +# fullsend-ai/agents schemas/review-result.schema.json. If that upstream file +# changes (a new enum value, a new required member) the tests keep passing +# against a stale copy, so this check compares the vendored file with the +# upstream content at the commit recorded in the pin file. +# +# Exits 0 when the two documents are equal as JSON (formatting and key order are +# ignored), and exits 1 on drift, an unreadable or malformed pin, or a fetch +# error. +# +# Inputs (env vars): +# REVIEW_SCHEMA_PIN — pin file (default: internal/security/testdata/review-result.schema.pin) +# REVIEW_SCHEMA_PATH — vendored schema (default: internal/security/testdata/review-result.schema.json) +# +# Requires: gh (authenticated with read access to the repo in the pin) and jq. + +set -euo pipefail + +PIN="${REVIEW_SCHEMA_PIN:-internal/security/testdata/review-result.schema.pin}" +SCHEMA="${REVIEW_SCHEMA_PATH:-internal/security/testdata/review-result.schema.json}" + +fail() { + echo "::error::${1//::/}" + exit 1 +} + +[[ -f "${PIN}" ]] || fail "Review-result schema pin file not found: ${PIN}" +[[ -f "${SCHEMA}" ]] || fail "Vendored review-result schema not found: ${SCHEMA}" + +repo="" commit="" path="" +while IFS='=' read -r key value; do + case "${key}" in + repo) repo="${value}" ;; + commit) commit="${value}" ;; + path) path="${value}" ;; + *) ;; + esac +done < <(grep -vE '^[[:space:]]*(#|$)' "${PIN}") + +[[ -n "${repo}" ]] || fail "Pin file ${PIN} has no repo=" +[[ -n "${path}" ]] || fail "Pin file ${PIN} has no path=" +[[ "${commit}" =~ ^[a-f0-9]{40}$ ]] || fail "Pin file ${PIN} has an invalid commit: ${commit:-}" + +if ! jq -e . "${SCHEMA}" >/dev/null 2>&1; then + fail "Vendored review-result schema is not valid JSON: ${SCHEMA}" +fi + +upstream="$(mktemp)" +trap 'rm -f "${upstream}"' EXIT + +if ! gh api -H "Accept: application/vnd.github.raw" \ + "repos/${repo}/contents/${path}?ref=${commit}" > "${upstream}" 2>/dev/null; then + fail "Failed to fetch ${repo}/${path} at ${commit}" +fi + +if ! jq -e . "${upstream}" >/dev/null 2>&1; then + fail "Upstream ${repo}/${path} at ${commit} is not valid JSON" +fi + +# Compare the documents semantically: a re-vendored file may be reformatted or +# have its keys reordered without drifting from upstream. +if diff <(jq -S . "${upstream}") <(jq -S . "${SCHEMA}") >/dev/null; then + echo "::notice::review-result schema pin is current: ${repo}/${path}@${commit}" + exit 0 +fi + +fail "review-result schema drift: ${SCHEMA} differs from ${repo}/${path}@${commit}; re-vendor the schema and update ${PIN}"