-
Notifications
You must be signed in to change notification settings - Fork 39
fix(security): run unicode normalization before secret redaction #1178
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1335,16 +1335,17 @@ func scanRepoContextFiles(repoDir string) []security.Finding { | |
| return allFindings | ||
| } | ||
|
|
||
| // scanOutputFiles runs the secret redactor on extracted output files, | ||
| // recursively walking all subdirectories (iteration-N/output/, etc.). | ||
| // scanOutputFiles runs the output security pipeline (unicode normalization and | ||
| // secret redaction) on extracted output files, recursively walking all | ||
| // subdirectories (iteration-N/output/, etc.). | ||
| func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { | ||
| if _, err := os.Stat(outputDir); os.IsNotExist(err) { | ||
| printer.StepInfo("No output files to scan") | ||
| return nil | ||
| } | ||
|
|
||
| redactor := security.NewSecretRedactor() | ||
| redacted := 0 | ||
| pipeline := security.OutputPipeline() | ||
| findingCount := 0 | ||
| findingsPath := filepath.Join(outputDir, "security", "findings.jsonl") | ||
|
|
||
| err := filepath.WalkDir(outputDir, func(path string, d os.DirEntry, err error) error { | ||
|
|
@@ -1365,12 +1366,13 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { | |
| return nil | ||
| } | ||
|
|
||
| result := redactor.Scan(string(content)) | ||
| text := string(content) | ||
| result := pipeline.Scan(text) | ||
| if len(result.Findings) > 0 { | ||
| redacted += len(result.Findings) | ||
| findingCount += len(result.Findings) | ||
| relPath, _ := filepath.Rel(outputDir, path) | ||
| for _, f := range result.Findings { | ||
| printer.StepWarn(fmt.Sprintf("Redacted [%s] in %s: %s", f.Name, relPath, f.Detail)) | ||
| printer.StepWarn(fmt.Sprintf("Sanitized [%s] in %s: %s", f.Name, relPath, f.Detail)) | ||
| security.AppendFinding(findingsPath, | ||
| security.TracedFinding{ | ||
| TraceID: traceID, | ||
|
|
@@ -1379,8 +1381,12 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { | |
| Finding: f, | ||
| }) | ||
| } | ||
| if writeErr := os.WriteFile(path, []byte(result.Sanitized), 0o644); writeErr != nil { | ||
| printer.StepWarn(fmt.Sprintf("Could not write redacted %s: %v", relPath, writeErr)) | ||
| out := result.Sanitized | ||
| if out == "" { | ||
| out = text | ||
|
Comment on lines
1383
to
+1386
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [MEDIUM] Empty-string fallback can bypass sanitization (6/8 review agents flagged this) When The practical security impact is low (requires input with ONLY invisible characters — no secrets to leak), but it's a semantic bug in the Suggestion: Guard on findings count: out := result.Sanitized
if out == "" && len(result.Findings) > 0 {
// Pipeline stripped everything — don't revert to original
printer.StepWarn(fmt.Sprintf("Sanitized output empty despite %d finding(s) in %s", len(result.Findings), relPath))
}
if out == "" && len(result.Findings) == 0 {
out = text
}Or better, add a |
||
| } | ||
| if writeErr := os.WriteFile(path, []byte(out), 0o644); writeErr != nil { | ||
| printer.StepWarn(fmt.Sprintf("Could not write sanitized %s: %v", relPath, writeErr)) | ||
| } | ||
| } | ||
| return nil | ||
|
|
@@ -1389,10 +1395,10 @@ func scanOutputFiles(outputDir, traceID string, printer *ui.Printer) error { | |
| return err | ||
| } | ||
|
|
||
| if redacted > 0 { | ||
| printer.StepWarn(fmt.Sprintf("Redacted %d secret(s) from output files", redacted)) | ||
| if findingCount > 0 { | ||
| printer.StepWarn(fmt.Sprintf("Sanitized %d finding(s) in output files", findingCount)) | ||
| } else { | ||
| printer.StepDone("Output files clean — no secrets found") | ||
| printer.StepDone("Output files clean — no issues found") | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| #!/usr/bin/env python3 | ||
| """Integration tests for post-tool hook chain ordering (unicode before secret redact).""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import subprocess | ||
| import sys | ||
| import unittest | ||
| from pathlib import Path | ||
|
|
||
| HOOKS_DIR = Path(__file__).parent | ||
| UNICODE_HOOK = str(HOOKS_DIR / "unicode_posttool.py") | ||
| SECRET_HOOK = str(HOOKS_DIR / "secret_redact_posttool.py") | ||
|
|
||
| PLAIN_PAT = "ghp_FAKEtesttoken000000000000000000000000" | ||
|
|
||
|
|
||
| def obfuscate_with_char(text: str, char: str) -> str: | ||
| """Insert invisible character between each codepoint.""" | ||
| return char.join(text) | ||
|
|
||
|
|
||
| def run_hook(script: str, tool_result: str) -> tuple[int, str, str]: | ||
| proc = subprocess.run( | ||
| [sys.executable, script], | ||
| input=json.dumps({"tool_name": "Read", "tool_result": tool_result}), | ||
| capture_output=True, | ||
| text=True, | ||
| timeout=10, | ||
| ) | ||
| return proc.returncode, proc.stdout, proc.stderr | ||
|
|
||
|
|
||
| def run_chain(tool_result: str) -> str: | ||
| """Run unicode_posttool then secret_redact_posttool (correct sandbox order).""" | ||
| rc, stdout, stderr = run_hook(UNICODE_HOOK, tool_result) | ||
| if rc != 0: | ||
| raise RuntimeError(f"unicode hook failed: rc={rc}, stderr={stderr}") | ||
| if stdout.strip(): | ||
| out = json.loads(stdout) | ||
| tool_result = out["tool_result"] | ||
|
|
||
| rc, stdout, stderr = run_hook(SECRET_HOOK, tool_result) | ||
| if rc != 0: | ||
| raise RuntimeError(f"secret_redact hook failed: rc={rc}, stderr={stderr}") | ||
| if stdout.strip(): | ||
| out = json.loads(stdout) | ||
| return out["tool_result"] | ||
| return tool_result | ||
|
|
||
|
|
||
| class TestPostToolChain(unittest.TestCase): | ||
| def test_plain_pat_redacted_by_chain(self): | ||
| result = run_chain(PLAIN_PAT) | ||
| self.assertNotIn("ghp_FAKEtest", result) | ||
| self.assertIn("...", result) | ||
|
|
||
| def test_zero_width_obfuscated_pat_redacted_by_chain(self): | ||
| obfuscated = obfuscate_with_char(PLAIN_PAT, "\u200c") | ||
| result = run_chain(obfuscated) | ||
| self.assertNotIn("ghp_FAKEtest", result) | ||
| self.assertIn("...", result) | ||
|
|
||
| def test_ltr_mark_obfuscated_pat_redacted_by_chain(self): | ||
| obfuscated = obfuscate_with_char(PLAIN_PAT, "\u200e") | ||
| result = run_chain(obfuscated) | ||
| self.assertNotIn("ghp_FAKEtest", result) | ||
| self.assertIn("...", result) | ||
|
|
||
| def test_redact_alone_misses_zero_width_obfuscated_pat(self): | ||
| obfuscated = obfuscate_with_char(PLAIN_PAT, "\u200c") | ||
| rc, stdout, _ = run_hook(SECRET_HOOK, obfuscated) | ||
| self.assertEqual(rc, 0) | ||
| # secret_redact alone does not modify output when regex cannot match | ||
| self.assertEqual(stdout.strip(), "") | ||
| # Obfuscated token still present in source (would leak after unicode strips ZWNJ) | ||
| self.assertIn("\u200c", obfuscated) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -228,6 +228,36 @@ func TestPipeline(t *testing.T) { | |
| assert.NotContains(t, r.Sanitized, "ghp_FAKEtest") | ||
| }) | ||
|
|
||
| t.Run("normalize then redact catches zero-width obfuscated PAT", func(t *testing.T) { | ||
| p := NewPipeline(NewUnicodeNormalizer(), NewSecretRedactor()) | ||
| plain := "ghp_FAKEtesttoken000000000000000000000000" | ||
| var obfuscated strings.Builder | ||
| for _, r := range plain { | ||
| obfuscated.WriteRune(r) | ||
| obfuscated.WriteRune('\u200c') | ||
| } | ||
| r := p.Scan(obfuscated.String()) | ||
| assert.False(t, r.Safe) | ||
| assert.True(t, hasFinding(r, "zero_width")) | ||
| assert.True(t, hasFinding(r, "github_pat")) | ||
| assert.NotContains(t, r.Sanitized, "ghp_FAKEtest") | ||
| }) | ||
|
|
||
| t.Run("normalize then redact catches LTR mark obfuscated PAT", func(t *testing.T) { | ||
| p := NewPipeline(NewUnicodeNormalizer(), NewSecretRedactor()) | ||
| plain := "ghp_FAKEtesttoken000000000000000000000000" | ||
| var obfuscated strings.Builder | ||
| for _, r := range plain { | ||
| obfuscated.WriteRune(r) | ||
| obfuscated.WriteRune('\u200e') | ||
| } | ||
| r := p.Scan(obfuscated.String()) | ||
| assert.False(t, r.Safe) | ||
| assert.True(t, hasFinding(r, "zero_width")) | ||
| assert.True(t, hasFinding(r, "github_pat")) | ||
| assert.NotContains(t, r.Sanitized, "ghp_FAKEtest") | ||
| }) | ||
|
|
||
| t.Run("clean text passes both", func(t *testing.T) { | ||
| p := InputPipeline() | ||
| r := p.Scan("Normal commit message fixing a null pointer bug.") | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [MEDIUM] Missing wrong-order negative test (2/8 agents flagged) These tests prove the correct pipeline order catches obfuscated tokens, but there's no test proving the wrong order ( Suggestion: t.Run("wrong order leaks zero-width obfuscated PAT", func(t *testing.T) {
p := NewPipeline(NewSecretRedactor(), NewUnicodeNormalizer())
plain := "ghp_FAKEtesttoken000000000000000000000000"
var obfuscated strings.Builder
for _, r := range plain {
obfuscated.WriteRune(r)
obfuscated.WriteRune('')
}
r := p.Scan(obfuscated.String())
// Redactor runs first, sees obfuscated token, misses it
assert.True(t, hasFinding(r, "zero_width"))
assert.False(t, hasFinding(r, "github_pat"), "wrong order must NOT catch the obfuscated token")
}) |
||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.