#!/usr/bin/env python3 """CC0: bounded LZ4 content-size controls; not a general parser or security test.""" import argparse import ctypes as C import ctypes.util import datetime import importlib.util import json import pathlib import platform import struct BASE = pathlib.Path(__file__).parent SPEC = importlib.util.spec_from_file_location("checksum_policy", BASE / "lz4-checksum-policy.py") P = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(P) F, lib = P.F, P.lib xxh_name = ctypes.util.find_library("xxhash") P.require(xxh_name is not None, "existing libxxhash required; do not install automatically") xxh = C.CDLL(xxh_name) xxh.XXH32.argtypes = [C.c_void_p, C.c_size_t, C.c_uint] xxh.XXH32.restype = C.c_uint xxh.XXH_versionNumber.restype = C.c_uint lib.LZ4F_getFrameInfo.argtypes = [C.c_void_p, C.POINTER(F.FrameInfo), C.c_void_p, C.POINTER(C.c_size_t)] lib.LZ4F_getFrameInfo.restype = C.c_size_t SIZES = {"absent": None, "zero": 0, "one": 1, "short": 8191, "exact": 8192, "long": 8193} def with_size(original, size): P.require(original[:4] == bytes.fromhex("04224d18") and original[4] == 0x74, "expected checksum-enabled one-block fixture without optional fields") P.require(size is None or (type(size) is int and 0 <= size < 2**64), "invalid declared size") if size is None: return original descriptor = bytes([original[4] | 8, original[5]]) + struct.pack("> 8) & 255 return original[:4] + descriptor + bytes([check]) + original[7:] def decode(data, expected, capacity): P.require(type(capacity) is int and 0 < capacity <= 65536, "invalid output capacity") ctx = C.c_void_p() F.checked(lib.LZ4F_createDecompressionContext(C.byref(ctx), 100)) offset, output, error, hint, calls = 0, bytearray(), None, 1, 0 try: source = C.create_string_buffer(data) count, info = C.c_size_t(len(data)), F.FrameInfo() F.checked(lib.LZ4F_getFrameInfo(ctx, C.byref(info), source, C.byref(count))) offset = header_consumed = count.value for _ in range(100): source = C.create_string_buffer(data[offset:]) count = C.c_size_t(len(data) - offset) target, size = C.create_string_buffer(capacity), C.c_size_t(capacity) hint = lib.LZ4F_decompress(ctx, target, C.byref(size), source, C.byref(count), None) calls += 1 if lib.LZ4F_isError(hint): error = lib.LZ4F_getErrorName(hint).decode() break offset += count.value output.extend(target.raw[:size.value]) P.require(len(output) <= len(expected), "fixture output budget exceeded") if hint == 0 or (count.value == 0 and size.value == 0): break else: raise ValueError("native call budget exhausted") finally: F.checked(lib.LZ4F_freeDecompressionContext(ctx)) return {"reportedContentSize": info.contentSize, "headerConsumedBytes": header_consumed, "error": error, "frameComplete": error is None and hint == 0, "inputFullyConsumed": offset == len(data), "successfulConsumedBytes": offset, "successfulCallOutputBytes": len(output), "outputSha256": F.sha(output), "exactPayload": bytes(output) == expected, "nativeCalls": calls} def run(): P.require(lib.LZ4_versionString() == b"1.9.4", "record other versions separately") rows = [] for storage in ("compressed", "stored"): original, payload, _ = P.fixture(storage) for policy, declared in SIZES.items(): data = with_size(original, declared) for capacity in (1024, 16384): result = decode(data, payload, capacity) expected_error = None if declared in (None, 0, len(payload)) else "ERROR_frameSize_wrong" P.require(result["error"] == expected_error, "unexpected size enforcement") if expected_error is None: P.require(result["frameComplete"] and result["inputFullyConsumed"] and result["exactPayload"], "clean object control failed") codec_object = result["frameComplete"] and result["inputFullyConsumed"] and result["exactPayload"] # Optional application rule: an advertised size must match trusted object metadata. header_matches = declared is None or declared == len(payload) rows.append({"id": f"{storage}/{policy}/{capacity}", "storage": storage, "sizePolicy": policy, "wireSizePresent": declared is not None, "wireContentSize": declared, "outputBufferBytes": capacity, "frameBytes": len(data), "frameSha256": F.sha(data), "blockAndFooterSha256": F.sha(data[15 if declared is not None else 7:]), "expectedPayloadSha256": F.sha(payload), **result, "codecAndObjectAccepted": codec_object, "advertisedSizeMatchesExpected": header_matches, "strictMetadataAccepted": codec_object and header_matches}) return {"schemaVersion": 1, "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), "classification": "Designed native API observations, not a corruption rate, benchmark or vulnerability claim.", "environment": {"liblz4": lib.LZ4_versionString().decode(), "libxxhashVersionNumber": xxh.XXH_versionNumber(), "python": platform.python_version(), "platform": platform.platform()}, "method": {"payloadBytes": 8192, "sizes": SIZES, "outputCapacities": [1024, 16384], "recipe": "Reuse compressed/stored checksum-policy fixtures. Insert optional uint64-LE Content Size and recompute only descriptor xxHash32 byte. Original data blocks, block checksum, EndMark and content checksum stay byte-identical.", "acceptance": "Codec completion, full consumption and exact expected payload; separate stricter caller rule compares any advertised size with trusted expected length.", "scope": "24 fresh-context cases. NULL decompression options; error-call buffers/counts excluded. Bounded buffers, not allocations from declared sizes.", "harnessSha256": F.sha(pathlib.Path(__file__).read_bytes()), "checksumHarnessSha256": F.sha((BASE / "lz4-checksum-policy.py").read_bytes()), "frameHarnessSha256": F.sha((BASE / "lz4-frame-contract.py").read_bytes())}, "observations": rows} def verify(receipt, replay): P.require(type(receipt) is dict and set(receipt) == set(replay), "receipt fields differ") for key in ("liblz4", "libxxhashVersionNumber"): P.require(type(receipt["environment"][key]) is type(replay["environment"][key]) and receipt["environment"][key] == replay["environment"][key], "library version differs") for key in ("schemaVersion", "classification", "method", "observations"): P.require(json.dumps(receipt[key], sort_keys=True, allow_nan=False) == json.dumps(replay[key], sort_keys=True, allow_nan=False), key + " differs") def main(): parser = argparse.ArgumentParser(description=__doc__) group = parser.add_mutually_exclusive_group() group.add_argument("--output", type=pathlib.Path) group.add_argument("--verify", type=pathlib.Path) args = parser.parse_args() observed = run() if args.verify: verify(json.loads(args.verify.read_text(), object_pairs_hook=P.unique_object), observed) print("Exact replay: 24 content-size controls") elif args.output: args.output.write_text(json.dumps(observed, indent=2) + "\n") print("Recorded 24 content-size controls") else: print(json.dumps(observed, indent=2)) if __name__ == "__main__": main()