systemd-resolved-rs 0.2.0

A compatibility-oriented reimplementation of systemd-resolved
#!/usr/bin/env python3
"""Regression tests for portable readiness certificate validation."""

from __future__ import annotations

from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import tempfile


ROOT = Path(__file__).resolve().parents[1]
VERIFIER = ROOT / "scripts" / "verify-readiness-bundle.py"


def digest(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def run(certificate: Path, *arguments: str) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        [
            sys.executable,
            str(VERIFIER),
            "--certificate",
            str(certificate),
            *arguments,
        ],
        check=False,
        capture_output=True,
        text=True,
    )


def fixture(directory: Path) -> tuple[Path, dict[str, object], Path]:
    artifacts = directory / "certificate.d" / "artifacts"
    artifacts.mkdir(parents=True)
    entries = {}
    for key, name in (
        ("binary", "systemd-resolved"),
        ("client", "resolvectl"),
        ("nss", "libnss_resolve.so.2"),
    ):
        path = artifacts / name
        path.write_bytes((key + "\n").encode())
        entries[key] = {
            "path": f"/stale/runner/{name}",
            "artifact_path": f"certificate.d/artifacts/{name}",
            "sha256": digest(path),
        }
    payload: dict[str, object] = {
        "schema": 2,
        "certified": True,
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "source_commit": "1" * 40,
        "source_tree": "2" * 40,
        "upstream_commit": "3" * 40,
        "gates": [{"name": "fixture", "status": "pass"}],
        **entries,
    }
    certificate = directory / "certificate.json"
    certificate.write_text(json.dumps(payload) + "\n", encoding="utf-8")
    return certificate, payload, artifacts / "libnss_resolve.so.2"


def main() -> None:
    with tempfile.TemporaryDirectory(prefix="readiness-bundle-test-") as name:
        certificate, payload, nss = fixture(Path(name))
        result = run(certificate, "--shell-values")
        assert result.returncode == 0, result.stderr
        assert len(result.stdout.splitlines()) == 9, result.stdout

        nss.write_bytes(b"tampered\n")
        result = run(certificate)
        assert result.returncode != 0
        assert "NSS module artifact hash mismatch" in result.stderr, result.stderr

        nss.write_bytes(b"nss\n")
        nss_entry = payload["nss"]
        assert isinstance(nss_entry, dict)
        nss_entry["artifact_path"] = "../libnss_resolve.so.2"
        certificate.write_text(json.dumps(payload) + "\n", encoding="utf-8")
        result = run(certificate)
        assert result.returncode != 0
        assert "NSS module artifact path is unsafe" in result.stderr, result.stderr

    print("readiness bundle regression tests passed")


if __name__ == "__main__":
    main()