from __future__ import annotations import subprocess import sys import unittest from pathlib import Path SCRIPT = Path(__file__).with_name("redact_bounded_log.py") class RedactBoundedLogTest(unittest.TestCase): def run_filter(self, source: str, limit: int = 4096) -> subprocess.CompletedProcess: return subprocess.run( [sys.executable, str(SCRIPT), "--max-output-bytes", str(limit)], input=source, text=True, capture_output=True, check=True, ) def test_redacts_json_headers_and_assignment_shapes(self) -> None: source = "\n".join( ( '{"authorization":"Bearer JSON_SECRET","ok":true}', "Authorization: Bearer HEADER_SECRET", "access_token=QUERY_SECRET&safe=value", '{"client_secret": "CLIENT_SECRET", "password":"PASSWORD_SECRET"}', ) ) result = self.run_filter(source) for secret in ( "JSON_SECRET", "HEADER_SECRET", "QUERY_SECRET", "CLIENT_SECRET", "PASSWORD_SECRET", ): self.assertNotIn(secret, result.stdout) self.assertIn('{"authorization":"","ok":true}', result.stdout) self.assertIn("access_token=&safe=value", result.stdout) def test_caps_output_without_writing_unredacted_tail(self) -> None: result = self.run_filter("safe-line\n" * 1000 + "token=TAIL_SECRET\n", limit=256) self.assertLessEqual(len(result.stdout.encode("utf-8")), 256) self.assertIn("[log output truncated by byte limit]", result.stdout) self.assertNotIn("TAIL_SECRET", result.stdout) self.assertIn("truncated=true", result.stderr) if __name__ == "__main__": unittest.main()