#!/usr/bin/env python3 """Validate native evidence and derive a table; no expected result is measured here.""" import argparse from datetime import datetime import errno import json from pathlib import Path import probe ROOT = Path(__file__).resolve().parent M, C, I = probe.MODIFY, probe.CLOSE_WRITE, probe.IGNORED PHASES = ("configuration_events", "write_events", "close_events") # Each reader has ordered (configuration, write, close) events. EXPECTED = { "alias-replace": {"a": ([], [], [C])}, "alias-union": {"a": ([], [M], [C])}, "alias-create-guard": {"a": ([], [M], [])}, "alias-invalid-flags": {"a": ([], [M], [])}, "alias-remove-union": {"a": ([I], [], [])}, "alias-union-oneshot": {"a": ([], [M, I], [])}, "dup-drain": {"duplicate": ([], [M], []), "original": ([], [], [])}, "dup-close-original": {"duplicate": ([], [M], [])}, "separate-instances": {"a": ([], [M], []), "b": ([], [M], [C])}, "directory-outside-alias": {"a": ([], [], []), "b": ([], [M], [C])}, "directory-inside-name": {"a": ([], [M], []), "b": ([], [M], [C])}, } NAMES = {M: "MODIFY", C: "CLOSE_WRITE", I: "IGNORED"} require = probe.require def watch_info(line): pairs = [token.split(":", 1) for token in line.split() if token.partition(":")[0] in {"wd", "ino", "sdev", "mask"}] require(len(pairs) == 4, "invalid fdinfo field count") values = dict(pairs) require(set(values) == {"wd", "ino", "sdev", "mask"}, "invalid fdinfo record") return {key: int(value, 16) for key, value in values.items()} def validate_row(row): case = row["case"] require(case in EXPECTED, "unknown case") expected = EXPECTED[case] require(row["pwrite_calls"] == 1 and row["changed_bytes"] == 1, "incorrect byte accounting") require(row["before_sha256"] == probe.sha(probe.PAYLOAD), "wrong initial hash") require(row["after_sha256"] == probe.sha(b"B" + probe.PAYLOAD[1:]), "wrong final hash") before, after = row["identity_before"], row["identity_after"] require(before == after and before["path"] == before["alias"], "alias identity changed") require(before["path"]["size"] == 4096 and before["path"]["links"] == 2, "wrong payload size or hard-link count") require(row["write_via"] == ("inside/payload" if case == "directory-inside-name" else "outside/alias"), "wrong write path") calls = row["calls"] first = calls["first_add"] require(first["return"] >= 0 and first["errno"] == 0 and first["errno_name"] is None and first["requested_mask"] == M, "initial watch invalid") expected_calls = {"first_add"} second_mask = None if case.startswith("alias-"): expected_calls.add("second_add") flags = {"alias-replace": 0, "alias-union": probe.MASK_ADD, "alias-create-guard": probe.MASK_CREATE, "alias-invalid-flags": probe.MASK_ADD | probe.MASK_CREATE, "alias-remove-union": probe.MASK_ADD, "alias-union-oneshot": probe.MASK_ADD | probe.ONESHOT}[case] second_mask = C | flags elif not case.startswith("dup-"): expected_calls.add("second_add") second_mask = M | C if second_mask is not None: second = calls["second_add"] error = {"alias-create-guard": errno.EEXIST, "alias-invalid-flags": errno.EINVAL}.get(case, 0) require(second["requested_mask"] == second_mask, "wrong second mask") require(second["errno"] == error and second["errno_name"] == errno.errorcode.get(error), "wrong second-call errno") require(second["return"] == -1 if error else second["return"] >= 0, "wrong second-call return") if not error and case.startswith("alias-"): require(second["return"] == first["return"], "aliases did not share wd") if case == "alias-remove-union": expected_calls.add("remove_via_second_wd") require(calls["remove_via_second_wd"] == {"return": 0, "errno": 0, "errno_name": None}, "removal failed") require(set(calls) == expected_calls, "wrong syscall controls") require(set(row["fdinfo_after_configuration"]) == set(expected), "wrong reader set") for reader in expected: lines = row["fdinfo_after_configuration"][reader] require(len(lines) == (0 if case == "alias-remove-union" else 1), "wrong watch count") wd = calls["second_add"]["return"] if reader == "b" else first["return"] if lines: info = watch_info(lines[0]) require(info["wd"] == wd, "fdinfo watch descriptor mismatch") mask = (M | C) if reader == "b" or case in ("alias-union", "alias-union-oneshot") else M if case == "alias-replace": mask = C if case == "alias-union-oneshot": mask |= probe.ONESHOT require(info["mask"] & (M | C | probe.ONESHOT) == mask, "effective mask mismatch") if not (case.startswith("directory-") and reader == "a"): require(info["ino"] == before["path"]["inode"], "watched inode mismatch") for index, phase in enumerate(PHASES): require(set(row[phase]) == set(expected), "missing reader events") events = row[phase][reader] require([e["mask"] for e in events] == expected[reader][index], "unexpected event masks") for event in events: require(set(event) == {"wd", "mask", "cookie", "name"}, "unexpected event fields") require(event["wd"] == wd and event["cookie"] == 0, "wrong event identity") name = "payload" if case == "directory-inside-name" and reader == "a" else "" require(event["name"] == name, "wrong event name") return probe.projection(row) def validate(result): require(result["schema_version"] == 1 and result["kind"] == "native_inotify_ownership_controls", "wrong capture schema") require(result["source_sha256"] == probe.sha((ROOT / "probe.py").read_bytes()), "probe changed") require(datetime.fromisoformat(result["generated_at"]).utcoffset().total_seconds() == 0, "timestamp must be UTC") require(result["cases"] == list(probe.CASES), "missing or reordered cases") require(result["quiet_wait_seconds"] == probe.QUIET_SECONDS, "wait changed") n = result["repetitions"] require(type(n) is int and n > 0 and bool(result["runs"]), "empty evidence") environment = result["environment"] require(set(environment) == {"kernel", "python", "libc", "machine"} and all(environment.values()), "missing environment") reference, total = None, 0 filesystems = [] for run in result["runs"]: require(run["directory"] and run["filesystem"], "missing mount provenance") require(len(run["observations"]) == n, "missing repetition") filesystems.append(run["filesystem"]) for repetition in run["observations"]: require([r["case"] for r in repetition] == list(probe.CASES), "incomplete case sequence") current = [validate_row(row) for row in repetition] if reference is None: reference = current require(current == reference, "behavior differs between runs") total += len(current) return {"schema_version": 1, "observations": total, "filesystems": filesystems, "environment": environment, "repetitions_per_mount": n, "source_sha256": result["source_sha256"], "cases": reference} def table(summary): lines = ["# Observed inotify ownership controls", "", "Native sequential syscalls, not a simulation or backup failure-rate estimate.", f'{summary["observations"]} case executions; {summary["repetitions_per_mount"]} repetitions per mount.', "Mount types: " + ", ".join(summary["filesystems"]) + ".", "Kernel: " + summary["environment"]["kernel"] + ".", "", "Every case changed exactly one byte of a 4096-byte file. All repetitions agreed.", "A dash means no event in the named phase, not proof of unmodified contents.", "", "| Case | Reader | Configuration | After write | After close |", "| --- | --- | --- | --- | --- |"] for case in summary["cases"]: for reader in case["events"][PHASES[0]]: fields = [", ".join(NAMES[e["mask"]] for e in case["events"][phase][reader]) or "-" for phase in PHASES] lines.append("| " + " | ".join([case["case"], reader] + fields) + " |") return "\n".join(lines) + "\n" def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("--input", type=Path, default=ROOT / "results.json") p.add_argument("--write", action="store_true") p.add_argument("--check-generated", action="store_true") args = p.parse_args() result = json.loads(args.input.read_text()) summary = validate(result) if args.write or args.check_generated: for name, value in {"summary.json": json.dumps(summary, indent=2) + "\n", "RESULTS.md": table(summary)}.items(): path = ROOT / name if args.write: path.write_text(value) else: require(path.read_text() == value, "generated mismatch: " + name) print(json.dumps({"validated_observations": summary["observations"], "filesystems": summary["filesystems"]})) if __name__ == "__main__": main()