diff --git a/docs/node-maintenance-operator.md b/docs/node-maintenance-operator.md index 20cda46..6fd864e 100644 --- a/docs/node-maintenance-operator.md +++ b/docs/node-maintenance-operator.md @@ -441,3 +441,20 @@ reset or replacement. Repairs already reachable from the audited default branch do not block later publication. Upgrade and legacy proposals keep their existing publication behavior. Complete live repair acceptance remains required before general rollout. + + +## History storage bounds + +New audit and repair artifacts use storage v2: identical audit objects, repeated +strings and dependency-path prefixes are stored once inside the same artifact. +The reader still accepts existing v1 artifacts. Both formats reconstruct the +same complete logical history, including every attempt, historical field value, +path string, duplicate and ordering. No old artifact or native receipt is rewritten. + +The report stays bounded at 1 MiB; normal audit history retains its 512 KiB +encoded bound. The v2 reader checks backward-only references and computes complete +expansion costs before allocating historical containers. It rejects histories +above 8 MiB canonical logical JSON, 200000 values/table entries or depth 64. +Repeated mutable containers are rebuilt independently. Invalid, cyclic, +noncanonical or oversized history fails preparation; it never drops old evidence +or skips producer, job, Check, artifact-digest or publication verification. diff --git a/node/runtime/history.py b/node/runtime/history.py new file mode 100644 index 0000000..80bde29 --- /dev/null +++ b/node/runtime/history.py @@ -0,0 +1,238 @@ +"""Self-contained lossless history sharing with bounded logical expansion.""" + +import base64 +import json +import re +from collections import Counter + +MAX_REPORT = 1048576 +MAX_LOGICAL = 8 * MAX_REPORT +MAX_VALUES = 200000 +MAX_DEPTH = 64 +PATTERN = re.compile(r"^$", re.M) + + +def canonical(value): + return json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False + ).encode("ascii") + + +def bounded(size, values, depth): + if size > MAX_LOGICAL or values > MAX_VALUES or depth > MAX_DEPTH: + raise ValueError("Historical evidence exceeds its logical expansion bound") + return size, values, depth + + +def pack(record): + strings = Counter() + visited = 0 + + def count(value, paths=False, depth=0): + nonlocal visited + visited += 1 + bounded(0, visited, depth + int(isinstance(value, (dict, list)))) + if isinstance(value, dict): + for key, child in value.items(): + if not isinstance(key, str): + raise ValueError("History keys must be strings") + count(child, key == "paths", depth + 1) + elif isinstance(value, list): + for child in value: + count(child, paths, depth + 1) + elif isinstance(value, str) and not paths: + strings[value] += 1 + + count(record) + bounded(len(canonical(record)), visited, 0) + objects, paths, segments, shared = [], [], [], [] + object_ids, path_ids, segment_ids, string_ids = {}, {}, {}, {} + + def encode(value, in_paths=False): + if isinstance(value, str) and in_paths: + parent = -1 + for part in value.split(">"): + if part not in segment_ids: + segment_ids[part] = len(segments) + segments.append(part) + edge = (parent, segment_ids[part]) + if edge not in path_ids: + path_ids[edge] = len(paths) + paths.append(list(edge)) + parent = path_ids[edge] + return {"p": parent} + if ( + isinstance(value, str) + and (strings[value] - 1) * len(canonical(value)) > 12 * strings[value] + 3 + ): + if value not in string_ids: + string_ids[value] = len(shared) + shared.append(value) + return {"s": string_ids[value]} + if isinstance(value, dict): + node = {k: encode(value[k], k == "paths") for k in sorted(value)} + elif isinstance(value, list): + node = [encode(v, in_paths) for v in value] + else: + return value + key = canonical(node) + if key not in object_ids: + object_ids[key] = len(objects) + objects.append(node) + return {"r": object_ids[key]} + + root = encode(record) + if sum(map(len, (objects, paths, segments, shared))) > MAX_VALUES: + raise ValueError("History tables exceed their entry bound") + return dict( + version=2, + root=root, + objects=objects, + paths=paths, + segments=segments, + strings=shared, + ) + + +def unpack(data): + if ( + not isinstance(data, dict) + or set(data) != {"version", "root", "objects", "paths", "segments", "strings"} + or type(data["version"]) is not int + or data["version"] != 2 + ): + raise ValueError("Unsupported history storage envelope") + objects, paths, segments, strings = ( + data[k] for k in ("objects", "paths", "segments", "strings") + ) + if ( + any(not isinstance(v, list) for v in (objects, paths, segments, strings)) + or not objects + ): + raise ValueError("Invalid history tables") + if sum(map(len, (objects, paths, segments, strings))) > MAX_VALUES: + raise ValueError("History tables exceed their entry bound") + if any(not isinstance(s, str) for s in segments + strings): + raise ValueError("Invalid history string table") + + def index(value, limit): + if type(value) is not int or not 0 <= value < limit: + raise ValueError("Invalid or forward history reference") + return value + + path_sizes = [] + for i, edge in enumerate(paths): + if not isinstance(edge, list) or len(edge) != 2 or type(edge[0]) is not int: + raise ValueError("Invalid history path") + parent, segment = edge + size = len(canonical(segments[index(segment, len(segments))])) - 2 + if parent != -1: + size += path_sizes[index(parent, i)] + 1 + bounded(size + 2, 1, 0) + path_sizes.append(size) + string_sizes = [len(canonical(s)) for s in strings] + sizes = [] + + def stats(token, limit): + if isinstance(token, dict): + if len(token) != 1: + raise ValueError("Invalid history token") + kind, value = next(iter(token.items())) + if kind == "r": + return sizes[index(value, limit)] + if kind == "p": + return path_sizes[index(value, len(paths))] + 2, 1, 0 + if kind == "s": + return string_sizes[index(value, len(strings))], 1, 0 + raise ValueError("Unknown history token") + if isinstance(token, list): + raise ValueError("Inline history container") + return len(canonical(token)), 1, 0 + + # Compute complete expansion costs before building any expanded container. + for i, node in enumerate(objects): + if not isinstance(node, (dict, list)): + raise ValueError("Invalid history object") + children = [ + stats(v, i) for v in (node.values() if isinstance(node, dict) else node) + ] + keys = sum(len(canonical(k)) + 1 for k in node) if isinstance(node, dict) else 0 + sizes.append( + bounded( + 2 + max(0, len(node) - 1) + keys + sum(c[0] for c in children), + 1 + sum(c[1] for c in children), + 1 + max((c[2] for c in children), default=0), + ) + ) + if data["root"] != {"r": len(objects) - 1}: + raise ValueError("Invalid history root") + stats(data["root"], len(objects)) + + def expand(token): + if not isinstance(token, dict): + return token + kind, value = next(iter(token.items())) + if kind == "s": + return strings[value] + if kind == "p": + parts = [] + while value != -1: + value, segment = paths[value] + parts.append(segments[segment]) + return ">".join(reversed(parts)) + node = objects[value] + # Build each occurrence independently; mutable historical views cannot alias. + return ( + {k: expand(v) for k, v in node.items()} + if isinstance(node, dict) + else [expand(v) for v in node] + ) + + return expand(data["root"]) + + +def marker(record, max_encoded=MAX_REPORT): + if ( + not isinstance(record, dict) + or type(record.get("version")) is not int + or record["version"] != 1 + ): + raise ValueError("Unsupported logical history") + raw = canonical(pack(record)) + encoded = base64.b64encode(raw).decode("ascii") + if len(encoded) > max_encoded: + raise ValueError("Historical evidence exceeds its stored bound") + return f"" + + +def read(report): + def unique(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("Duplicate history field") + result[key] = value + return result + + try: + if len(report) > MAX_REPORT: + raise ValueError("Audit report exceeds its bound") + text = report.decode("utf-8") + matches = PATTERN.findall(text) + if len(matches) != 1 or text.count("node-audit-history:") != 1: + raise ValueError("Missing or ambiguous sealed audit history") + version, encoded = matches[0] + raw = base64.b64decode(encoded, validate=True) + stored = json.loads(raw, object_pairs_hook=unique) + if canonical(stored) != raw: + raise ValueError("Noncanonical history") + record = unpack(stored) if version == "2" else stored + if ( + not isinstance(record, dict) + or type(record.get("version")) is not int + or record["version"] != 1 + ): + raise ValueError("Unsupported logical history") + return record + except (RecursionError, UnicodeError, TypeError, OverflowError) as error: + raise ValueError("Malformed historical evidence") from error diff --git a/node/runtime/repair.py b/node/runtime/repair.py index 0791151..cc61225 100644 --- a/node/runtime/repair.py +++ b/node/runtime/repair.py @@ -1128,8 +1128,7 @@ def cumulative_report( "| Package | Update | Severity | Advisories | Action / blocker | Security evidence |\n| --- | --- | --- | --- | --- | --- |\n" + "\n".join(rows) ) - encoded = base64.b64encode(ENGINE["canonical_history"](record)).decode("ascii") - report += f"\n\n\n" + report += "\n\n" + ENGINE["history_marker"](record) + "\n" if len(report.encode()) > 1048576: raise ValueError("Cumulative history exceeds its bound; no artifact sealed") return report diff --git a/node/runtime/templates/dependency_audit.py b/node/runtime/templates/dependency_audit.py index 248969e..59c2413 100644 --- a/node/runtime/templates/dependency_audit.py +++ b/node/runtime/templates/dependency_audit.py @@ -1,7 +1,6 @@ """Prepare a best-effort npm or pnpm upgrade report for one standalone Node project.""" import argparse -import base64 import copy import hashlib import html @@ -23,6 +22,7 @@ LOCAL_PATCHES = runpy.run_path(str(Path(__file__).parents[1] / "local_patches.py")) NODE_RELEASES = runpy.run_path(str(Path(__file__).parents[1] / "node_releases.py")) +HISTORY = runpy.run_path(str(Path(__file__).parents[1] / "history.py")) REPAIR_CHOICES = runpy.run_path(str(Path(__file__).parents[1] / "repair_choices.py")) SEVERITY_ORDER = {"critical": 0, "high": 1, "moderate": 2, "low": 3, "info": 4} @@ -4063,10 +4063,7 @@ def published_patch_versions(specifier, *, all_versions=False): "initial_ids": sorted(initial_ids or ()), "remaining_ids": sorted(remaining_ids or ()), } - encoded = base64.b64encode(canonical_history(record)).decode("ascii") - if len(encoded) > 524288: - raise ValueError("Historical audit evidence exceeds its bound") - report += f"\n\n" + report += "\n" + history_marker(record, max_encoded=524288) + "\n" heading, separator, tail = report.partition("\n") report = ( heading.replace("Validation failed or unavailable", "Validation pending") @@ -4083,15 +4080,10 @@ def published_patch_versions(specifier, *, all_versions=False): HISTORY_TITLE = "Node audit evidence v1" -HISTORY_PATTERN = re.compile( - r"^$", re.M -) - - -def canonical_history(value): - return json.dumps( - value, sort_keys=True, separators=(",", ":"), ensure_ascii=True - ).encode("ascii") +HISTORY_PATTERN = HISTORY["PATTERN"] +canonical_history = HISTORY["canonical"] +history_marker = HISTORY["marker"] +history_record = HISTORY["read"] def dependency_state(snapshot): @@ -4101,33 +4093,6 @@ def dependency_state(snapshot): } -def history_record(report): - def unique(pairs): - result = {} - for key, value in pairs: - if key in result: - raise ValueError("Duplicate history field") - result[key] = value - return result - - if len(report) > 1048576: - raise ValueError("Audit report exceeds its bound") - text = report.decode("utf-8") - matches = HISTORY_PATTERN.findall(text) - if len(matches) != 1 or text.count("node-audit-history:") != 1: - raise ValueError("Missing or ambiguous sealed audit history") - raw = base64.b64decode(matches[0], validate=True) - record = json.loads(raw, object_pairs_hook=unique) - if ( - canonical_history(record) != raw - or not isinstance(record, dict) - or type(record.get("version")) is not int - or record["version"] != 1 - ): - raise ValueError("Noncanonical or unsupported audit history") - return record - - def check_prepared_history(report, directory): record = history_record(report) if ( diff --git a/node/tests/test_history.py b/node/tests/test_history.py new file mode 100644 index 0000000..284c3f6 --- /dev/null +++ b/node/tests/test_history.py @@ -0,0 +1,262 @@ +"""Lossless history storage and adversarial expansion boundaries.""" + +import base64 +import copy +import runpy +from pathlib import Path + +import pytest + +CODEC = runpy.run_path(str(Path(__file__).parents[1] / "runtime/history.py")) + + +def framed(data, version=2): + return ( + f"" + ) + + +def sample(): + advisory = { + "title": "A repeated advisory title that belongs to each historical snapshot", + "url": "https://github.com/advisories/GHSA-test-test-test", + "paths": ["root>α@1>leaf@2", "root>α@1>leaf@3", "root>α@1>leaf@2", "", ">x>"], + } + return { + "version": 1, + "attempts": [ + {"before": copy.deepcopy(advisory), "after": copy.deepcopy(advisory)} + for _ in range(3) + ], + "tokens": [{"r": 0}, {"p": -1}, {"s": True}], + } + + +@pytest.mark.parametrize("version", [1, 2]) +def test_exact_logical_history_and_independent_mutable_snapshots(version): + record = sample() + body = framed(record, 1) if version == 1 else CODEC["marker"](record).encode() + restored = CODEC["read"](body) + assert CODEC["canonical"](restored) == CODEC["canonical"](record) + restored["attempts"][0]["before"]["paths"].reverse() + assert restored["attempts"][0]["after"] == record["attempts"][0]["after"] + assert restored["attempts"][1] == record["attempts"][1] + assert CODEC["PATTERN"].sub("", body.decode()) == "" + + +def test_changed_historical_fields_stay_distinct_and_encoding_is_deterministic(): + record = sample() + record["attempts"][1]["after"]["title"] += " changed" + packed = CODEC["pack"](record) + assert CODEC["unpack"](packed) == record + reordered = dict(reversed(list(record.items()))) + assert CODEC["marker"](reordered) == CODEC["marker"](record) + + +def test_repeated_advisories_and_dependency_routes_have_order_of_magnitude_saving(): + advisory = { + "title": "Repeated long security advisory title", + "paths": [f"project@1>parent@2>branch{i}@3>leaf@4" for i in range(150)], + } + record = { + "version": 1, + "attempts": [{"before": advisory, "after": advisory} for _ in range(8)], + } + old = framed(record, 1) + new = CODEC["marker"](record).encode() + assert len(old) > 10 * len(new) + assert CODEC["read"](new) == record + + +@pytest.mark.parametrize( + "problem", + [ + "envelope-key", + "version", + "bool-version", + "table-type", + "empty-objects", + "object-type", + "inline-list", + "unknown-token", + "multi-token", + "bool-index", + "float-index", + "negative-index", + "forward-object", + "root-type", + "root-bool", + "path-type", + "path-parent", + "path-cycle", + "path-segment", + "string-type", + "segment-type", + "missing-string", + ], +) +def test_rejects_invalid_tables_and_references(problem): + data = CODEC["pack"]({"version": 1, "child": [1]}) + if problem == "envelope-key": + data["extra"] = 0 + elif problem == "version": + data["version"] = 3 + elif problem == "bool-version": + data["version"] = True + elif problem == "table-type": + data["objects"] = {} + elif problem == "empty-objects": + data["objects"] = [] + elif problem == "object-type": + data["objects"][0] = "bad" + elif problem == "inline-list": + data["objects"][0] = [[0]] + elif problem == "unknown-token": + data["objects"][0] = [{"x": 0}] + elif problem == "multi-token": + data["objects"][0] = [{"r": 0, "s": 0}] + elif problem == "bool-index": + data["objects"][0] = [{"r": False}] + elif problem == "float-index": + data["objects"][0] = [{"r": 0.0}] + elif problem == "negative-index": + data["objects"][0] = [{"r": -1}] + elif problem == "forward-object": + data["objects"][0] = [{"r": 1}] + elif problem == "root-type": + data["root"] = [] + elif problem == "root-bool": + data["root"] = {"r": True} + elif problem == "path-type": + data["paths"] = [{}] + elif problem == "path-parent": + data["segments"], data["paths"] = ["x"], [[-2, 0]] + elif problem == "path-cycle": + data["segments"], data["paths"] = ["x"], [[0, 0]] + elif problem == "path-segment": + data["segments"], data["paths"] = ["x"], [[-1, True]] + elif problem == "string-type": + data["strings"] = [0] + elif problem == "segment-type": + data["segments"] = [None] + elif problem == "missing-string": + data["objects"][0] = [{"s": 0}] + with pytest.raises(ValueError): + CODEC["read"](framed(data)) + + +@pytest.mark.parametrize( + "problem", ["cycle", "amplification", "depth", "values", "path-size"] +) +def test_preflight_rejects_expansion_without_building_it(monkeypatch, problem): + data = CODEC["pack"]({"version": 1}) + if problem in {"cycle", "amplification"}: + data["objects"] = [[None]] + for _ in range(25): + data["objects"].append([{"r": len(data["objects"]) - 1}] * 2) + data["root"] = {"r": len(data["objects"]) - 1} + if problem == "cycle": + data["objects"][0] = [{"r": 0}] + elif problem == "path-size": + data["segments"], data["paths"] = ["abcdef"], [[i - 1, 0] for i in range(20)] + monkeypatch.setitem(CODEC["bounded"].__globals__, "MAX_LOGICAL", 100) + else: + value = {"version": 1, "child": [None] * 12} + if problem == "depth": + for _ in range(10): + value["child"] = [value["child"]] + data = CODEC["pack"](value) + monkeypatch.setitem( + CODEC["bounded"].__globals__, + "MAX_DEPTH" if problem == "depth" else "MAX_VALUES", + 5, + ) + with pytest.raises(ValueError): + CODEC["read"](framed(data)) + + +@pytest.mark.parametrize( + "raw", + [ + b'{"version":1,"version":1}', + b'{"version": 1}', + b'{"version":1,"n":NaN}', + b'{"version":1,"n":1e9999}', + ], +) +def test_rejects_duplicate_noncanonical_and_nonfinite_legacy_json(raw): + with pytest.raises(ValueError): + CODEC["read"](b"") + + +def test_stored_limits_ambiguous_markers_and_unknown_versions(): + body = CODEC["marker"](sample()).encode() + for invalid in [ + body * 2, + body + b"\n", + body.replace(b":v2:", b":v3:"), + b"x" * 1048577, + ]: + with pytest.raises(ValueError): + CODEC["read"](invalid) + with pytest.raises(ValueError): + CODEC["marker"](sample(), max_encoded=12) + + +def test_many_small_json_shapes_round_trip(): + for i in range(105): + value = { + "version": 1, + "value": [ + None, + True, + False, + i, + i / 7, + "雪", + {"r": i}, + {"paths": [">" * i, "x>" * i]}, + ], + } + assert CODEC["read"](CODEC["marker"](value).encode()) == value + + +def test_exact_logical_byte_limit_counts_unicode_and_path_separators(monkeypatch): + record = sample() + data = CODEC["pack"](record) + size = len(CODEC["canonical"](record)) + monkeypatch.setitem(CODEC["bounded"].__globals__, "MAX_LOGICAL", size) + assert CODEC["read"](framed(data)) == record + monkeypatch.setitem(CODEC["bounded"].__globals__, "MAX_LOGICAL", size - 1) + with pytest.raises(ValueError): + CODEC["read"](framed(data)) + + +def test_writer_and_reader_share_exact_container_depth_limit(monkeypatch): + record = {"version": 1, "value": [[[]]]} + monkeypatch.setitem(CODEC["bounded"].__globals__, "MAX_DEPTH", 4) + body = CODEC["marker"](record).encode() + assert CODEC["read"](body) == record + monkeypatch.setitem(CODEC["bounded"].__globals__, "MAX_DEPTH", 3) + with pytest.raises(ValueError): + CODEC["marker"](record) + with pytest.raises(ValueError): + CODEC["read"](body) + + +def test_repeated_large_strings_hit_byte_limit_before_value_limit(): + data = CODEC["pack"]({"version": 1}) + data["strings"] = ["x" * 100000] + data["objects"][-1]["large"] = {"r": 0} + data["objects"].insert(0, [{"s": 0}] * 90) + data["root"] = {"r": 1} + with pytest.raises(ValueError, match="logical expansion"): + CODEC["read"](framed(data)) + + +@pytest.mark.parametrize("value", [None, [], {}, {"version": True}, {"version": 2}]) +def test_writer_rejects_unsupported_logical_record(value): + with pytest.raises(ValueError, match="logical history"): + CODEC["marker"](value)