Harden preview_log path validation and add regression test

This commit is contained in:
2026-04-17 20:37:14 +02:00
parent 5e5d7c34b2
commit 7055971163
3 changed files with 446 additions and 353 deletions

View File

@@ -592,13 +592,28 @@ class TestPreviewLog:
assert result.regex_error is not None
async def test_rejects_log_paths_outside_allowed_directories(self) -> None:
"""preview_log rejects files outside the configured safe log directories."""
req = LogPreviewRequest(
log_path="/etc/passwd",
fail_regex=r"root",
)
result = await config_service.preview_log(req)
assert result.regex_error is not None
assert "outside the allowed directory" in result.regex_error
async def test_matches_lines_in_file(self, tmp_path: Any) -> None:
"""preview_log correctly identifies matching and non-matching lines."""
log_file = tmp_path / "test.log"
log_file.write_text("FAIL login from 1.2.3.4\nOK normal line\nFAIL from 5.6.7.8\n")
req = LogPreviewRequest(log_path=str(log_file), fail_regex=r"FAIL")
result = await config_service.preview_log(req)
with patch(
"app.services.log_service._SAFE_LOG_PREFIXES",
(str(tmp_path),),
):
result = await config_service.preview_log(req)
assert result.total_lines == 3
assert result.matched_count == 2
@@ -612,7 +627,11 @@ class TestPreviewLog:
log_path=str(log_file),
fail_regex=r"from (\d+\.\d+\.\d+\.\d+)",
)
result = await config_service.preview_log(req)
with patch(
"app.services.log_service._SAFE_LOG_PREFIXES",
(str(tmp_path),),
):
result = await config_service.preview_log(req)
matched = [ln for ln in result.lines if ln.matched]
assert len(matched) == 1
@@ -624,7 +643,11 @@ class TestPreviewLog:
log_file.write_text("\n".join(f"line {i}" for i in range(500)) + "\n")
req = LogPreviewRequest(log_path=str(log_file), fail_regex=r"line", num_lines=50)
result = await config_service.preview_log(req)
with patch(
"app.services.log_service._SAFE_LOG_PREFIXES",
(str(tmp_path),),
):
result = await config_service.preview_log(req)
assert result.total_lines <= 50