Files
dxdesigner-part-replacement/tests/trial_task_center/test_evidence.py
T

234 lines
8.8 KiB
Python

from __future__ import annotations
import hashlib
import json
import os
from pathlib import Path
import subprocess
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
import dx_productivity.trial_task_center.evidence as evidence_module
from dx_productivity.trial_task_center.evidence import capture_profile, profile_stamp
FIXTURES = Path(__file__).parents[1] / "fixtures" / "trial_task_center"
def _copy_fixture(name: str, destination: Path) -> bytes:
data = (FIXTURES / name).read_bytes()
destination.write_bytes(data)
return data
def _directory_alias(alias: Path, target: Path) -> None:
if os.name == "nt":
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(alias), str(target)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.skip(f"junctions unavailable: {created.stderr or created.stdout}")
else:
try:
alias.symlink_to(target, target_is_directory=True)
except OSError as error:
pytest.skip(f"directory aliases unavailable: {error}")
def test_profile_stamp_returns_exact_hash_for_a_stable_snapshot(tmp_path: Path) -> None:
source = tmp_path / "profile.json"
data = _copy_fixture("profile-before.json", source)
stamp = profile_stamp(source)
assert stamp is not None
assert stamp.size == len(data)
assert stamp.sha256 == hashlib.sha256(data).hexdigest()
assert stamp.modified_ns == source.stat().st_mtime_ns
assert profile_stamp(tmp_path / "missing.json") is None
@pytest.mark.parametrize(
("contents", "code"),
(
(b"{", "profile_json"),
(b'{"format_version": 1, "format_version": 1}', "profile_duplicate_key"),
(b'{"format_version": 2, "project": {"identity": "C:/Projects/Board.prj"}}', "profile_version"),
(b'{"format_version": 1, "project": {"identity": "C:/Other/Board.prj"}}', "profile_project"),
),
)
def test_capture_profile_rejects_untrustworthy_probe_output(
tmp_path: Path, contents: bytes, code: str
) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "captured.json"
source.write_bytes(contents)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == code
assert not destination.exists()
def test_capture_profile_requires_new_evidence_and_publishes_exact_bytes_atomically(tmp_path: Path) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "captured.json"
original = _copy_fixture("profile-before.json", source)
previous = profile_stamp(source)
assert previous is not None
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), previous)
assert raised.value.code == "profile_unchanged"
updated = json.loads(original)
updated["capture"] = "after operator action"
data = json.dumps(updated, sort_keys=True, separators=(",", ":")).encode("utf-8")
source.write_bytes(data)
os.utime(source, ns=(previous.modified_ns + 1, previous.modified_ns + 1))
captured = capture_profile(source, destination, Path("c:\\projects\\board.prj"), previous)
assert captured.source == source
assert captured.destination == destination
assert captured.project_identity == "C:/Projects/Board.PRJ"
assert captured.stamp.sha256 == hashlib.sha256(data).hexdigest()
assert destination.read_bytes() == data
assert source.read_bytes() == data
assert not list(tmp_path.glob(".captured.json.*"))
@pytest.mark.parametrize("constant", ("NaN", "Infinity", "-Infinity"))
def test_capture_profile_rejects_non_finite_json_constants(tmp_path: Path, constant: str) -> None:
source = tmp_path / "menu-probe.json"
source.write_bytes(
('{"format_version":1,"project":{"identity":"C:/Projects/Board.PRJ"},"value":' + constant + "}").encode("ascii")
)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, tmp_path / "captured.json", Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_json"
def test_capture_profile_accepts_a_canonical_project_alias(tmp_path: Path) -> None:
real_project = tmp_path / "projects" / "Board.prj"
alias = tmp_path / "alias" / "Board.prj"
real_project.parent.mkdir()
real_project.write_text("project", encoding="utf-8")
_directory_alias(alias.parent, real_project.parent)
source = tmp_path / "menu-probe.json"
profile = json.loads((FIXTURES / "profile-before.json").read_text(encoding="utf-8"))
profile["project"]["identity"] = str(alias)
source.write_text(json.dumps(profile), encoding="utf-8")
captured = capture_profile(source, tmp_path / "captured.json", real_project, None)
assert captured.project_identity == str(alias)
def test_capture_profile_rejects_a_reparse_destination_parent(tmp_path: Path) -> None:
source = tmp_path / "menu-probe.json"
_copy_fixture("profile-before.json", source)
target = tmp_path / "target"
target.mkdir()
alias = tmp_path / "alias"
_directory_alias(alias, target)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, alias / "captured.json", Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_publish_path"
def test_capture_profile_rejects_staged_path_hardlink_substitution(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "published" / "captured.json"
attacker = tmp_path / "attacker.json"
_copy_fixture("profile-before.json", source)
destination.parent.mkdir()
destination.write_bytes(b"previous-profile")
attacker.write_bytes(b"attacker-controlled-bytes")
def substitute(_: Path, temporary: Path) -> None:
temporary.unlink()
os.link(attacker, temporary)
monkeypatch.setattr(evidence_module, "_publication_hook", substitute, raising=False)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_publish"
assert destination.read_bytes() == b"previous-profile"
assert attacker.read_bytes() == b"attacker-controlled-bytes"
def test_capture_profile_rejects_source_destination_alias_without_mutating_source(tmp_path: Path) -> None:
source = tmp_path / "menu-probe.json"
_copy_fixture("profile-before.json", source)
before = source.stat()
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, source, Path("C:/Projects/Board.PRJ"), None)
after = source.stat()
assert raised.value.code == "profile_source_destination_alias"
assert (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) == (
before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns,
)
def test_capture_profile_rejects_hardlink_destination_alias(tmp_path: Path) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "destination.json"
_copy_fixture("profile-before.json", source)
os.link(source, destination)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_source_destination_alias"
def test_capture_profile_rejects_junction_or_symlink_destination_alias(tmp_path: Path) -> None:
source_parent = tmp_path / "source-parent"
source = source_parent / "menu-probe.json"
alias_parent = tmp_path / "alias-parent"
source_parent.mkdir()
_copy_fixture("profile-before.json", source)
_directory_alias(alias_parent, source_parent)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, alias_parent / source.name, Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_source_destination_alias"
def test_capture_profile_rejects_non_windows_publication_before_destination_write(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "not-created" / "captured.json"
original = _copy_fixture("profile-before.json", source)
before = source.stat()
monkeypatch.setattr(evidence_module, "_WINDOWS_EVIDENCE_PUBLICATION", False, raising=False)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), None)
after = source.stat()
assert raised.value.code == "unsupported_platform"
assert source.read_bytes() == original
assert (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) == (
before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns,
)
assert not destination.parent.exists()