|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +import pytest |
| 7 | + |
| 8 | +from logprivacy.cleaner import Cleaner |
| 9 | +from logprivacy.exceptions import InputLimitExceededError |
| 10 | +from logprivacy.files.operations import clean_file, scan_file |
| 11 | +from logprivacy.integrations.logging_filter import LogPrivacyFilter |
| 12 | +from logprivacy.internal.matches import _DetectedMatch |
| 13 | +from logprivacy.jsonl.streaming import _iter_lines, iter_safe_jsonl |
| 14 | +from logprivacy.policy import CleanerPolicy |
| 15 | + |
| 16 | +_MAX_LINE = 1_000_000 |
| 17 | + |
| 18 | + |
| 19 | +class _GuardedBinaryStream: |
| 20 | + def __init__(self, data: bytes) -> None: |
| 21 | + self.data = data |
| 22 | + self.position = 0 |
| 23 | + self.requested_sizes: list[int] = [] |
| 24 | + |
| 25 | + def __iter__(self): |
| 26 | + return self |
| 27 | + |
| 28 | + def __next__(self): |
| 29 | + raise AssertionError("physical lines must not be read through unbounded iteration") |
| 30 | + |
| 31 | + def readline(self, size: int = -1) -> bytes: |
| 32 | + if size < 0: |
| 33 | + raise AssertionError("readline() must always receive a finite size") |
| 34 | + self.requested_sizes.append(size) |
| 35 | + if self.position >= len(self.data): |
| 36 | + return b"" |
| 37 | + end = min(self.position + size, len(self.data)) |
| 38 | + newline = self.data.find(b"\n", self.position, end) |
| 39 | + if newline >= 0: |
| 40 | + end = newline + 1 |
| 41 | + chunk = self.data[self.position : end] |
| 42 | + self.position = end |
| 43 | + return chunk |
| 44 | + |
| 45 | + |
| 46 | +class _BlockingRule: |
| 47 | + name = "custom_block" |
| 48 | + category = "credential\nERROR forged-event" |
| 49 | + |
| 50 | + def find(self, text: str) -> tuple[_DetectedMatch, ...]: |
| 51 | + if "blocked-value" not in text: |
| 52 | + return () |
| 53 | + start = text.index("blocked-value") |
| 54 | + return ( |
| 55 | + _DetectedMatch( |
| 56 | + rule_name=self.name, |
| 57 | + category=self.category, |
| 58 | + start=start, |
| 59 | + end=start + len("blocked-value"), |
| 60 | + matched="blocked-value", |
| 61 | + reason="test blocked value", |
| 62 | + ), |
| 63 | + ) |
| 64 | + |
| 65 | + def replacement_for(self, match: _DetectedMatch, masking: object) -> str: |
| 66 | + return "[BLOCKED]" |
| 67 | + |
| 68 | + |
| 69 | +def _record(message: str) -> logging.LogRecord: |
| 70 | + return logging.LogRecord( |
| 71 | + name="security.marker", |
| 72 | + level=logging.WARNING, |
| 73 | + pathname=__file__, |
| 74 | + lineno=1, |
| 75 | + msg=message, |
| 76 | + args=(), |
| 77 | + exc_info=None, |
| 78 | + ) |
| 79 | + |
| 80 | + |
| 81 | +def test_jsonl_reader_uses_bounded_readline_and_recovers_after_oversized_line() -> None: |
| 82 | + stream = _GuardedBinaryStream(b"a" * (_MAX_LINE + 1) + b"\n" + b'{"status":"ok"}\n') |
| 83 | + |
| 84 | + lines = list(_iter_lines(stream)) |
| 85 | + |
| 86 | + assert lines[0] == (1, None, "max_line_bytes") |
| 87 | + assert lines[1] == (2, '{"status":"ok"}\n', None) |
| 88 | + assert stream.requested_sizes |
| 89 | + assert max(stream.requested_sizes) <= _MAX_LINE + 1 |
| 90 | + |
| 91 | + |
| 92 | +def test_iter_safe_jsonl_can_replace_an_oversized_line_and_continue() -> None: |
| 93 | + stream = _GuardedBinaryStream(b"a" * (_MAX_LINE + 1) + b"\n" + b'{"status":"ok"}\n') |
| 94 | + |
| 95 | + records = list(iter_safe_jsonl(stream, on_error="placeholder")) |
| 96 | + |
| 97 | + assert records[0].line_number == 1 |
| 98 | + assert records[0].result.cleaned["_logprivacy_error"] == "max_line_bytes" |
| 99 | + assert records[1].line_number == 2 |
| 100 | + assert records[1].result.cleaned == {"status": "ok"} |
| 101 | + |
| 102 | + |
| 103 | +def test_clean_file_rejects_oversized_line_before_replacing_destination( |
| 104 | + tmp_path: Path, |
| 105 | +) -> None: |
| 106 | + source = tmp_path / "source.log" |
| 107 | + destination = tmp_path / "clean.log" |
| 108 | + source.write_bytes(b"a" * (_MAX_LINE + 1) + b"\n") |
| 109 | + destination.write_text("existing-safe-output", encoding="utf-8") |
| 110 | + |
| 111 | + with pytest.raises(InputLimitExceededError) as caught: |
| 112 | + clean_file(source, output=destination) |
| 113 | + |
| 114 | + assert caught.value.limit == "max_line_chars" |
| 115 | + assert destination.read_text(encoding="utf-8") == "existing-safe-output" |
| 116 | + |
| 117 | + |
| 118 | +def test_scan_file_marks_oversized_physical_line_incomplete(tmp_path: Path) -> None: |
| 119 | + source = tmp_path / "source.log" |
| 120 | + source.write_bytes(b"a" * (_MAX_LINE + 1) + b"\nnormal line\n") |
| 121 | + |
| 122 | + report = scan_file(source) |
| 123 | + |
| 124 | + assert report.complete is False |
| 125 | + assert report.limitations == ("max_line_chars",) |
| 126 | + |
| 127 | + |
| 128 | +def test_blocked_marker_escapes_control_characters_from_category() -> None: |
| 129 | + rule = _BlockingRule() |
| 130 | + policy = CleanerPolicy( |
| 131 | + rules=(rule,), |
| 132 | + block_categories=(rule.category,), |
| 133 | + ) |
| 134 | + record = _record("blocked-value") |
| 135 | + |
| 136 | + assert LogPrivacyFilter(cleaner=Cleaner(policy=policy)).filter(record) is True |
| 137 | + |
| 138 | + rendered = record.getMessage() |
| 139 | + assert rendered.splitlines() == [rendered] |
| 140 | + assert "\n" not in rendered |
| 141 | + assert r"\x0aERROR forged-event" in rendered |
| 142 | + assert "blocked-value" not in rendered |
| 143 | + |
| 144 | + |
| 145 | +def test_clean_file_preserves_configured_multibyte_encoding(tmp_path: Path) -> None: |
| 146 | + source = tmp_path / "source-utf16.log" |
| 147 | + destination = tmp_path / "clean-utf16.log" |
| 148 | + source.write_text("password=secret123\nstatus=ok\n", encoding="utf-16") |
| 149 | + |
| 150 | + clean_file(source, output=destination, encoding="utf-16") |
| 151 | + |
| 152 | + cleaned = destination.read_text(encoding="utf-16") |
| 153 | + assert "secret123" not in cleaned |
| 154 | + assert "password=[SECRET]" in cleaned |
| 155 | + assert "status=ok" in cleaned |
0 commit comments