"""Observe rsync append selection on disposable synthetic files only.""" import argparse from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import platform import re import shutil import subprocess import tempfile SOURCE = hashlib.shake_256(b"hesela-rsync-append-v1").digest(16384) MTIME_NS = 1700000000000000000 FIXTURES = ("short-correct-prefix", "short-wrong-prefix", "equal-wrong-same-time", "equal-wrong-different-time", "longer-correct-prefix") POLICIES = { "append": ["--append"], "append-verify": ["--append-verify"], "append-verify-checksum": ["--append-verify", "--checksum"], "checksum": ["--checksum"], "quick-check": [], "append-verify-ignore-times": ["--append-verify", "--ignore-times"], } SOURCES = [ "https://download.samba.org/pub/rsync/rsync.1.html", "https://github.com/RsyncProject/rsync/blob/v3.2.7/rsync.1.md", "https://github.com/RsyncProject/rsync/blob/v3.2.7/generator.c", "https://github.com/RsyncProject/rsync/blob/v3.2.7/receiver.c", ] def require(condition, message): if not condition: raise ValueError(message) def digest(data): return hashlib.sha256(data).hexdigest() def initial_bytes(fixture): if fixture == "short-correct-prefix": return SOURCE[:8192] if fixture == "short-wrong-prefix": return bytes([SOURCE[0] ^ 1]) + SOURCE[1:8192] if fixture.startswith("equal-wrong-"): return bytes([SOURCE[0] ^ 1]) + SOURCE[1:] if fixture == "longer-correct-prefix": return SOURCE + b"X" * 8192 raise ValueError("Unknown fixture: " + fixture) def expected_bytes(fixture, policy): before = initial_bytes(fixture) if policy == "checksum" or (policy == "quick-check" and fixture != "equal-wrong-same-time"): return SOURCE if fixture.startswith("short-"): if policy == "append": return before + SOURCE[len(before):] return SOURCE return before def snapshot(path): data = path.read_bytes() stat = path.stat() n = min(len(data), len(SOURCE)) return {"bytes": len(data), "sha256": digest(data), "mtimeNs": stat.st_mtime_ns, "equalsSource": data == SOURCE, "matchesSourcePrefix": data[:n] == SOURCE[:n]} def validate(record): require(type(record["schemaVersion"]) is int and record["schemaVersion"] == 2, "Wrong evidence schema") require(record["id"] == "rsync-append-selection", "Wrong evidence identity") require(record["evidenceType"] == "Measured software behavior on constructed fixtures", "Wrong evidence type") require(record["method"] == method(), "Method/fixture mismatch") require(record["sources"] == SOURCES, "Source provenance mismatch") require(record["scriptSha256"] == digest(Path(__file__).read_bytes()), "Script provenance mismatch") generated = datetime.fromisoformat(record["generatedAt"]) require(generated.utcoffset() is not None, "Timestamp needs a timezone") environment = record["environment"] for field in ("python", "os", "filesystemReportedType"): require(isinstance(environment[field], str) and bool(environment[field].strip()), "Missing environment field: " + field) require(re.fullmatch(r"[0-9a-f]{64}", environment["binarySha256"]) is not None, "Invalid binary digest") require(environment["rsyncVersion"].startswith("rsync version "), "Missing rsync identity") expected_ids = {(f, p) for f in FIXTURES for p in POLICIES} require(len(record["cases"]) == len(expected_ids), "Wrong case count") require({(r["fixture"], r["policy"]) for r in record["cases"]} == expected_ids, "Missing or duplicate case") for row in record["cases"]: fixture, policy = row["fixture"], row["policy"] before, after = initial_bytes(fixture), expected_bytes(fixture, policy) require(type(row["returncode"]) is int and row["returncode"] == 0, "Unexpected rsync exit") require(isinstance(row["stdout"], str) and isinstance(row["stderr"], str), "Missing command output") require(row["sourceUnchanged"] is True, "Source changed") require(row["fullByteOraclePassed"] is True, "Byte oracle failed") for label, data in (("before", before), ("after", after)): observed = row[label] require(observed["bytes"] == len(data), label + " size mismatch") require(observed["sha256"] == digest(data), label + " digest mismatch") require(observed["equalsSource"] is (data == SOURCE), label + " equality mismatch") n = min(len(data), len(SOURCE)) require(observed["matchesSourcePrefix"] is (data[:n] == SOURCE[:n]), label + " prefix mismatch") expected_command = ["rsync", "-ti", "--no-whole-file", "--out-format=%i %n", *POLICIES[policy], "--", "source.bin", "destination.bin"] require(row["command"] == expected_command, "Command/label mismatch") expected_time = MTIME_NS - (10000000000 if fixture.endswith("different-time") else 0) require(row["before"]["mtimeNs"] == expected_time, "Wrong fixture mtime") after_time = expected_time if policy.startswith("append") and not fixture.startswith("short-") else MTIME_NS require(row["after"]["mtimeNs"] == after_time, "Wrong final mtime") def method(): return {"sourceBytes": len(SOURCE), "sourceSha256": digest(SOURCE), "sourceRecipe": "SHAKE-256 of ASCII hesela-rsync-append-v1; 16384 output bytes", "caseCount": len(FIXTURES) * len(POLICIES), "transport": "local, --no-whole-file", "sourceState": "quiescent before, during and after copying", "verification": "full byte equality, not only rsync status or hashes", "seed": None, "mtimeNs": MTIME_NS, "environmentControl": "LC_ALL=C; empty HOME; RSYNC_* variables removed"} def observe(): binary = shutil.which("rsync") if not binary: raise RuntimeError("rsync must already be installed") binary = str(Path(binary).resolve()) environment = {k: v for k, v in os.environ.items() if not k.startswith("RSYNC_")} environment["LC_ALL"] = "C" cases = [] with tempfile.TemporaryDirectory(prefix="hesela-rsync-append-") as temporary: root = Path(temporary) # An empty HOME isolates optional per-user popt aliases. home = root / "home" home.mkdir() environment["HOME"] = str(home) version = subprocess.run([binary, "--version"], env=environment, check=True, capture_output=True, text=True, timeout=15).stdout for fixture in FIXTURES: for policy, options in POLICIES.items(): directory = root / (fixture + "-" + policy) directory.mkdir() source, target = directory / "source.bin", directory / "destination.bin" source.write_bytes(SOURCE) target.write_bytes(initial_bytes(fixture)) os.utime(source, ns=(MTIME_NS, MTIME_NS)) target_time = MTIME_NS - (10000000000 if fixture.endswith("different-time") else 0) os.utime(target, ns=(target_time, target_time)) source_before, before = snapshot(source), snapshot(target) command = [binary, "-ti", "--no-whole-file", "--out-format=%i %n", *options, "--", "source.bin", "destination.bin"] result = subprocess.run(command, cwd=directory, env=environment, capture_output=True, text=True, timeout=15) after = snapshot(target) correct = target.read_bytes() == expected_bytes(fixture, policy) require(correct, "Unexpected full payload: " + fixture + "/" + policy) cases.append({ "fixture": fixture, "policy": policy, "command": ["rsync", *command[1:]], "returncode": result.returncode, "stdout": result.stdout, "stderr": result.stderr, "before": before, "after": after, "sourceUnchanged": snapshot(source) == source_before, "fullByteOraclePassed": correct, }) filesystem = subprocess.run(["stat", "-f", "-c", "%T", temporary], capture_output=True, text=True, check=True).stdout.strip() record = { "schemaVersion": 2, "id": "rsync-append-selection", "generatedAt": datetime.now(timezone.utc).isoformat(), "evidenceType": "Measured software behavior on constructed fixtures", "scriptSha256": digest(Path(__file__).read_bytes()), "environment": {"python": platform.python_version(), "os": platform.platform(), "rsyncVersion": version, "binarySha256": digest(Path(binary).read_bytes()), "filesystemReportedType": filesystem}, "method": method(), "limits": [ "One installed Linux rsync build, identified rather than recommended.", "No network, concurrent writer, interruption, hard link or application restore.", "OS-visible reads do not establish cold-media integrity or power-loss durability.", "Constructed counterexamples do not estimate a production failure rate.", "No adversarial checksum-collision test or cryptographic authentication claim.", ], "sources": SOURCES, "cases": cases, } validate(record) return record def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() # Refuse existing paths before work; exclusive creation also closes the race. if args.output.exists() or args.output.is_symlink(): parser.error("output already exists") record = observe() with args.output.open("x", encoding="utf-8") as output: json.dump(record, output, indent=2) output.write("\n") print("Validated", len(record["cases"]), "cases; output:", args.output) if __name__ == "__main__": main()