|
| 1 | +"""Tests for safe subprocess usage in sync scan optimizations.""" |
| 2 | + |
| 3 | +from datetime import datetime |
| 4 | +import sys |
| 5 | + |
| 6 | +import pytest |
| 7 | + |
| 8 | +import basic_memory.sync.sync_service as sync_service_module |
| 9 | + |
| 10 | + |
| 11 | +class _FakeProcess: |
| 12 | + def __init__(self, stdout: bytes, returncode: int = 0): |
| 13 | + self._stdout = stdout |
| 14 | + self.returncode = returncode |
| 15 | + |
| 16 | + async def communicate(self): |
| 17 | + return self._stdout, b"" |
| 18 | + |
| 19 | + |
| 20 | +class _FakeStream: |
| 21 | + def __init__(self, chunks: list[bytes]): |
| 22 | + self._chunks = chunks |
| 23 | + |
| 24 | + async def read(self, _limit: int = -1): |
| 25 | + if not self._chunks: |
| 26 | + return b"" |
| 27 | + return self._chunks.pop(0) |
| 28 | + |
| 29 | + |
| 30 | +class _FakeStreamingProcess: |
| 31 | + def __init__(self, stdout_chunks: list[bytes], returncode: int = 0): |
| 32 | + self.stdout = _FakeStream(stdout_chunks) |
| 33 | + self.stderr = _FakeStream([b""]) |
| 34 | + self.returncode = returncode |
| 35 | + |
| 36 | + async def wait(self): |
| 37 | + return self.returncode |
| 38 | + |
| 39 | + async def communicate(self): # pragma: no cover - failure path for the assertion below |
| 40 | + raise AssertionError("_quick_count_files must stream stdout instead of buffering it") |
| 41 | + |
| 42 | + |
| 43 | +@pytest.mark.asyncio |
| 44 | +@pytest.mark.skipif(sys.platform == "win32", reason="Windows path uses Python scan fallback") |
| 45 | +async def test_quick_count_files_uses_exec_without_shell(monkeypatch, sync_service, tmp_path): |
| 46 | + """Directory names with shell metacharacters must be passed as exec args.""" |
| 47 | + directory = tmp_path / 'project "quoted"; echo unsafe' |
| 48 | + captured_args: list[tuple[str, ...]] = [] |
| 49 | + |
| 50 | + async def fail_if_shell_called(*args, **kwargs): |
| 51 | + raise AssertionError("create_subprocess_shell must not be used") |
| 52 | + |
| 53 | + async def fake_create_subprocess_exec(*args, **kwargs): |
| 54 | + captured_args.append(args) |
| 55 | + return _FakeStreamingProcess(stdout_chunks=[b"/project/a.md\0", b"/project/b.md\0"]) |
| 56 | + |
| 57 | + monkeypatch.setattr( |
| 58 | + sync_service_module.asyncio, "create_subprocess_shell", fail_if_shell_called |
| 59 | + ) |
| 60 | + monkeypatch.setattr( |
| 61 | + sync_service_module.asyncio, |
| 62 | + "create_subprocess_exec", |
| 63 | + fake_create_subprocess_exec, |
| 64 | + ) |
| 65 | + |
| 66 | + count = await sync_service._quick_count_files(directory) |
| 67 | + |
| 68 | + assert count == 2 |
| 69 | + assert captured_args == [("find", str(directory), "-type", "f", "-print0")] |
| 70 | + |
| 71 | + |
| 72 | +@pytest.mark.asyncio |
| 73 | +@pytest.mark.skipif(sys.platform == "win32", reason="Windows path uses Python scan fallback") |
| 74 | +async def test_scan_directory_modified_since_uses_exec_without_shell( |
| 75 | + monkeypatch, |
| 76 | + sync_service, |
| 77 | + tmp_path, |
| 78 | +): |
| 79 | + """Incremental scan should pass the timestamp and directory as exec args.""" |
| 80 | + directory = tmp_path / "project $(echo unsafe)" |
| 81 | + since_timestamp = 1_700_000_000.0 |
| 82 | + since_date = datetime.fromtimestamp(since_timestamp).strftime("%Y-%m-%d %H:%M:%S") |
| 83 | + captured_args: list[tuple[str, ...]] = [] |
| 84 | + |
| 85 | + async def fail_if_shell_called(*args, **kwargs): |
| 86 | + raise AssertionError("create_subprocess_shell must not be used") |
| 87 | + |
| 88 | + async def fake_create_subprocess_exec(*args, **kwargs): |
| 89 | + captured_args.append(args) |
| 90 | + return _FakeProcess( |
| 91 | + stdout=(f"{directory / 'notes' / 'a.md'}\n{directory / 'notes' / 'b.md'}\n").encode() |
| 92 | + ) |
| 93 | + |
| 94 | + monkeypatch.setattr( |
| 95 | + sync_service_module.asyncio, "create_subprocess_shell", fail_if_shell_called |
| 96 | + ) |
| 97 | + monkeypatch.setattr( |
| 98 | + sync_service_module.asyncio, |
| 99 | + "create_subprocess_exec", |
| 100 | + fake_create_subprocess_exec, |
| 101 | + ) |
| 102 | + |
| 103 | + paths = await sync_service._scan_directory_modified_since(directory, since_timestamp) |
| 104 | + |
| 105 | + assert paths == ["notes/a.md", "notes/b.md"] |
| 106 | + assert captured_args == [ |
| 107 | + ("find", str(directory), "-type", "f", "-newermt", since_date), |
| 108 | + ] |
0 commit comments