Spaces:
Running
Running
Sync GitHub source be65266003b1406483e36902be71bb8e6e6c49ec
Browse filesCanonical source: https://github.com/noqt/Lumi-Eggcracker/commit/be65266003b1406483e36902be71bb8e6e6c49ec
Files changed (7)
36 unmodified lines3738394041424329 unmodified lines7374757677787980108 unmodified lines189190191192193194195228 unmodified lines424425426427428429138 unmodified lines568569570571572573245 unmodified lines81982082182282382436 unmodified lines"size": 10537},"README.md": {"sha256": "a18d3c31f1987f2fa031f9f86a8e74237cb8340325ccb23d98a903a6d1c5fb50","size": 25049},"RELEASE_NOTES.md": {29 unmodified lines"size": 1494},"docs/BROKERED_OPERATOR.md": {"sha256": "ec25e416977a0b64d8df541b2308da946e14aa786b42daf28a9c1667ea8eda8e","size": 11515},"docs/DETECTION_RECEIPT_EXPORT.md": {"sha256": "a3100dd3f281f880a1cc1a34b293bc55a2a2a87702b5a482e354578954cc8fa0",108 unmodified lines"size": 4101},"index.html": {"sha256": "73350ec089b45a9239f3b8e6e5532193b662e3b411ef8816920f1045916dfe55","size": 22790},"integrations/prometheus/eggcracker.rules.yml": {228 unmodified lines"sha256": "4f22dab7aebbe43d17fb107972b28a3caec1942c022f82ab89a4cf3a775d65c9","size": 549},"src/lumi_eggcracker/brokered/linux_ipc.py": {"sha256": "6c26fd8b79f013bbbec931aa30f7c0b6c1a7de70368fcaf6121de1db39f6cff2","size": 32508138 unmodified lines"sha256": "414e36e22c6cf6f0cb1e9576c6e3cbca1929bba74c014257153284750f24202e","size": 15450},"tests/test_brokered_linux_ipc.py": {"sha256": "e5b7bec974741e97fd9c1af35b6539bb3caf982e81e76f6652ea37a3584aeb1c","size": 34985245 unmodified lines},"schema": "noqt.huggingface_manifest.v1","source_repository": "https://github.com/noqt/Lumi-Eggcracker","source_revision": "eba52968fad4f7ebf329d6f232d7854107032417","source_url": "https://github.com/noqt/Lumi-Eggcracker/commit/eba52968fad4f7ebf329d6f232d7854107032417"}36 unmodified lines3738394041424329 unmodified lines7374757677787980108 unmodified lines189190191192193194195228 unmodified lines424425426427428429430431432433138 unmodified lines572573574575576577578579580581245 unmodified lines82782882983083183236 unmodified lines"size": 10537},"README.md": {"sha256": "7690fb7783d34e793d5ade4805253d17de563fca17ad09748dde6669c23db09d","size": 25049},"RELEASE_NOTES.md": {29 unmodified lines"size": 1494},"docs/BROKERED_OPERATOR.md": {"sha256": "1fea0977311d62937936c3ea122abd23111c5f03115bcb0191f097eb266d514e","size": 13700},"docs/DETECTION_RECEIPT_EXPORT.md": {"sha256": "a3100dd3f281f880a1cc1a34b293bc55a2a2a87702b5a482e354578954cc8fa0",108 unmodified lines"size": 4101},"index.html": {"sha256": "e079727522e20ab833db71426d7014ffee3d32e78531ff927ae2bd2667d5484d","size": 22790},"integrations/prometheus/eggcracker.rules.yml": {228 unmodified lines"sha256": "4f22dab7aebbe43d17fb107972b28a3caec1942c022f82ab89a4cf3a775d65c9","size": 549},"src/lumi_eggcracker/brokered/compare_detection_receipts.py": {"sha256": "81045b347b3b5e13408b3ab857c769ed0b76a290416434b948a5934686c190de","size": 18807},"src/lumi_eggcracker/brokered/linux_ipc.py": {"sha256": "6c26fd8b79f013bbbec931aa30f7c0b6c1a7de70368fcaf6121de1db39f6cff2","size": 32508138 unmodified lines"sha256": "414e36e22c6cf6f0cb1e9576c6e3cbca1929bba74c014257153284750f24202e","size": 15450},"tests/test_brokered_detection_receipt_comparison.py": {"sha256": "7efdf0e8ec4001ddc03d4d06ccc20801ee8b8b26f3bccc3095a86f9cc204660b","size": 12517},"tests/test_brokered_linux_ipc.py": {"sha256": "e5b7bec974741e97fd9c1af35b6539bb3caf982e81e76f6652ea37a3584aeb1c","size": 34985245 unmodified lines},"schema": "noqt.huggingface_manifest.v1","source_repository": "https://github.com/noqt/Lumi-Eggcracker","source_revision": "be65266003b1406483e36902be71bb8e6e6c49ec","source_url": "https://github.com/noqt/Lumi-Eggcracker/commit/be65266003b1406483e36902be71bb8e6e6c49ec"}
123456757 unmodified lines65666768697071{"manifest": "HUGGINGFACE_MANIFEST.json","manifest_sha256": "82ad3e95cc6ca1661fc9c09a3b85489d384d8f831c15f03eb957e80ffea005b9","mirrored_files": 189,"mode": "DERIVED_READ_ONLY_MIRROR","release_reference": {"assets": [57 unmodified lines},"schema": "noqt.huggingface_sync.v1","source_repository": "https://github.com/noqt/Lumi-Eggcracker","source_revision": "eba52968fad4f7ebf329d6f232d7854107032417","source_url": "https://github.com/noqt/Lumi-Eggcracker/commit/eba52968fad4f7ebf329d6f232d7854107032417","target": "https://huggingface.co/spaces/noqt/eggcracker"}123456757 unmodified lines65666768697071{"manifest": "HUGGINGFACE_MANIFEST.json","manifest_sha256": "fdeb610dbf0ef60b47c494232a7b331dcd41e8dd75f6347e2953ce1341c760dc","mirrored_files": 191,"mode": "DERIVED_READ_ONLY_MIRROR","release_reference": {"assets": [57 unmodified lines},"schema": "noqt.huggingface_sync.v1","source_repository": "https://github.com/noqt/Lumi-Eggcracker","source_revision": "be65266003b1406483e36902be71bb8e6e6c49ec","source_url": "https://github.com/noqt/Lumi-Eggcracker/commit/be65266003b1406483e36902be71bb8e6e6c49ec","target": "https://huggingface.co/spaces/noqt/eggcracker"}
10 unmodified lines1112131415161710 unmodified lines---> Official noqt Hugging Face distribution, generated from GitHub commit> [`eba52968fad4`](https://github.com/noqt/Lumi-Eggcracker/commit/eba52968fad4f7ebf329d6f232d7854107032417). This Space distributes the source for> discovery and cloning; Eggcracker itself runs on a supported native Linux> host, not on Hugging Face. A snapshot is called current only after the> release-linked sync job verifies its returned Hub commit and full manifest.10 unmodified lines1112131415161710 unmodified lines---> Official noqt Hugging Face distribution, generated from GitHub commit> [`be65266003b1`](https://github.com/noqt/Lumi-Eggcracker/commit/be65266003b1406483e36902be71bb8e6e6c49ec). This Space distributes the source for> discovery and cloning; Eggcracker itself runs on a supported native Linux> host, not on Hugging Face. A snapshot is called current only after the> release-linked sync job verifies its returned Hub commit and full manifest.
200 unmodified lines201202203200 unmodified linestermination is unsupported. The wall-clock expiry depends on the trustedservice's local clock. Do not use a synthetic receipt as evidence that a realprocess was admitted, dispatched, stopped, contained, or verified empty.200 unmodified lines201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241200 unmodified linestermination is unsupported. The wall-clock expiry depends on the trustedservice's local clock. Do not use a synthetic receipt as evidence that a realprocess was admitted, dispatched, stopped, contained, or verified empty.## Offline comparison of redacted detection exportsFor a before/after review, the standard-library comparator accepts exactly twoexplicit redacted exports and writes one bounded JSON object to stdout:```shpython -B src/lumi_eggcracker/brokered/compare_detection_receipts.py \--before ./detection-receipt-export-before.json \--after ./detection-receipt-export-after.json```Each input must be a normal, regular file no larger than the export ceiling of8 KiB. Parent directories must not contain symbolic links or Windows reparsepoints. The comparator does not discover files, read raw receipts, import adetector or containment runtime, create an output file, modify either input,upload data, or contact a service. It rejects malformed, duplicate-key,nonfinite, oversized, too-deep, and extra-field JSON with a fixed diagnosticthat does not echo a supplied path, field, value, or operating-system error.The stdout allowlist reports the recorded source commit, version, cataloguehash, detector profile, and result for each side, plus fixed change labels. A`TERMINATED` to `CONTAINMENT_FAILED` transition is reported explicitly; anunchanged result is reported as `UNCHANGED`. Both the input exports and thecomparison are labelled `NOT_AUTHENTICATED`, and live verification,independent observation, native qualification, and performance evidence are`NOT_PERFORMED`. The output describes recorded redacted data only; it is not alive-safety, native-qualification, independent-use, or performance claim.Timing is `UNAVAILABLE` when either export has no recorded timing, including afailure export, and is never represented as zero. It is `INCOMPARABLE` whenthe recorded source, version, catalogue, profile, trigger, or containmentprimitive context differs. Only when that recorded context matches does thetool show the two recorded durations and their arithmetic delta, labelled`MATCHING_RECORDED_CONTEXT_ONLY`. It uses the exported duration fields aftervalidating their internal consistency; it never subtracts absolute monotonicclock values and the exports provide no host or workload identity with whichto infer workload or performance comparability.
3 unmodified lines45678910638 unmodified lines6496506516526536546553 unmodified lines<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="description" content="Lumi Eggcracker is noqt's native Linux kill switch for unapproved supported local-AI workloads. Clone the complete source from Hugging Face."><meta name="noqt-source-revision" content="eba52968fad4f7ebf329d6f232d7854107032417"><meta name="theme-color" content="#090a0c"><title>Lumi Eggcracker — Native Linux AI kill switch</title><style>638 unmodified lines<section><div class="shell source-bar"><div><div class="source-id">SOURCE COMMIT · eba52968fad4</div><h2>Inspect every line.</h2><p>Complete source, tests, qualification documents and reproducible proof tooling are distributed in this repository.</p></div>3 unmodified lines45678910638 unmodified lines6496506516526536546553 unmodified lines<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="description" content="Lumi Eggcracker is noqt's native Linux kill switch for unapproved supported local-AI workloads. Clone the complete source from Hugging Face."><meta name="noqt-source-revision" content="be65266003b1406483e36902be71bb8e6e6c49ec"><meta name="theme-color" content="#090a0c"><title>Lumi Eggcracker — Native Linux AI kill switch</title><style>638 unmodified lines<section><div class="shell source-bar"><div><div class="source-id">SOURCE COMMIT · be65266003b1</div><h2>Inspect every line.</h2><p>Complete source, tests, qualification documents and reproducible proof tooling are distributed in this repository.</p></div>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561"""Compare two bounded, redacted detection receipt exports.
The comparator is deliberately offline. It reads exactly the two paths suppliedby its caller, validates the exporter v1 allowlist, and writes one bounded JSONcomparison to stdout. It does not import the detector, containment, broker, orany other runtime code."""
from __future__ import annotations
import argparseimport datetime as dtimport jsonimport mathimport osimport reimport statimport sysfrom pathlib import Pathfrom typing import Any
EXPORT_SCHEMA = "lumi-eggcracker.redacted-detection-receipt-export.v1"COMPARISON_SCHEMA = "lumi-eggcracker.redacted-detection-receipt-comparison.v1"RECEIPT_SCHEMA = "lumi-eggcracker.detection-receipt.v2"DETECTOR_SCHEMA = "lumi-eggcracker.detectors.v3"MAX_INPUT_BYTES = 8_192MAX_OUTPUT_BYTES = 8_192MAX_JSON_DEPTH = 64MAX_MONOTONIC_NS = (1 << 63) - 1_REPARSE_POINT = 0x400_EVENT_ID = re.compile(r"[0-9a-f]{24}\Z")_SHA256 = re.compile(r"[0-9a-f]{64}\Z")_COMMIT = re.compile(r"[0-9a-f]{40}\Z")_SEMVER = re.compile( r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)" r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?" r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?\Z")_UTC_TIMESTAMP = re.compile( r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}" r"(?:\.[0-9]{1,6})?Z\Z")_PROFILE_TRIGGER = { "content.gguf-llama": "UNAPPROVED_AI_MATCH", "content.gguf-ollama": "UNAPPROVED_OLLAMA_GGUF", "content.safetensors-pytorch": "UNAPPROVED_SAFETENSORS_PYTORCH", "content.safetensors-vllm": "UNAPPROVED_VLLM_SAFETENSORS",}_CONTAINMENT_PRIMITIVE = "pidfd-stop+cgroup.kill"_TOP_LEVEL_FIELDS = { "authentication", "export_schema", "live_verification", "receipt", "source_sha256",}_RECEIPT_FIELDS = { "catalogue_sha256", "detector", "event_id", "receipt_written_utc", "recorded_result", "schema_version", "source_commit", "trigger", "version",}_DETECTOR_FIELDS = {"catalogue_schema", "detection_path", "profile"}_TRIGGER_FIELDS = {"kind"}_EVIDENCE_FIELDS = { "empty_verified_monotonic_ns", "first_stop_monotonic_ns", "kill_write_completed_monotonic_ns", "kill_write_started_monotonic_ns", "primitive", "qualification_to_first_stop_ms", "root_populated", "surviving_pids", "trigger_to_empty_ms",}
class ComparisonError(ValueError): """A deliberately non-specific validation or filesystem failure."""
def _fail() -> None: raise ComparisonError("comparison failed")
def _pairs_without_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: result: dict[str, Any] = {} for key, value in pairs: if key in result: _fail() result[key] = value return result
def _parse_int(token: str) -> int: if len(token) > 64: _fail() return int(token)
def _parse_float(token: str) -> float: if len(token) > 128: _fail() value = float(token) if not math.isfinite(value): _fail() mantissa = token.lower().split("e", maxsplit=1)[0] if value == 0.0 and any(character in "123456789" for character in mantissa): _fail() return value
def _reject_constant(_token: str) -> None: _fail()
def _check_depth(text: str) -> None: depth = 0 quoted = False escaped = False for character in text: if quoted: if escaped: escaped = False elif character == "\\": escaped = True elif character == '"': quoted = False elif character == '"': quoted = True elif character in "[{": depth += 1 if depth > MAX_JSON_DEPTH: _fail() elif character in "]}": depth -= 1 if depth < 0: _fail() if quoted or escaped or depth: _fail()
def _decode_export(raw: bytes) -> dict[str, Any]: if type(raw) is not bytes or len(raw) > MAX_INPUT_BYTES: _fail() try: text = raw.decode("utf-8") _check_depth(text) value = json.loads( text, object_pairs_hook=_pairs_without_duplicates, parse_int=_parse_int, parse_float=_parse_float, parse_constant=_reject_constant, ) except (ComparisonError, UnicodeDecodeError, json.JSONDecodeError, OverflowError, RecursionError, TypeError, ValueError): _fail() if not isinstance(value, dict): _fail() return value
def _path_without_parent_links(value: str | os.PathLike[str]) -> Path: if not isinstance(value, (str, os.PathLike)): _fail() try: path = Path(value) if not path.is_absolute(): if path.drive: _fail() path = Path.cwd() / path if not path.anchor or any(part == ".." for part in path.parts): _fail() if path.drive.startswith(("\\\\", "//")): _fail() # Reject Windows alternate data streams and device spellings. The # comparator accepts ordinary files only; a colon is valid only in a # drive anchor, never in a path component. anchor_parts = len(Path(path.anchor).parts) if any(":" in part for part in path.parts[anchor_parts:]): _fail() if os.name == "nt": reserved = {"CON", "PRN", "AUX", "NUL"} reserved.update({f"COM{index}" for index in range(1, 10)}) reserved.update({f"LPT{index}" for index in range(1, 10)}) for part in path.parts[anchor_parts:]: stem = part.rstrip(" .").split(".", maxsplit=1)[0].upper() if stem in reserved: _fail() return path except (OSError, TypeError, ValueError): _fail()
def _link_like(info: os.stat_result) -> bool: attributes = getattr(info, "st_file_attributes", 0) return stat.S_ISLNK(info.st_mode) or bool(attributes & _REPARSE_POINT)
def _check_directory_chain(path: Path) -> None: try: anchor = Path(path.anchor) info = os.lstat(anchor) if _link_like(info) or not stat.S_ISDIR(info.st_mode): _fail() for part in path.parts[len(anchor.parts) :]: anchor = anchor / part info = os.lstat(anchor) if _link_like(info) or not stat.S_ISDIR(info.st_mode): _fail() except (OSError, ValueError): _fail()
def _identity(info: os.stat_result) -> tuple[int, int]: return info.st_dev, info.st_ino
def _read_source(path_value: str | os.PathLike[str]) -> bytes: """Read one explicit regular file with bounded, race-aware checks."""
path = _path_without_parent_links(path_value) _check_directory_chain(path.parent) descriptor: int | None = None try: before = os.lstat(path) if _link_like(before) or not stat.S_ISREG(before.st_mode): _fail() if before.st_size > MAX_INPUT_BYTES: _fail() flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) descriptor = os.open(path, flags) opened = os.fstat(descriptor) if ( not stat.S_ISREG(opened.st_mode) or _link_like(opened) or _identity(opened) != _identity(before) or opened.st_size > MAX_INPUT_BYTES ): _fail()
chunks: list[bytes] = [] remaining = MAX_INPUT_BYTES + 1 while remaining: chunk = os.read(descriptor, min(65_536, remaining)) if not chunk: break chunks.append(chunk) remaining -= len(chunk) raw = b"".join(chunks) after = os.fstat(descriptor) if ( len(raw) > MAX_INPUT_BYTES or len(raw) != opened.st_size or after.st_size != opened.st_size or after.st_mtime_ns != opened.st_mtime_ns or after.st_ctime_ns != opened.st_ctime_ns ): _fail() return raw except (ComparisonError, OSError, ValueError): _fail() finally: if descriptor is not None: try: os.close(descriptor) except OSError: pass
def _expect_keys(value: object, expected: set[str]) -> dict[str, Any]: if not isinstance(value, dict) or set(value) != expected: _fail() return value
def _required_text( parent: dict[str, Any], key: str, pattern: re.Pattern[str], *, maximum: int = 128,) -> str: value = parent.get(key) if not isinstance(value, str) or len(value) > maximum or not pattern.fullmatch(value): _fail() return value
def _required_monotonic_ns(parent: dict[str, Any], key: str) -> int: value = parent.get(key) if type(value) is not int or not 0 <= value <= MAX_MONOTONIC_NS: _fail() return value
def _required_ms(parent: dict[str, Any], key: str) -> int | float: value = parent.get(key) if type(value) not in (int, float) or not math.isfinite(value): _fail() if not 0 <= value <= MAX_MONOTONIC_NS / 1_000_000: _fail() return value
def _validate_timestamp(value: Any) -> str: if not isinstance(value, str) or not _UTC_TIMESTAMP.fullmatch(value): _fail() try: dt.datetime.fromisoformat(value) except ValueError: _fail() return value
def _validate_export(raw: bytes) -> dict[str, Any]: document = _expect_keys(_decode_export(raw), _TOP_LEVEL_FIELDS) if document["export_schema"] != EXPORT_SCHEMA: _fail() if document["authentication"] != "NOT_AUTHENTICATED": _fail() if document["live_verification"] != "NOT_PERFORMED": _fail() _required_text(document, "source_sha256", _SHA256, maximum=64)
receipt_value = document["receipt"] if not isinstance(receipt_value, dict) or not ( set(receipt_value) == _RECEIPT_FIELDS or set(receipt_value) == _RECEIPT_FIELDS | {"recorded_empty_evidence"} ): _fail() receipt = receipt_value if receipt["schema_version"] != RECEIPT_SCHEMA: _fail() _required_text(receipt, "event_id", _EVENT_ID, maximum=24) source_commit = _required_text(receipt, "source_commit", _COMMIT, maximum=40) version = _required_text(receipt, "version", _SEMVER, maximum=64) catalogue_sha256 = _required_text(receipt, "catalogue_sha256", _SHA256, maximum=64) receipt_written_utc = _validate_timestamp(receipt["receipt_written_utc"])
detector = _expect_keys(receipt["detector"], _DETECTOR_FIELDS) profile = detector["profile"] if not isinstance(profile, str) or profile not in _PROFILE_TRIGGER: _fail() if detector["detection_path"] != "CONTENT" or detector["catalogue_schema"] != DETECTOR_SCHEMA: _fail()
trigger = _expect_keys(receipt["trigger"], _TRIGGER_FIELDS) if trigger["kind"] != _PROFILE_TRIGGER[profile]: _fail()
result = receipt["recorded_result"] if result not in ("TERMINATED", "CONTAINMENT_FAILED"): _fail()
evidence: dict[str, Any] | None = None if result == "TERMINATED": # The exporter always emits all timing/empty-state fields for a # terminated result. Missing fields are invalid input, not zeroes. if set(receipt) != _RECEIPT_FIELDS | {"recorded_empty_evidence"}: _fail() evidence = _expect_keys(receipt["recorded_empty_evidence"], _EVIDENCE_FIELDS) if evidence["primitive"] != _CONTAINMENT_PRIMITIVE: _fail() if type(evidence["root_populated"]) is not int or evidence["root_populated"] != 0: _fail() if type(evidence["surviving_pids"]) is not list or evidence["surviving_pids"]: _fail()
first_stop_ns = _required_monotonic_ns(evidence, "first_stop_monotonic_ns") kill_started_ns = _required_monotonic_ns(evidence, "kill_write_started_monotonic_ns") kill_completed_ns = _required_monotonic_ns(evidence, "kill_write_completed_monotonic_ns") empty_ns = _required_monotonic_ns(evidence, "empty_verified_monotonic_ns") if not first_stop_ns <= kill_started_ns <= kill_completed_ns <= empty_ns: _fail() qualification_ms = _required_ms(evidence, "qualification_to_first_stop_ms") trigger_to_empty_ms = _required_ms(evidence, "trigger_to_empty_ms") expected_trigger_to_empty_ms = (empty_ns - first_stop_ns) / 1_000_000 if not math.isclose( trigger_to_empty_ms, expected_trigger_to_empty_ms, rel_tol=0.0, abs_tol=1e-9, ): _fail() timing = { "qualification_to_first_stop_ms": qualification_ms, "trigger_to_empty_ms": trigger_to_empty_ms, "primitive": _CONTAINMENT_PRIMITIVE, } else: # Failure exports intentionally contain neither timing nor raw error. if set(receipt) != _RECEIPT_FIELDS: _fail() timing = None
return { "source_commit": source_commit, "version": version, "catalogue_sha256": catalogue_sha256, "profile": profile, "trigger": trigger["kind"], "recorded_result": result, "receipt_written_utc": receipt_written_utc, "timing": timing, }
def _context(record: dict[str, Any]) -> tuple[str, ...]: timing = record["timing"] primitive = timing["primitive"] if timing is not None else "" return ( record["source_commit"], record["version"], record["catalogue_sha256"], record["profile"], record["trigger"], primitive, )
def _result_change(before: str, after: str) -> str: if before == after: return "UNCHANGED" if before == "TERMINATED" and after == "CONTAINMENT_FAILED": return "TERMINATED_TO_CONTAINMENT_FAILED" if before == "CONTAINMENT_FAILED" and after == "TERMINATED": return "CONTAINMENT_FAILED_TO_TERMINATED" return "CHANGED"
def _record_summary(record: dict[str, Any]) -> dict[str, str]: return { "source_commit": record["source_commit"], "version": record["version"], "catalogue_sha256": record["catalogue_sha256"], "profile": record["profile"], "recorded_result": record["recorded_result"], }
def _timing_comparison(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]: before_timing = before["timing"] after_timing = after["timing"] if before_timing is None or after_timing is None: return { "status": "UNAVAILABLE", "basis": "MISSING_RECORDED_TIMING", } if _context(before) != _context(after): return { "status": "INCOMPARABLE", "basis": "RECORDED_CONTEXT_MISMATCH", }
before_durations = { "qualification_to_first_stop_ms": before_timing["qualification_to_first_stop_ms"], "trigger_to_empty_ms": before_timing["trigger_to_empty_ms"], } after_durations = { "qualification_to_first_stop_ms": after_timing["qualification_to_first_stop_ms"], "trigger_to_empty_ms": after_timing["trigger_to_empty_ms"], } return { "status": "COMPARABLE", "basis": "MATCHING_RECORDED_CONTEXT_ONLY", "before_durations_ms": before_durations, "after_durations_ms": after_durations, "delta_ms": { "qualification_to_first_stop_ms": ( after_durations["qualification_to_first_stop_ms"] - before_durations["qualification_to_first_stop_ms"] ), "trigger_to_empty_ms": ( after_durations["trigger_to_empty_ms"] - before_durations["trigger_to_empty_ms"] ), }, }
def compare_receipts( before_path: str | os.PathLike[str], after_path: str | os.PathLike[str],) -> dict[str, Any]: """Return a fixed-field comparison of exactly two explicit exports."""
before = _validate_export(_read_source(before_path)) after = _validate_export(_read_source(after_path)) changes = { "source_commit": "UNCHANGED" if before["source_commit"] == after["source_commit"] else "CHANGED", "version": "UNCHANGED" if before["version"] == after["version"] else "CHANGED", "catalogue_sha256": ( "UNCHANGED" if before["catalogue_sha256"] == after["catalogue_sha256"] else "CHANGED" ), "profile": "UNCHANGED" if before["profile"] == after["profile"] else "CHANGED", "recorded_result": _result_change( before["recorded_result"], after["recorded_result"] ), } return { "comparison_schema": COMPARISON_SCHEMA, "authentication": "NOT_AUTHENTICATED", "live_verification": "NOT_PERFORMED", "comparison_status": "RECORDED", "comparison_basis": "RECORDED_EXPORTS_ONLY", "before": _record_summary(before), "after": _record_summary(after), "changes": changes, "timing_comparison": _timing_comparison(before, after), "native_qualification": "NOT_PERFORMED", "independent_observation": "NOT_PERFORMED", "performance_evidence": "NOT_PERFORMED", }
def _encode_output(value: dict[str, Any]) -> bytes: try: encoded = ( json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n" ).encode("utf-8") except (TypeError, ValueError, OverflowError): _fail() if len(encoded) > MAX_OUTPUT_BYTES: _fail() return encoded
class _QuietArgumentParser(argparse.ArgumentParser): def error(self, _message: str) -> None: self.print_usage(sys.stderr) self.exit(2, f"{self.prog}: invalid command line\n")
def main(argv: list[str] | None = None) -> int: parser = _QuietArgumentParser( prog="compare_detection_receipts.py", description="Compare two explicit redacted detection receipt exports.", ) parser.add_argument("--before", required=True, metavar="FILE", help="first export file") parser.add_argument("--after", required=True, metavar="FILE", help="second export file") args = parser.parse_args(argv) try: output = _encode_output(compare_receipts(args.before, args.after)) sys.stdout.write(output.decode("utf-8")) except Exception: # noqa: BLE001 - never echo untrusted input or OS error text. print("comparison failed: invalid redacted export or filesystem path", file=sys.stderr) return 1 return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313"""Focused tests for the offline redacted detection receipt comparator."""
from __future__ import annotations
import copyimport importlib.utilimport ioimport jsonimport osimport tempfileimport unittestfrom contextlib import redirect_stderr, redirect_stdoutfrom pathlib import Path
_MODULE_PATH = ( Path(__file__).parents[1] / "src" / "lumi_eggcracker" / "brokered" / "compare_detection_receipts.py")_MODULE_SPEC = importlib.util.spec_from_file_location("compare_detection_receipts", _MODULE_PATH)if _MODULE_SPEC is None or _MODULE_SPEC.loader is None: # pragma: no cover - test setup guard raise ImportError("comparison module could not be loaded")comparison = importlib.util.module_from_spec(_MODULE_SPEC)_MODULE_SPEC.loader.exec_module(comparison)
def _document( *, result: str = "TERMINATED", profile: str = "content.gguf-llama", source_commit: str = "a" * 40, version: str = "1.0.10", catalogue_sha256: str = "b" * 64, event_id: str = "0" * 24, qualification_to_first_stop_ms: float = 5.0, trigger_to_empty_ms: float = 0.25, first_stop_ns: int = 1_000_000_000, empty_ns: int = 1_000_250_000,) -> dict[str, object]: receipt: dict[str, object] = { "schema_version": comparison.RECEIPT_SCHEMA, "event_id": event_id, "source_commit": source_commit, "version": version, "catalogue_sha256": catalogue_sha256, "receipt_written_utc": "2026-10-02T00:00:00Z", "detector": { "profile": profile, "detection_path": "CONTENT", "catalogue_schema": comparison.DETECTOR_SCHEMA, }, "trigger": {"kind": comparison._PROFILE_TRIGGER[profile]}, "recorded_result": result, } if result == "TERMINATED": receipt["recorded_empty_evidence"] = { "empty_verified_monotonic_ns": empty_ns, "first_stop_monotonic_ns": first_stop_ns, "kill_write_completed_monotonic_ns": first_stop_ns + 200, "kill_write_started_monotonic_ns": first_stop_ns + 100, "primitive": comparison._CONTAINMENT_PRIMITIVE, "qualification_to_first_stop_ms": qualification_to_first_stop_ms, "root_populated": 0, "surviving_pids": [], "trigger_to_empty_ms": trigger_to_empty_ms, } return { "export_schema": comparison.EXPORT_SCHEMA, "source_sha256": "f" * 64, "authentication": "NOT_AUTHENTICATED", "live_verification": "NOT_PERFORMED", "receipt": receipt, }
def _write(path: Path, document: object, *, allow_nan: bool = False) -> None: path.write_text( json.dumps(document, sort_keys=True, separators=(",", ":"), allow_nan=allow_nan) + "\n", encoding="utf-8", )
class DetectionReceiptComparisonTests(unittest.TestCase): def setUp(self) -> None: # Leave the task-scoped fixtures in place so the guarded test runner can # preserve its bounded artifacts without deleting any repository file. self.root = Path(tempfile.mkdtemp(prefix="receipt-comparison-"))
def _write_document(self, name: str, **kwargs: object) -> Path: path = self.root / name _write(path, _document(**kwargs)) return path
@staticmethod def _run_cli(before: Path, after: Path) -> tuple[int, str, str]: stdout = io.StringIO() stderr = io.StringIO() with redirect_stdout(stdout), redirect_stderr(stderr): status = comparison.main( ["--before", str(before), "--after", str(after)] ) return status, stdout.getvalue(), stderr.getvalue()
def test_matching_recorded_context_compares_durations_without_absolute_clock_subtraction(self) -> None: before = self._write_document( "before.json", event_id="0" * 24, qualification_to_first_stop_ms=5.0, trigger_to_empty_ms=0.25, first_stop_ns=3_000_000_000, empty_ns=3_000_250_000, ) after = self._write_document( "after.json", event_id="1" * 24, qualification_to_first_stop_ms=7.0, trigger_to_empty_ms=0.5, first_stop_ns=1_000_000_000, empty_ns=1_000_500_000, )
output = comparison.compare_receipts(before, after)
self.assertEqual("RECORDED", output["comparison_status"]) self.assertEqual("NOT_AUTHENTICATED", output["authentication"]) self.assertEqual("NOT_PERFORMED", output["live_verification"]) self.assertEqual( { "source_commit": "UNCHANGED", "version": "UNCHANGED", "catalogue_sha256": "UNCHANGED", "profile": "UNCHANGED", "recorded_result": "UNCHANGED", }, output["changes"], ) self.assertEqual("COMPARABLE", output["timing_comparison"]["status"]) self.assertEqual( "MATCHING_RECORDED_CONTEXT_ONLY", output["timing_comparison"]["basis"], ) self.assertEqual( {"qualification_to_first_stop_ms": 2.0, "trigger_to_empty_ms": 0.25}, output["timing_comparison"]["delta_ms"], ) self.assertNotIn("monotonic", json.dumps(output).lower()) self.assertLessEqual(len(comparison._encode_output(output)), comparison.MAX_OUTPUT_BYTES)
def test_terminated_to_failure_shows_transition_and_unavailable_timing(self) -> None: before = self._write_document("before.json") after = self._write_document( "after.json", result="CONTAINMENT_FAILED", profile="content.gguf-ollama", source_commit="d" * 40, version="1.0.11", catalogue_sha256="e" * 64, event_id="2" * 24, )
output = comparison.compare_receipts(before, after)
self.assertEqual("TERMINATED_TO_CONTAINMENT_FAILED", output["changes"]["recorded_result"]) self.assertEqual("UNAVAILABLE", output["timing_comparison"]["status"]) self.assertEqual("MISSING_RECORDED_TIMING", output["timing_comparison"]["basis"]) self.assertNotIn("delta_ms", output["timing_comparison"]) self.assertEqual("CONTAINMENT_FAILED", output["after"]["recorded_result"])
def test_mismatched_recorded_context_is_incomparable_without_durations(self) -> None: before = self._write_document("before.json") after = self._write_document( "after.json", profile="content.gguf-ollama", source_commit="c" * 40, version="1.0.11", catalogue_sha256="d" * 64, event_id="3" * 24, first_stop_ns=10_000_000_000, empty_ns=10_000_100_000, trigger_to_empty_ms=0.1, )
output = comparison.compare_receipts(before, after)
self.assertEqual("CHANGED", output["changes"]["profile"]) self.assertEqual("INCOMPARABLE", output["timing_comparison"]["status"]) self.assertEqual("RECORDED_CONTEXT_MISMATCH", output["timing_comparison"]["basis"]) self.assertNotIn("before_durations_ms", output["timing_comparison"])
def test_cli_normal_files_is_stdout_only_and_uses_fixed_safe_fields(self) -> None: before = self._write_document("before.json") after = self._write_document("after.json", event_id="4" * 24) before_names = {entry.name for entry in self.root.iterdir()}
status, stdout, stderr = self._run_cli(before, after)
self.assertEqual(0, status) self.assertEqual("", stderr) parsed = json.loads(stdout) self.assertEqual(comparison.COMPARISON_SCHEMA, parsed["comparison_schema"]) self.assertEqual(before_names, {entry.name for entry in self.root.iterdir()}) self.assertNotIn(str(before), stdout) self.assertNotIn(str(after), stdout) self.assertLessEqual(len(stdout.encode("utf-8")), comparison.MAX_OUTPUT_BYTES)
def test_strict_parser_rejects_malformed_oversized_duplicate_nonfinite_deep_and_extra_fields(self) -> None: valid = self._write_document("valid.json") cases: list[tuple[str, bytes, str]] = [ ("malformed", b"{", "malformed"), ( "oversized", b"{" + (b" " * comparison.MAX_INPUT_BYTES), "oversized", ), ( "duplicate", b'{"authentication":"NOT_AUTHENTICATED","authentication":"NOT_AUTHENTICATED"}', "duplicate", ), ( "deep", (b"[" * (comparison.MAX_JSON_DEPTH + 1)) + (b"]" * (comparison.MAX_JSON_DEPTH + 1)), "deep", ), ] extra = copy.deepcopy(_document()) extra["receipt"]["detector"]["raw"] = "SENSITIVE_SHOULD_NOT_ECHO" cases.append( ( "extra", ( json.dumps(extra, sort_keys=True, separators=(",", ":")) + "\n" ).encode("utf-8"), "extra", ) ) nonfinite = copy.deepcopy(_document()) nonfinite["receipt"]["recorded_empty_evidence"]["trigger_to_empty_ms"] = float("nan") cases.append( ( "nonfinite", ( json.dumps(nonfinite, sort_keys=True, separators=(",", ":"), allow_nan=True) + "\n" ).encode("utf-8"), "nonfinite", ) )
for name, raw, _label in cases: with self.subTest(case=name): bad = self.root / f"{name}.json" bad.write_bytes(raw) status, stdout, stderr = self._run_cli(bad, valid) self.assertEqual(1, status) self.assertEqual("", stdout) self.assertEqual( "comparison failed: invalid redacted export or filesystem path\n", stderr ) self.assertNotIn(str(bad), stderr) self.assertNotIn("SENSITIVE_SHOULD_NOT_ECHO", stderr)
def test_inconsistent_timing_and_failure_evidence_are_rejected(self) -> None: inconsistent = copy.deepcopy(_document()) inconsistent["receipt"]["recorded_empty_evidence"]["trigger_to_empty_ms"] = 9.0 first = self.root / "inconsistent.json" _write(first, inconsistent) second = self._write_document("second.json") with self.assertRaises(comparison.ComparisonError): comparison.compare_receipts(first, second)
failure_with_evidence = _document(result="CONTAINMENT_FAILED") failure_with_evidence["receipt"]["recorded_empty_evidence"] = {} failure = self.root / "failure-extra-evidence.json" _write(failure, failure_with_evidence) with self.assertRaises(comparison.ComparisonError): comparison.compare_receipts(failure, second)
def test_symlink_input_is_rejected_when_platform_supports_symlinks(self) -> None: source = self._write_document("source.json") other = self._write_document("other.json", event_id="5" * 24) linked = self.root / "linked.json" try: os.symlink(source, linked) except (OSError, NotImplementedError): self.skipTest("symlink creation is unavailable on this host") with self.assertRaises(comparison.ComparisonError): comparison.compare_receipts(linked, other)
def test_cli_argument_errors_and_windows_stream_spellings_are_generic(self) -> None: source = self._write_document("source.json") stdout = io.StringIO() stderr = io.StringIO() with ( redirect_stdout(stdout), redirect_stderr(stderr), self.assertRaises(SystemExit) as raised, ): comparison.main(["--before", str(source)]) self.assertEqual(2, raised.exception.code) self.assertEqual("", stdout.getvalue()) self.assertTrue(stderr.getvalue().endswith("compare_detection_receipts.py: invalid command line\n")) self.assertNotIn(str(source), stderr.getvalue())
with self.assertRaises(comparison.ComparisonError): comparison.compare_receipts(str(source) + ":hidden-stream", source)
if __name__ == "__main__": unittest.main()HUGGINGFACE_MANIFEST.json+14-6
HUGGINGFACE_SYNC.json+4-4
README.md+1-1
docs/BROKERED_OPERATOR.md+38
index.html+2-2
src/lumi_eggcracker/brokered/compare_detection_receipts.pyAdded+561
tests/test_brokered_detection_receipt_comparison.pyAdded+313