eBPF-based security platform
bpm: seal tree segments in bpm tree append
John Fastabend136f317a4ad3
diff --git a/.agents/skills/upatch/SKILL.md b/.agents/skills/upatch/SKILL.mdindex c35ad75b..bd253688 100644--- a/.agents/skills/upatch/SKILL.md+++ b/.agents/skills/upatch/SKILL.md@@ -142,8 +142,12 @@ shirudo bpm tree show oci://<registry>/<repository> --cert <keys>/cert.der [--reappend` adds a load or delete operation to a signed upatch tree thattargets sync; `Documentation/reference/cli/bpm.rst` lists its options.It refuses an `add` whose XDP programs select a device class another-upatch of the tree selects on the same nodes: give each class to one-upatch, or the two entries selectors that exclude each other. `tree+upatch of the tree selects on the same nodes, in any segment: give each+class to one upatch, or the two entries selectors that exclude each+other. A segment that holds `--segment-ops` operations (64 by default,+1 to 512) is sealed and tagged `segment-<k>`, and the append starts the+next one; keep the `segment-*` tags in the registry, since targets walk+back through the sealed segments by digest. `treeshow` prints the publication verified as a target verifies it, as`{"manifest_digest":...,"document":...}` with the signed documentverbatim, `fixes` included: the check that an append published whatdiff --git a/Documentation/contribute/testing/proof-coverage.rst b/Documentation/contribute/testing/proof-coverage.rstindex 61e00105..79f66896 100644--- a/Documentation/contribute/testing/proof-coverage.rst+++ b/Documentation/contribute/testing/proof-coverage.rst@@ -1000,6 +1000,7 @@ the model follows the C.``historyBytes`` of ``Shirudo.Events``, which CBMC,``chain-events``, checks* - ``Shirudo.Events``, the event encodings of :src:`util/chain.c`+ and the history root's step of :src:`util/chain_history.c`- ``bytes_injective``: two admitted events hash the same bytes onlywhen they are the same event; ``listing_injective``: the initevent's listing spells one set while no name holds a newline;diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex 53d00e76..354433c8 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -515,6 +515,18 @@ signed config image.another key, a wrong certificate, a tampered layer and a document``tree sync`` would refuse with the errno sync reports, andwrites nothing to the registry+ * - ``t7009-bpm-tree-seal``+ - ``bpm tree append`` seals a segment at ``--segment-ops``, a value+ that may change between appends, or before one append would pass+ 512 operations, never splits an append, tags the sealed manifest+ ``segment-<k>`` with its bytes unchanged and keeps a tag an earlier+ run left, starts the next segment with the sealed head, digest and+ a ``history_root`` recomputed independently, carries ``fixes`` and+ selectors across a seal, refuses a current segment that does not+ verify, refuses an XDP ``add`` whose class a live ``add`` of a+ sealed segment selects and takes it once a later segment deleted+ that ``add``, and fetches no sealed segment for an ``add`` without+ XDP classes* - ``t7101-bpm-tree``- Tree sync with a selector* - ``t7102-bpm-tree-sequential``@@ -638,10 +650,10 @@ signed config image.Unit suites and fuzz targets~~~~~~~~~~~~~~~~~~~~~~~~~~~~-The unit suites in :src:`testing/unit/` cover 29 of the modules in+The unit suites in :src:`testing/unit/` cover 30 of the modules in:src:`util/`: ``attest``, ``bpm_oci``, ``bpm_package``, ``bpm_state``,``bpm_tree``, ``bpm_tree_overlap``, ``bpm_tree_state``, ``chain``,-``conditions``, ``curl``,+``chain_history``, ``conditions``,``eventlog``, ``format``, ``hex``, ``io``, ``json``, ``kernel_abi``,``keepalive``, ``keepalive_quote``, ``kernel_build_id``,``kernel_release``, ``measured``,@@ -792,12 +804,12 @@ Coverage by area``oci-http``, ``oci-manifest``, ``oci-ref``, ``registry-auth``. Unit:``bpm_oci``, ``bpm_package``* - upatch tree- - ``t3011``, ``t5004``, ``t7005``, ``t7007``, ``t7008``, ``t7101``,- ``t7102``, ``t7103``, ``t7104``, ``t7105``, ``t7106``,+ - ``t3011``, ``t5004``, ``t7005``, ``t7007``, ``t7008``, ``t7009``,+ ``t7101``, ``t7102``, ``t7103``, ``t7104``, ``t7105``, ``t7106``,``t7107``, ``t7109``, ``t9105``, ``t9109``. Fuzz: ``tree``,``tree-state``, ``kconfig``. Unit: ``bpm_tree``,- ``bpm_tree_overlap``, ``bpm_tree_state``, ``kernel_build_id``,- ``kernel_release``+ ``bpm_tree_overlap``, ``bpm_tree_state``, ``chain_history``,+ ``kernel_build_id``, ``kernel_release``* - Policy labels- upatch labels and Beefile serialization: ``t3109``, ``t7006``.Unauthorized policy-xattr changes: ``t6111``. Task and socketdiff --git a/Documentation/reference/cli/bpm.rst b/Documentation/reference/cli/bpm.rstindex 022e0624..f4658af3 100644--- a/Documentation/reference/cli/bpm.rst+++ b/Documentation/reference/cli/bpm.rst@@ -235,6 +235,46 @@ package as the next operations of the signed tree at* - ``--op``- ``add``- ``add`` or ``delete``.+ * - ``--segment-ops``+ - ``64``+ - Operations after which a segment is sealed, 1 to 512. Any other+ value is refused with ``bpm tree append: --segment-ops must be 1+ to 512``. It may differ from one append to the next.++The existing publication must pass the checks ``tree sync`` makes before+it applies anything: the sequence numbers, the ``base`` keys and every+operation's digest. Otherwise the append is refused with ``bpm tree+append: the publication at <repository>:<reference> does not verify``+and nothing is published.++A tree is a chain of segments, each one publication document of at most+512 operations; :doc:`/reference/formats/bpm-formats` has the ``base``+keys that link them. An append never splits its operations+across segments. Before it adds its ``n`` operations to the current+segment, which holds ``c``, it seals that segment when ``c`` is at least+``--segment-ops`` or ``c + n`` exceeds 512, so a segment can hold up to+``n - 1`` operations more than ``--segment-ops``. A package holds at most+128 tree entries, so one append always fits in a segment. Sealing:++#. The current publication becomes the sealed segment, its manifest and+ document unchanged.+#. Its manifest is tagged ``segment-<k>``, where ``k`` counts the sealed+ segments from 1. The tag only keeps registry garbage collection from+ deleting the segment: a target follows ``<reference>`` and reaches the+ sealed segments by digest. The append looks up the last tag by+ doubling ``k`` and then halving the gap, about 2 log\ :sub:`2` ``k``+ manifest requests, and never moves an existing tag. When the last tag+ already names the sealed manifest, left by an append that failed after+ tagging, it adds none.+#. The new publication holds only the appended operations. Its+ ``base.seq`` is the sealed ``head.seq``, ``base.segment_manifest_digest``+ and ``parent_manifest_digest`` both name the sealed manifest, its+ ``generation`` is one higher, and ``base.history_root`` is the sealed+ segment's ``base.history_root``, 64 zeros for the first segment,+ folded over the sealed operations.++The tag is written after every check has passed and just before+``<reference>`` moves, so a refused append leaves no tag.``tree append`` works out every operation of the package, checks eachas a target will and signs the publication before it uploads anything:@@ -262,6 +302,21 @@ shared classes, and nothing is published.- The classes of the earlier upatches are read from their artifacts inthe registry, so the append fails when one of them cannot be fetched.Two upatches of the package being appended are compared as well.+- The earlier upatches are those of every segment back to ``seq`` 1. For+ an ``add`` whose XDP programs select a class, the append fetches each+ sealed segment by its digest, as a target that joins the tree does, and+ checks that it verifies against ``--previous-cert``, that it is the+ segment its successor names, ends where the successor starts and has a+ lower generation, and it passes the checks of the current publication+ above. A segment that fails is refused with ``bpm tree append: the+ sealed segment <digest>, which ends at seq <n>, does not verify``.+ A ``delete`` in any later segment withdraws an ``add`` as one in its+ own segment does. The walk covers at most 1,048,576 operations, the+ limit of a joining target; past it the append is refused with ``bpm+ tree append: a joining node walks back <n> operations, past the limit+ of 1048576, so the XDP device classes of the sealed segments cannot be+ checked``. An ``add`` without XDP classes and a ``delete`` fetch no+ sealed segment.An ``add`` carries the entry's ``fixes``, a ``delete`` none, and everyearlier operation keeps its own. The append is refused, and nothing isdiff --git a/Documentation/reference/formats/bpm-formats.rst b/Documentation/reference/formats/bpm-formats.rstindex 40ad450b..9afae48a 100644--- a/Documentation/reference/formats/bpm-formats.rst+++ b/Documentation/reference/formats/bpm-formats.rst@@ -338,6 +338,12 @@ Tree objects in the registry``schemaVersion`` 2, ``artifactType````application/vnd.shirudo.upatch.tree.v1``, the empty config, andexactly one document layer and one signature layer.+ * - Sealed segment+ - A publication manifest that a later segment names in+ ``base.segment_manifest_digest``, unchanged since it was the+ current one. Tagged ``segment-<k>``, ``k`` counting the sealed+ segments from 1, only so that registry garbage collection keeps+ it; targets fetch it by digest and never read the tag.* - Document layer- The publication document, media type``application/vnd.shirudo.upatch.tree.v1+json``.diff --git a/Documentation/upatches/publish/publishing.rst b/Documentation/upatches/publish/publishing.rstindex cd2e63d5..5bd18c26 100644--- a/Documentation/upatches/publish/publishing.rst+++ b/Documentation/upatches/publish/publishing.rst@@ -151,6 +151,28 @@ entries selectors that exclude each other, such as different values ofone label, or append the ``delete`` of the earlier upatch first.:doc:`/reference/cli/bpm` has the exact rule.+Segments and registry retention+-------------------------------++A tree grows past what one signed document holds as a chain of+segments. Once the current segment holds 64 operations, or the number+``--segment-ops`` gives, ``tree append`` seals it and publishes the new+operations as the next segment, which names the sealed one by digest.+One append always goes into one segment, and a segment never holds more+than 512 operations. ``<tree>:stable`` names only the current segment; a+target that is behind fetches the sealed ones by digest.++Every sealed segment is tagged ``segment-1``, ``segment-2`` and so on in+the tree's repository. Keep the ``segment-*`` tags: a registry that+deletes untagged manifests, or a retention policy that prunes old tags,+would remove a segment a target still has to walk through, and the+target then refuses to sync rather than skip it.++An ``add`` whose XDP programs select a device class makes ``tree+append`` fetch every sealed segment, so its class check covers the whole+tree. Expect three fetches per sealed segment for such an ``add``, its+manifest, document and signature; any other operation fetches none.+What a target does with them----------------------------diff --git a/Makefile.shirudo b/Makefile.shirudoindex bd512046..e0ab6b31 100644--- a/Makefile.shirudo+++ b/Makefile.shirudo@@ -239,6 +239,7 @@ UTIL_SRCS := \util/tpm_wire.c \util/attest.c \util/chain.c \+ util/chain_history.c \util/hex.c \util/string.c \util/bpm_tree.c \@@ -508,6 +509,7 @@ tools/shirudo-build/shirudo-build: $(BUILD_OBJS) util/sign.o util/config_image.outil/bpm_oci.o util/curl.o util/bpm_package.o \util/upatch_rodata.o \util/bpm_tree.o util/bpm_tree_overlap.o \+ util/chain_history.o \util/kernel_release.o $(VERSION_OBJ) \$(LIBBPF_A)@printf ' LD $@\n'@@ -1133,7 +1135,8 @@ testing/fuzz/fuzz-tpm-wire: testing/fuzz/fuzz-tpm-wire.c $(FUZZ_BASE) \util/tpm_wire.c util/crypto_openssl.c util/io.c \$(FUZZ_SEAL)testing/fuzz/fuzz-attest: testing/fuzz/fuzz-attest.c $(FUZZ_BASE) \- util/attest.c util/chain.c util/nv_writer.c util/tpm.c \+ util/attest.c util/chain.c util/chain_history.c \+ util/nv_writer.c util/tpm.c \util/tpm_wire.c util/eventlog.c util/timefmt.c \util/crypto_openssl.c util/io.c $(FUZZ_SEAL) \util/config_attest.c util/config_update.c \diff --git a/completion/shirudo.bash b/completion/shirudo.bashindex f5db1e6d..706dee95 100644--- a/completion/shirudo.bash+++ b/completion/shirudo.bash@@ -168,7 +168,7 @@ _shirudo()COMPREPLY=( $(compgen -f -- "$cur") )elif [[ $sub == tree && ${COMP_WORDS[3]} == append && $cur == -* ]]; thenCOMPREPLY=( $(compgen -W "--keys-dir --key --cert --previous-cert --tree-id \- --reference --op" -- "$cur") )+ --reference --op --segment-ops" -- "$cur") )elif [[ $sub == tree && ${COMP_WORDS[3]} == append ]]; thenCOMPREPLY=( $(compgen -f -X '!*.bee' -- "$cur") \$(compgen -d -- "$cur") )diff --git a/testing/functional/bpm/t7009-bpm-tree-seal.sh b/testing/functional/bpm/t7009-bpm-tree-seal.shnew file mode 100755index 00000000..2fbde739--- /dev/null+++ b/testing/functional/bpm/t7009-bpm-tree-seal.sh@@ -0,0 +1,473 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t7009 -- bpm tree append seals a segment that holds --segment-ops+# operations, or that one append would take past 512, tags the sealed+# manifest segment-<k> with its bytes unchanged, and starts the next+# segment at the sealed head with the sealed digest and the history root+# there, recomputed here. An append is never split; fixes and selectors+# carry across a seal. The XDP class check reaches the adds of the sealed+# segments, fetched by digest and verified as a joining node verifies+# them, an add a later segment deleted no longer counts, and an add+# without XDP classes fetches no sealed segment.+# Needs clang, shirudo-build, python3 and an OpenSSL >= 3.5 (ML-DSA).++cd "$(dirname "$0")/../.."+. ./test-lib.sh++S=../shirudo+SHB=../tools/shirudo-build/shirudo-build++command -v clang >/dev/null 2>&1 || test_skip_all "no clang"+command -v openssl >/dev/null 2>&1 || test_skip_all "no openssl"+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"+[ -x "$S" ] || test_skip_all "shirudo not built"+[ -x "$SHB" ] || test_skip_all "shirudo-build not built (make shirudo-build)"+[ -e ../vendor/linux/vmlinux.h ] || test_skip_all "no vendor/linux/vmlinux.h (build the tree)"+openssl list -public-key-algorithms 2>/dev/null | grep -qi 'ML-DSA' ||+ test_skip_all "openssl without ML-DSA (needs OpenSSL >= 3.5)"++REPO=$(cd .. && pwd)+case "$SHB" in+/*) B="$SHB" ;;+*) B="$REPO/${SHB#../}" ;;+esac+S="$REPO/shirudo"++WORK=$(mktemp -d)+SERVER_PID=+cleanup() {+ [ -z "$SERVER_PID" ] || kill "$SERVER_PID" 2>/dev/null || :+ rm -rf "$WORK"+}+trap cleanup EXIT HUP INT TERM++"$S" genkey --keys-dir "$WORK/keys" >/dev/null 2>&1 ||+ test_skip_all "genkey failed"++export SHIRUDO_BUILD="$B" BPM_OCI_SCHEME=http+export REGISTRY_AUTH_FILE="$WORK/absent-auth.json" NO_PROXY=127.0.0.1 no_proxy=127.0.0.1+unset BPM_OCI_CA_FILE BPM_OCI_USERNAME BPM_OCI_PASSWORD++# A package named $1 of one upatch per further name, each an XDP program+# for the device classes $2 or, when $2 is empty, an fentry program, with+# the tree entry lines $3.+package() {+ name=$1 classes=$2 entry=$3+ shift 3+ if [ -n "$classes" ]; then+ program="SEC(\"xdp/$classes\")\nint xdp_pass(struct xdp_md *ctx)\n{\n\treturn XDP_PASS;\n}"+ else+ program="SEC(\"fentry/do_nanosleep\")\nint BPF_PROG(fn)\n{\n\treturn 0;\n}"+ fi+ mkdir -p "$WORK/$name" &&+ ln -s "$REPO/vendor" "$WORK/$name/vendor" &&+ ln -s "$REPO/bpf" "$WORK/$name/bpf" &&+ printf '[package]\nname = "%s"\n' "$name" >"$WORK/$name/Beefile" &&+ for id in "$@"; do+ printf '// SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause\n#include "vmlinux.h"\n#include <bpf/bpf_helpers.h>\n#include <bpf/bpf_tracing.h>\n\nchar _license[] SEC("license") = "Dual BSD/GPL";\n\n%b\n' \+ "$program" >"$WORK/$name/$id.bpf.c" &&+ printf '\n[[upatches]]\nsource = "%s.bpf.c"\n\n[upatches.tree]\nid = "%s"\n%b' \+ "$id" "$id" "$entry" >>"$WORK/$name/Beefile" || return 1+ done &&+ ( cd "$WORK" && "$S" bpm build "$name" --version 1.0.0 \+ --keys-dir "$WORK/keys" ) >&2+}++SITE_A='\n[upatches.tree.selector.labels]\nsite = ["a"]\n'+test_expect_success 'bpm build packages the upatches the appends publish' '+ package t7009a "" \+ "fixes = [\"EXAMPLE-0102\", \"EXAMPLE-0101\"]$SITE_A" t7009a &&+ package t7009m "" "" t7009m1 t7009m2 t7009m3 &&+ package t7009xa 2 "$SITE_A" t7009xa &&+ package t7009xb 2 "$SITE_A" t7009xb+'+for p in t7009a t7009m t7009xa t7009xb; do+ [ -s "$WORK/$p-1.0.0.bee" ] || test_done+done++PORT=$(python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')+REG="$WORK/registry"+LOG="$WORK/requests.log"+python3 ./helper/test-oci-registry.py --root "$REG" --port "$PORT" --writable \+ --log "$LOG" --ready-file "$WORK/ready" &+SERVER_PID=$!+i=0+while [ ! -e "$WORK/ready" ]; do+ i=$((i + 1))+ [ "$i" -lt 100 ] || test_skip_all "registry fixture did not start"+ sleep .05+done++# Append package $1 to repository ns/$2 with the options that follow.+append() {+ pkg=$1 tree=$2+ shift 2+ "$S" bpm tree append "$WORK/$pkg-1.0.0.bee" \+ "oci://127.0.0.1:$PORT/ns/$tree" --keys-dir "$WORK/keys" "$@" \+ >"$WORK/out" 2>"$WORK/err"+}++# The checks of the segments of a tree, read from the registry files.+cat >"$WORK/segments.py" <<\PY+import hashlib, json, pathlib++DOC = "application/vnd.shirudo.upatch.tree.v1+json"+SIG = "application/vnd.shirudo.upatch.tree.signature.v1"+++def sha(data):+ return "sha256:" + hashlib.sha256(data).hexdigest()+++def layer(manifest, media):+ return [l for l in json.loads(manifest)["layers"]+ if l["mediaType"] == media][0]["digest"]+++def segment(repo, ref):+ manifest = (repo / "manifests" / ref).read_bytes()+ document = (repo / "blobs" / layer(manifest, DOC)).read_bytes()+ return {"digest": sha(manifest), "manifest": manifest,+ "document": document, "doc": json.loads(document)}+++def op_digest(op):+ canonical = {k: v for k, v in op.items()+ if k not in ("operation_digest", "fixes")}+ return sha(json.dumps(canonical, separators=(",", ":")).encode())+++def history(ops):+ root = bytes(32)+ for op in ops:+ step = b"shirudo-tree-history\0" + root+ root = hashlib.sha256(step + bytes.fromhex(op["operation_digest"][7:])).digest()+ return root.hex()+++def walk(repo, ref="stable"):+ """Every segment, oldest first, each checked against its successor."""+ chain = [segment(repo, ref)]+ while chain[0]["doc"]["base"]["seq"]:+ succ = chain[0]["doc"]+ pred = segment(repo, succ["base"]["segment_manifest_digest"])+ assert pred["digest"] == succ["base"]["segment_manifest_digest"], pred+ assert pred["doc"]["head"]["seq"] == succ["base"]["seq"], succ+ assert pred["doc"]["generation"] < succ["generation"], succ+ assert pred["doc"]["tree_id"] == succ["tree_id"], succ+ chain.insert(0, pred)+ ops = []+ for k, seg in enumerate(chain):+ doc = seg["doc"]+ base = doc["base"]+ assert base["seq"] == len(ops), (k, base)+ if base["seq"]:+ assert set(base) == {"seq", "segment_manifest_digest",+ "history_root"}, base+ assert base["history_root"] == history(ops), (k, base)+ else:+ assert base == {"seq": 0}, base+ for i, op in enumerate(doc["operations"]):+ assert op["seq"] == base["seq"] + 1 + i, op+ assert op["operation_digest"] == op_digest(op), op+ assert doc["head"]["seq"] == base["seq"] + len(doc["operations"]), doc+ ops += doc["operations"]+ if k + 1 < len(chain):+ tag = repo / "manifests" / f"segment-{k + 1}"+ assert tag.read_bytes() == seg["manifest"], k+ assert not (repo / "manifests" / f"segment-{len(chain)}").exists()+ return chain+PY++# Run the Python on standard input with the checks above and $@ as its+# arguments.+segments() {+ python3 - "$WORK" "$REG/ns" "$@"+}++test_expect_success 'appends fill a segment of --segment-ops operations' '+ append t7009a seal --segment-ops 2 &&+ append t7009a seal --segment-ops=2 &&+ cp "$REG/ns/seal/manifests/stable" "$WORK/sealed.manifest" &&+ segments <<-\PY+ import sys; sys.path.insert(0, sys.argv[1])+ import pathlib, segments as s+ chain = s.walk(pathlib.Path(sys.argv[2]) / "seal")+ assert len(chain) == 1, chain+ doc = chain[0]["doc"]+ assert doc["generation"] == 2 and doc["head"] == {"seq": 2}, doc+ PY+'++test_expect_success 'appending to a full segment seals and tags it' '+ append t7009a seal --segment-ops 2 &&+ grep -q "^oci://127.0.0.1:$PORT/ns/seal:stable sha256:" "$WORK/out" &&+ test ! -s "$WORK/err" &&+ cmp -s "$WORK/sealed.manifest" "$REG/ns/seal/manifests/segment-1" &&+ segments "$WORK/sealed.manifest" <<-\PY+ import sys; sys.path.insert(0, sys.argv[1])+ import pathlib, segments as s+ repo = pathlib.Path(sys.argv[2]) / "seal"+ sealed = pathlib.Path(sys.argv[3]).read_bytes()+ chain = s.walk(repo)+ assert len(chain) == 2, chain+ old, new = chain[0], chain[1]["doc"]+ assert old["manifest"] == sealed, "the sealed manifest moved"+ assert (repo / "manifests" / old["digest"]).read_bytes() == sealed+ assert new["generation"] == 3 and new["parent_manifest_digest"] == old["digest"], new+ assert new["base"] == {"seq": 2, "segment_manifest_digest": old["digest"],+ "history_root": s.history(old["doc"]["operations"])}, new+ assert [op["seq"] for op in new["operations"]] == [3], new+ PY+'++test_expect_success 'an append of several operations is not split' '+ append t7009m seal --segment-ops 2 &&+ test ! -e "$REG/ns/seal/manifests/segment-2" &&+ segments <<-\PY+ import sys; sys.path.insert(0, sys.argv[1])+ import pathlib, segments as s+ chain = s.walk(pathlib.Path(sys.argv[2]) / "seal")+ assert len(chain) == 2, chain+ ops = chain[1]["doc"]["operations"]+ assert [(op["seq"], op["id"]) for op in ops] == [+ (3, "t7009a"), (4, "t7009m1"), (5, "t7009m2"), (6, "t7009m3")], ops+ PY+'++test_expect_success '--segment-ops changed between appends is honoured' '+ append t7009a seal --segment-ops 8 &&+ test ! -e "$REG/ns/seal/manifests/segment-2" &&+ cp "$REG/ns/seal/manifests/stable" "$WORK/sealed2.manifest" &&+ append t7009a seal --segment-ops=5 &&+ cmp -s "$WORK/sealed2.manifest" "$REG/ns/seal/manifests/segment-2" &&+ append t7009a seal &&+ test ! -e "$REG/ns/seal/manifests/segment-3" &&+ segments <<-\PY+ import sys; sys.path.insert(0, sys.argv[1])+ import pathlib, segments as s+ chain = s.walk(pathlib.Path(sys.argv[2]) / "seal")+ assert [(c["doc"]["base"]["seq"], c["doc"]["head"]["seq"]) for c in chain] == [+ (0, 2), (2, 7), (7, 9)], chain+ assert chain[2]["doc"]["generation"] == 7, chain[2]["doc"]+ PY+'++test_expect_success 'fixes and selectors survive across a seal' '+ segments <<-\PY+ import sys; sys.path.insert(0, sys.argv[1])+ import pathlib, segments as s+ chain = s.walk(pathlib.Path(sys.argv[2]) / "seal")+ adds = [op for c in chain for op in c["doc"]["operations"]+ if op["id"] == "t7009a"]+ assert [op["seq"] for op in adds] == [1, 2, 3, 7, 8, 9], adds+ for op in adds:+ assert op["fixes"] == ["EXAMPLE-0101", "EXAMPLE-0102"], op+ assert op["selector"] == {"labels": {"site": ["a"]}}, op+ assert op["artifact"] == adds[0]["artifact"], op+ PY+'++test_expect_success 'a seal an earlier run tagged keeps its tag' '+ append t7009a retag --segment-ops 1 &&+ cp "$REG/ns/retag/manifests/stable" "$REG/ns/retag/manifests/segment-1" &&+ append t7009a retag --segment-ops 1 &&+ test ! -e "$REG/ns/retag/manifests/segment-2" &&+ append t7009a retag --segment-ops 1 &&+ test -e "$REG/ns/retag/manifests/segment-2" &&+ test ! -e "$REG/ns/retag/manifests/segment-3" &&+ segments <<-\PY+ import sys; sys.path.insert(0, sys.argv[1])+ import pathlib, segments as s+ chain = s.walk(pathlib.Path(sys.argv[2]) / "retag")+ assert len(chain) == 3, chain+ PY+'++test_expect_success '--segment-ops outside 1 to 512 is refused' '+ cp "$REG/ns/seal/manifests/stable" "$WORK/before.manifest" &&+ for n in 0 513 -1 1x ""; do+ ! append t7009a seal --segment-ops "$n" &&+ grep -qx "bpm tree append: --segment-ops must be 1 to 512" \+ "$WORK/err" || exit 1+ done &&+ cmp -s "$WORK/before.manifest" "$REG/ns/seal/manifests/stable"+'++# Publish at ns/$1:stable the first segment of $2 operations, copies of+# the first operation of ns/seal at the next sequence numbers, signed+# with the operator key; with $3, the last one's digest is wrong.+synthetic() {+ python3 - "$WORK" "$REG/ns" "$@" <<-\PY &&+ import sys; sys.path.insert(0, sys.argv[1])+ import json, pathlib, segments as s+ work, ns = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2])+ n, bad = int(sys.argv[4]), len(sys.argv) > 5+ op = s.walk(ns / "seal")[0]["doc"]["operations"][0]+ ops = []+ for seq in range(1, n + 1):+ o = {k: v for k, v in op.items() if k not in ("fixes", "operation_digest")}+ o["seq"] = seq+ o["operation_digest"] = s.op_digest(o)+ ops.append(o)+ if bad:+ ops[-1]["operation_digest"] = ops[0]["operation_digest"]+ doc = {"schema": 1, "tree_id": "t7009a", "generation": 1,+ "base": {"seq": 0}, "operations": ops, "head": {"seq": n}}+ (work / "synthetic.json").write_bytes(+ json.dumps(doc, separators=(",", ":")).encode())+ PY+ openssl cms -sign -binary -md sha512 -in "$WORK/synthetic.json" \+ -signer "$WORK/keys/cert.der" -inkey "$WORK/keys/signing_key.pem" \+ -outform DER -out "$WORK/synthetic.sig" -nosmimecap -nocerts -keyid &&+ python3 - "$WORK" "$REG/ns" "$1" <<-\PY+ import sys; sys.path.insert(0, sys.argv[1])+ import json, pathlib, segments as s+ work, ns = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2])+ repo = ns / sys.argv[3]+ (repo / "manifests").mkdir(parents=True)+ (repo / "blobs").mkdir()+ manifest = json.loads((ns / "seal" / "manifests" / "segment-1").read_bytes())+ for l in manifest["layers"]:+ body = (work / ("synthetic.json" if l["mediaType"] == s.DOC+ else "synthetic.sig")).read_bytes()+ l["digest"], l["size"] = s.sha(body), len(body)+ (repo / "blobs" / l["digest"]).write_bytes(body)+ config = manifest["config"]["digest"]+ (repo / "blobs" / config).write_bytes((ns / "seal" / "blobs" / config).read_bytes())+ raw = json.dumps(manifest, separators=(",", ":")).encode()+ (repo / "manifests" / "stable").write_bytes(raw)+ (repo / "manifests" / s.sha(raw)).write_bytes(raw)+ PY+}++test_expect_success 'an append that fills a segment to 512 does not seal' '+ synthetic full 509 &&+ append t7009m full --segment-ops 512 &&+ append t7009a full --segment-ops 512 &&+ segments <<-\PY+ import sys; sys.path.insert(0, sys.argv[1])+ import pathlib, segments as s+ chain = s.walk(pathlib.Path(sys.argv[2]) / "full")+ assert [(c["doc"]["base"]["seq"], c["doc"]["head"]["seq"]) for c in chain] == [+ (0, 512), (512, 513)], chain+ PY+'++test_expect_success 'an append that would pass 512 operations seals first' '+ synthetic over 510 &&+ cp "$REG/ns/over/manifests/stable" "$WORK/over.manifest" &&+ append t7009m over --segment-ops 512 &&+ cmp -s "$WORK/over.manifest" "$REG/ns/over/manifests/segment-1" &&+ segments <<-\PY+ import sys; sys.path.insert(0, sys.argv[1])+ import pathlib, segments as s+ chain = s.walk(pathlib.Path(sys.argv[2]) / "over")+ assert [(c["doc"]["base"]["seq"], c["doc"]["head"]["seq"]) for c in chain] == [+ (0, 510), (510, 513)], chain+ PY+'++test_expect_success 'an append to a segment that does not verify is refused' '+ synthetic bad 3 wrong &&+ cp "$REG/ns/bad/manifests/stable" "$WORK/bad.manifest" &&+ ! append t7009a bad &&+ grep -qx "bpm tree append: the publication at oci://127.0.0.1:$PORT/ns/bad:stable does not verify" \+ "$WORK/err" &&+ cmp -s "$WORK/bad.manifest" "$REG/ns/bad/manifests/stable"+'++# Every request of the last append for a segment before the one it had+# in hand, the stable manifest $2 of ns/$1 before it: a manifest by+# digest, or its document or signature.+sealed_requests() {+ python3 - "$WORK" "$REG/ns" "$1" "$2" "$LOG" <<-\PY+ import sys; sys.path.insert(0, sys.argv[1])+ import json, pathlib, segments as s+ repo = pathlib.Path(sys.argv[2]) / sys.argv[3]+ hand = pathlib.Path(sys.argv[4]).read_bytes()+ base = json.loads((repo / "blobs" / s.layer(hand, s.DOC)).read_bytes())["base"]+ paths = set()+ for seg in s.walk(repo):+ if seg["doc"]["head"]["seq"] > base["seq"]:+ break+ paths.add("manifests/" + seg["digest"])+ for l in json.loads(seg["manifest"])["layers"]:+ paths.add("blobs/" + l["digest"])+ for line in pathlib.Path(sys.argv[5]).read_text().splitlines():+ method, path, _ = line.split("\t")+ if any(path.endswith("/" + p) for p in paths):+ print(method, path)+ PY+}++test_expect_success 'an XDP add whose class a live add of a sealed segment selects is refused' '+ append t7009xa xdp --segment-ops 1 &&+ append t7009a xdp --segment-ops 1 &&+ cp "$REG/ns/xdp/manifests/stable" "$WORK/xdp.manifest" &&+ ! append t7009xb xdp --segment-ops 1 &&+ grep -q "t7009xb and t7009xa (seq 1) both select XDP device classes 2 " \+ "$WORK/err" &&+ cmp -s "$WORK/xdp.manifest" "$REG/ns/xdp/manifests/stable" &&+ test ! -e "$REG/ns/xdp/manifests/segment-2" &&+ ! ls "$REG/ns/xdp/manifests" | grep -q "upatch-t7009xb"+'++test_expect_success 'an XDP add is taken once a later segment deleted the earlier add' '+ append t7009xa xdp --segment-ops 1 --op delete &&+ append t7009xb xdp --segment-ops 1 &&+ segments <<-\PY+ import sys; sys.path.insert(0, sys.argv[1])+ import pathlib, segments as s+ chain = s.walk(pathlib.Path(sys.argv[2]) / "xdp")+ ops = [(op["seq"], op["op"], op["id"]) for c in chain for op in c["doc"]["operations"]]+ assert ops == [(1, "add", "t7009xa"), (2, "add", "t7009a"),+ (3, "delete", "t7009xa"), (4, "add", "t7009xb")], ops+ assert len(chain) == 4, chain+ PY+'++test_expect_success 'an add without XDP classes fetches no sealed segment' '+ cp "$REG/ns/xdp/manifests/stable" "$WORK/hand.manifest" &&+ : >"$LOG" &&+ append t7009a xdp --segment-ops 1 &&+ test -e "$REG/ns/xdp/manifests/segment-4" &&+ sealed_requests xdp "$WORK/hand.manifest" >"$WORK/fetched" &&+ test ! -s "$WORK/fetched" &&+ cp "$REG/ns/xdp/manifests/stable" "$WORK/hand.manifest" &&+ : >"$LOG" &&+ append t7009a xdp --segment-ops 64 &&+ test ! -e "$REG/ns/xdp/manifests/segment-5" &&+ sealed_requests xdp "$WORK/hand.manifest" >"$WORK/fetched" &&+ test ! -s "$WORK/fetched" &&+ ! grep -q "manifests/segment-" "$LOG"+'++test_expect_success 'an XDP add fetches every sealed segment by digest' '+ cp "$REG/ns/xdp/manifests/stable" "$WORK/hand.manifest" &&+ : >"$LOG" &&+ append t7009xb xdp &&+ sealed_requests xdp "$WORK/hand.manifest" >"$WORK/fetched" &&+ test "$(grep -c "^GET .*/manifests/sha256:" "$WORK/fetched")" -eq 4+'++test_expect_success 'an XDP add refuses a sealed segment that is not the one named' '+ first=$(segments <<-\PY+ import sys; sys.path.insert(0, sys.argv[1])+ import pathlib, segments as s+ print(s.walk(pathlib.Path(sys.argv[2]) / "xdp")[0]["digest"])+ PY+ ) &&+ cp "$REG/ns/xdp/manifests/$first" "$WORK/first.manifest" &&+ cp "$REG/ns/xdp/manifests/segment-2" "$REG/ns/xdp/manifests/$first" &&+ cp "$REG/ns/xdp/manifests/stable" "$WORK/xdp.manifest" &&+ ! append t7009xb xdp &&+ grep -qx "bpm tree append: the sealed segment $first, which ends at seq 1, does not verify" \+ "$WORK/err" &&+ cmp -s "$WORK/xdp.manifest" "$REG/ns/xdp/manifests/stable" &&+ cp "$WORK/first.manifest" "$REG/ns/xdp/manifests/$first"+'++test_donediff --git a/testing/proofs/cbmc/chain-events.c b/testing/proofs/cbmc/chain-events.cindex 9e0a05a1..465faa2f 100644--- a/testing/proofs/cbmc/chain-events.c+++ b/testing/proofs/cbmc/chain-events.c@@ -2,13 +2,14 @@/** Copyright (c) 2026 Authors of shirudo*- * The event encoders of util/chain.c against testing/proofs/lean4/- * Shirudo/Events.lean, with SHA-256 modelled as recording what it is- * given: for every name of LEN bytes, payload, digest, sequence number- * and register, chain_upatch_event(), chain_key_event(),- * chain_tree_event(), chain_fold(), chain_history_step() and- * chain_init_event() of an empty set hand SHA-256 exactly the bytes of- * the model, and give its digest, or zeros and its error.+ * The event encoders of util/chain.c and util/chain_history.c against+ * testing/proofs/lean4/Shirudo/Events.lean, with SHA-256 modelled as+ * recording what it is given: for every name of LEN bytes, payload,+ * digest, sequence number and register, chain_upatch_event(),+ * chain_key_event(), chain_tree_event(), chain_fold(),+ * chain_history_step() and chain_init_event() of an empty set hand SHA-256+ * exactly the bytes of the model, and give its digest, or zeros and its+ * error.*/#include "proof.h"@@ -18,6 +19,7 @@#pragma CPROVER check push#pragma CPROVER check disable "conversion"#include "../../../util/chain.c"+#include "../../../util/chain_history.c"#pragma CPROVER check pop/* The longest string an event hashes: a upatch of a 256-byte name. */diff --git a/testing/unit/bpm_tree_overlap.c b/testing/unit/bpm_tree_overlap.cindex 7ed9858f..687a7e6e 100644--- a/testing/unit/bpm_tree_overlap.c+++ b/testing/unit/bpm_tree_overlap.c@@ -145,12 +145,41 @@ static void an_add_lives_until_a_delete_reaches_all_its_nodes(void)tree_publication_free(&pub);}+/* The operations of the segments after the add's, held apart from it. */+static void a_later_segment_withdraws_an_add_as_its_own_does(void)+{+ struct tree_publication sealed = {}, later = {};+ struct tree_operation *add, *op;++ add = operation(&sealed, "add", "x");+ label(&add->selector, "site", "a", "b");+ EXPECT_FALSE(tree_add_withdrawn(add, later.operations, 0));++ operation(&later, "add", "x");+ operation(&later, "delete", "y");+ op = operation(&later, "delete", "x");+ label(&op->selector, "site", "a", NULL);+ EXPECT_FALSE(tree_add_withdrawn(add, later.operations,+ later.n_operations));++ op = operation(&later, "delete", "x");+ label(&op->selector, "site", "b", "a");+ EXPECT_TRUE(tree_add_withdrawn(add, later.operations,+ later.n_operations));+ EXPECT_FALSE(tree_add_withdrawn(add, later.operations,+ later.n_operations - 1));+ EXPECT_TRUE(tree_add_live(&sealed, 0));+ tree_publication_free(&later);+ tree_publication_free(&sealed);+}+static const struct unit_case cases[] = {UNIT_CASE(an_unconstrained_selector_shares_every_node),UNIT_CASE(lists_without_a_common_value_are_disjoint),UNIT_CASE(release_prefixes_meet_where_one_continues_the_other),UNIT_CASE(a_key_with_other_values_is_disjoint),UNIT_CASE(an_add_lives_until_a_delete_reaches_all_its_nodes),+ UNIT_CASE(a_later_segment_withdraws_an_add_as_its_own_does),{}};diff --git a/testing/unit/chain.c b/testing/unit/chain.cindex 4aea58c7..bc258519 100644--- a/testing/unit/chain.c+++ b/testing/unit/chain.c@@ -62,95 +62,12 @@ static void chain_fold_extends_like_the_register(void)EXPECT_MEMEQ(chain, want, sizeof(want));}-/*- * The operation digests of a three-operation tree, and the history root- * after none, one, two and all of them as Python's hashlib gives it:- *- * root = bytes(32)- * for d in digests:- * root = sha256(b"shirudo-tree-history\0" + root + d).digest()- */-static const char *const tree_operations[] = {- "13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43",- "5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b",- "bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc",-};--static const char *const history_roots[] = {- "0000000000000000000000000000000000000000000000000000000000000000",- "470779d64e1302c4826a4be3222020050e70784ae6016040eabde9d0d8770d80",- "889efeb27650c0111168d523c935f051addbcc049d079e440e518dd3939722f0",- "bdc9ee89e753beca03d6e9ae89344269cb3a2e8ba3662122f55b1e3f7ff34011",-};--static void history_root_after(size_t n, char hex[2 * 32 + 1])-{- __u8 root[32] = {}, digest[32];- size_t i;-- for (i = 0; i < n; i++) {- ASSERT_EQ(hex_decode(tree_operations[i], digest, 32), 0);- ASSERT_EQ(chain_history_step(root, digest, root), 0);- }- hex_encode(root, sizeof(root), hex);-}--static void history_root_matches_the_reference(void)-{- char hex[2 * 32 + 1];-- history_root_after(0, hex);- EXPECT_STREQ(hex, history_roots[0]);- history_root_after(1, hex);- EXPECT_STREQ(hex, history_roots[1]);- history_root_after(3, hex);- EXPECT_STREQ(hex, history_roots[3]);-}--static void history_step_writes_beside_its_input(void)-{- __u8 prev[32] = {}, zero[32] = {}, digest[32], out[32];- char hex[2 * 32 + 1];-- ASSERT_EQ(hex_decode(tree_operations[0], digest, 32), 0);- ASSERT_EQ(chain_history_step(prev, digest, out), 0);- hex_encode(out, sizeof(out), hex);- EXPECT_STREQ(hex, history_roots[1]);- EXPECT_MEMEQ(prev, zero, sizeof(prev));-}--static void history_root_differs_from_the_projection_root(void)-{- static const char *const projection_roots[] = {- "04f83540c1727aefcf3c53449a99594c8fd1cc15e1466dbdbf3168cc8f9dc136",- "a042a582b3a3d8c1b633b8ed0356e0b52f1f5aa25af85b06cc3f481562dcda93",- "154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1",- };- __u8 history[32] = {}, projection[32] = {}, digest[32];- char hex[2 * 32 + 1];- size_t i;-- for (i = 0; i < ARRAY_SIZE(tree_operations); i++) {- ASSERT_EQ(hex_decode(tree_operations[i], digest, 32), 0);- ASSERT_EQ(chain_history_step(history, digest, history), 0);- ASSERT_EQ(sha256_2(projection, 32, digest, 32, projection), 0);- hex_encode(projection, sizeof(projection), hex);- EXPECT_STREQ(hex, projection_roots[i]);- hex_encode(history, sizeof(history), hex);- EXPECT_STREQ(hex, history_roots[i + 1]);- EXPECT_TRUE(memcmp(history, projection, sizeof(history)) != 0);- }-}-static const struct unit_case cases[] = {UNIT_CASE(sha256_matches_fips_180_vector),UNIT_CASE(sha256_2_hashes_the_concatenation),UNIT_CASE(sha256_2_reports_a_failure),UNIT_CASE(chain_events_hash_their_documented_input),UNIT_CASE(chain_fold_extends_like_the_register),- UNIT_CASE(history_root_matches_the_reference),- UNIT_CASE(history_step_writes_beside_its_input),- UNIT_CASE(history_root_differs_from_the_projection_root),{}};diff --git a/testing/unit/chain_history.c b/testing/unit/chain_history.cnew file mode 100644index 00000000..0e184129--- /dev/null+++ b/testing/unit/chain_history.c@@ -0,0 +1,95 @@+// SPDX-License-Identifier: BSD-2-Clause+/* Copyright (c) 2026 Authors of shirudo */++#include "chain.h"+#include "hex.h"+#include "unit.h"++/*+ * The operation digests of a three-operation tree, and the history root+ * after none, one, two and all of them as Python's hashlib gives it:+ *+ * root = bytes(32)+ * for d in digests:+ * root = sha256(b"shirudo-tree-history\0" + root + d).digest()+ */+static const char *const tree_operations[] = {+ "13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43",+ "5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b",+ "bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc",+};++static const char *const history_roots[] = {+ "0000000000000000000000000000000000000000000000000000000000000000",+ "470779d64e1302c4826a4be3222020050e70784ae6016040eabde9d0d8770d80",+ "889efeb27650c0111168d523c935f051addbcc049d079e440e518dd3939722f0",+ "bdc9ee89e753beca03d6e9ae89344269cb3a2e8ba3662122f55b1e3f7ff34011",+};++static void history_root_after(size_t n, char hex[2 * 32 + 1])+{+ __u8 root[32] = {}, digest[32];+ size_t i;++ for (i = 0; i < n; i++) {+ ASSERT_EQ(hex_decode(tree_operations[i], digest, 32), 0);+ ASSERT_EQ(chain_history_step(root, digest, root), 0);+ }+ hex_encode(root, sizeof(root), hex);+}++static void history_root_matches_the_reference(void)+{+ char hex[2 * 32 + 1];++ history_root_after(0, hex);+ EXPECT_STREQ(hex, history_roots[0]);+ history_root_after(1, hex);+ EXPECT_STREQ(hex, history_roots[1]);+ history_root_after(3, hex);+ EXPECT_STREQ(hex, history_roots[3]);+}++static void history_step_writes_beside_its_input(void)+{+ __u8 prev[32] = {}, zero[32] = {}, digest[32], out[32];+ char hex[2 * 32 + 1];++ ASSERT_EQ(hex_decode(tree_operations[0], digest, 32), 0);+ ASSERT_EQ(chain_history_step(prev, digest, out), 0);+ hex_encode(out, sizeof(out), hex);+ EXPECT_STREQ(hex, history_roots[1]);+ EXPECT_MEMEQ(prev, zero, sizeof(prev));+}++static void history_root_differs_from_the_projection_root(void)+{+ static const char *const projection_roots[] = {+ "04f83540c1727aefcf3c53449a99594c8fd1cc15e1466dbdbf3168cc8f9dc136",+ "a042a582b3a3d8c1b633b8ed0356e0b52f1f5aa25af85b06cc3f481562dcda93",+ "154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1",+ };+ __u8 history[32] = {}, projection[32] = {}, digest[32];+ char hex[2 * 32 + 1];+ size_t i;++ for (i = 0; i < ARRAY_SIZE(tree_operations); i++) {+ ASSERT_EQ(hex_decode(tree_operations[i], digest, 32), 0);+ ASSERT_EQ(chain_history_step(history, digest, history), 0);+ ASSERT_EQ(sha256_2(projection, 32, digest, 32, projection), 0);+ hex_encode(projection, sizeof(projection), hex);+ EXPECT_STREQ(hex, projection_roots[i]);+ hex_encode(history, sizeof(history), hex);+ EXPECT_STREQ(hex, history_roots[i + 1]);+ EXPECT_TRUE(memcmp(history, projection, sizeof(history)) != 0);+ }+}++static const struct unit_case cases[] = {+ UNIT_CASE(history_root_matches_the_reference),+ UNIT_CASE(history_step_writes_beside_its_input),+ UNIT_CASE(history_root_differs_from_the_projection_root),+ {}+};++UNIT_SUITE(chain_history, cases);diff --git a/tools/shirudo-build/bpm-publish.c b/tools/shirudo-build/bpm-publish.cindex de3181e8..dc5173fe 100644--- a/tools/shirudo-build/bpm-publish.c+++ b/tools/shirudo-build/bpm-publish.c@@ -39,6 +39,10 @@#define BPM_MANIFEST_CAP 8192u#define BPM_SIGN_MAX (64u * 1024u)+#define TREE_SEGMENT_OPS 64++/* One append never splits across segments, so it fits in one. */+BUILD_BUG_ON(BPM_BUILD_MAX_ENTRIES > TREE_MAX_OPS);static void tree_append_usage(void){@@ -47,11 +51,14 @@ static void tree_append_usage(void)" [--keys-dir <dir>] [--key <signing_key.pem>]\n"" [--cert <cert.der>] [--previous-cert <cert.der>]\n"" [--tree-id <id>]\n"- " [--reference <ref>] [--op add|delete]\n\n"+ " [--reference <ref>] [--op add|delete]\n"+ " [--segment-ops <n>]\n\n""Publishes the [upatches.tree] entries of a built package as the next\n""operations of the signed tree at <repository>:<ref> (default stable).\n"+ "A segment that holds --segment-ops operations (default %d, 1 to %d)\n"+ "is sealed and the entries start the next one.\n""The key defaults to --keys-dir, SHIRUDO_KEYS_DIR or %s.\n",- KEYS_DIR);+ TREE_SEGMENT_OPS, TREE_MAX_OPS, KEYS_DIR);}static int publish_fail(const char *action, int ret)@@ -843,15 +850,65 @@ struct tree_xdp_classes {bool known[TREE_MAX_OPS];};+/* The deletes of the segments after the one being checked. */+struct tree_later {+ struct tree_operation *deletes;+ int n;+ int cap;+};++static void tree_later_free(struct tree_later *later)+{+ for (int i = 0; i < later->n; i++)+ tree_selector_free(&later->deletes[i].selector);+ xfree(later->deletes, (size_t)later->cap * sizeof(*later->deletes));+ *later = (struct tree_later){};+}++static int tree_later_take(struct tree_later *later,+ const struct tree_publication *pub)+{+ for (int i = 0; i < pub->n_operations; i++) {+ const struct tree_operation *op = &pub->operations[i];+ struct tree_operation *deletes, *d;+ int cap;++ if (strcmp(op->op, "delete"))+ continue;+ if (later->n == later->cap) {+ if (check_mul_overflow(later->cap ? later->cap : 8, 2,+ &cap))+ return -E2BIG;+ deletes = xreallocarray(later->deletes,+ (size_t)later->cap, (size_t)cap,+ sizeof(*deletes));+ if (!deletes)+ return -ENOMEM;+ later->deletes = deletes;+ later->cap = cap;+ }+ d = &later->deletes[later->n];+ *d = (struct tree_operation){ .seq = op->seq };+ if (tree_selector_copy(&d->selector, &op->selector))+ return -ENOMEM;+ bpm_copy_string(d->op, sizeof(d->op), op->op);+ bpm_copy_string(d->id, sizeof(d->id), op->id);+ later->n++;+ }+ return 0;+}+/** A device runs one native XDP program. The second of two upatches that* select a class fails its load on every node with such a device, and- * tree sync stops at the first operation that fails.+ * tree sync stops at the first operation that fails. later, NULL for+ * none, holds the deletes published after pub.*/static int tree_refuse_shared_xdp_class(struct bpm_oci_client *c,const char *repository,const char *repo_ref,const struct tree_publication *pub,+ const struct tree_later *later,struct tree_xdp_classes *seen,const struct tree_operation *op,__u32 classes)@@ -862,6 +919,8 @@ static int tree_refuse_shared_xdp_class(struct bpm_oci_client *c,if (strcmp(other->op, "add") || !strcmp(other->id, op->id) ||!tree_add_live(pub, i) ||+ (later && tree_add_withdrawn(other, later->deletes,+ later->n)) ||tree_selectors_disjoint(&other->selector, &op->selector))continue;if (!seen->known[i]) {@@ -884,6 +943,246 @@ static int tree_refuse_shared_xdp_class(struct bpm_oci_client *c,return 0;}+/* What tree sync checks of a publication before it applies anything. */+static int tree_publication_verify(const struct tree_publication *pub)+{+ int ret = tree_publication_check(pub);++ for (int i = 0; !ret && i < pub->n_operations; i++)+ ret = tree_operation_validate(&pub->operations[i]);+ return ret;+}++/*+ * The sealed segment succ names, as a node walking back fetches it: by+ * manifest digest, signed, well formed and ending where succ starts.+ */+static int tree_fetch_sealed(struct bpm_oci_client *c, const char *repository,+ const char *cert,+ const struct tree_publication *succ,+ struct tree_publication *pred)+{+ struct bpm_buffer document = {};+ char digest[BPM_MAX_DIGEST];+ int ret;++ ret = bpm_tree_fetch_document(c, repository,+ succ->segment_manifest_digest, cert,+ NULL, &document, digest, sizeof(digest));+ if (!ret)+ ret = tree_parse((const char *)document.data, document.len,+ pred);+ if (!ret)+ ret = tree_publication_verify(pred);+ if (!ret)+ ret = tree_segment_precedes(pred, digest, succ);+ bpm_buffer_free(&document);+ if (ret)+ pr_err("bpm tree append: the sealed segment %s, which ends at seq %lld, does not verify",+ succ->segment_manifest_digest,+ (long long)succ->base_seq);+ return ret;+}++/*+ * The shared class check of an add over the sealed segments before cur,+ * back to seq 0: sealed when this append seals it, the others fetched+ * by digest. An add stays live until a delete of any later segment+ * withdraws it, so the deletes of every segment walked are kept.+ */+static int tree_refuse_sealed_xdp_class(struct bpm_oci_client *c,+ const char *repository,+ const char *repo_ref, const char *cert,+ const struct tree_publication *cur,+ const struct tree_publication *sealed,+ const struct tree_operation *op,+ __u32 classes)+{+ const struct tree_publication *succ = cur, *segment = sealed;+ struct tree_publication fetched[2] = {};+ struct tree_xdp_classes *seen;+ struct tree_later later = {};+ int next = 0, ret;++ if (cur->base_seq > TREE_MAX_JOIN_OPS) {+ pr_err("bpm tree append: a joining node walks back %lld operations, past the limit of %d, so the XDP device classes of the sealed segments cannot be checked",+ (long long)cur->base_seq, TREE_MAX_JOIN_OPS);+ return -E2BIG;+ }+ seen = xmalloc(sizeof(*seen));+ if (!seen)+ return -ENOMEM;+ ret = tree_later_take(&later, cur);+ while (!ret) {+ if (!segment) {+ if (!succ->base_seq)+ break;+ tree_publication_free(&fetched[next]);+ ret = tree_fetch_sealed(c, repository, cert, succ,+ &fetched[next]);+ if (ret)+ break;+ segment = &fetched[next];+ next ^= 1;+ }+ memset(seen, 0, sizeof(*seen));+ ret = tree_refuse_shared_xdp_class(c, repository, repo_ref,+ segment, &later, seen, op,+ classes);+ if (!ret)+ ret = tree_later_take(&later, segment);+ succ = segment;+ segment = NULL;+ }+ tree_later_free(&later);+ tree_publication_free(&fetched[0]);+ tree_publication_free(&fetched[1]);+ xfree(seen, sizeof(*seen));+ return ret;+}++/* history_root at the head of seg: its base's, over its operations. */+static int tree_history_at_head(const struct tree_publication *seg,+ char out[65])+{+ __u8 root[32] = {}, digest[32];+ int ret;++ if (seg->base_seq && hex_decode(seg->history_root, root, sizeof(root)))+ return -EINVAL;+ for (int i = 0; i < seg->n_operations; i++) {+ ret = sha256_digest_decode(seg->operations[i].operation_digest,+ digest);+ if (!ret)+ ret = chain_history_step(root, digest, root);+ if (ret)+ return ret;+ }+ hex_encode(root, sizeof(root), out);+ return 0;+}++static int tree_segment_tag(__u64 k, char *tag, size_t tag_sz)+{+ return strsprintf(tag, tag_sz, "segment-%llu", k) < 0 ?+ -ENAMETOOLONG : 0;+}++/* The digest of the manifest segment-<k> tags, -ENOENT without the tag. */+static int tree_segment_tag_digest(struct bpm_oci_client *c,+ const char *repository, __u64 k,+ char *digest, size_t digest_sz)+{+ struct bpm_buffer manifest = {};+ char tag[32], url[PATH_MAX], hex[65];+ int ret;++ ret = tree_segment_tag(k, tag, sizeof(tag));+ if (!ret)+ ret = bpm_oci_url(c, repository, "manifests", tag, url,+ sizeof(url));+ if (!ret)+ ret = bpm_oci_get_memory(c, url, BPM_MANIFEST_MEDIA, &manifest);+ if (!ret && bpm_sha256_hex(manifest.data, manifest.len, hex,+ sizeof(hex)))+ ret = -EINVAL;+ if (!ret && strsprintf(digest, digest_sz, "sha256:%s", hex) < 0)+ ret = -ENAMETOOLONG;+ bpm_buffer_free(&manifest);+ return ret;+}++/*+ * The k of the next segment-<k> tag: doubling, then halving, finds a k+ * without a tag in about 2 log2 k requests, so no tag is ever moved. 0+ * when the last tag already names the sealed manifest, which a run that+ * failed after tagging leaves behind.+ */+static int tree_next_segment_tag(struct bpm_oci_client *c,+ const char *repository,+ const char *sealed_digest, __u64 *k)+{+ char digest[BPM_MAX_DIGEST], last[BPM_MAX_DIGEST] = {};+ __u64 present = 0, absent = 1, probe;+ bool doubling = true;+ int ret;++ while (doubling || absent - present > 1) {+ probe = doubling ? absent : present + (absent - present) / 2;+ ret = tree_segment_tag_digest(c, repository, probe, digest,+ sizeof(digest));+ if (ret == -ENOENT) {+ absent = probe;+ doubling = false;+ continue;+ }+ if (ret)+ return ret;+ present = probe;+ bpm_copy_string(last, sizeof(last), digest);+ if (doubling && check_mul_overflow(absent, 2, &absent))+ return -EOVERFLOW;+ }+ *k = present && !strcmp(last, sealed_digest) ? 0 : absent;+ return 0;+}++/*+ * Tag the sealed manifest segment-<k> so that registry garbage collection+ * keeps it; nodes walk back to it by digest and never read the tag.+ */+static int tree_tag_sealed(struct bpm_oci_client *c, const char *repository,+ const char *sealed_digest)+{+ char tag[32] = {}, url[PATH_MAX], digest[BPM_MAX_DIGEST], hex[65];+ struct bpm_buffer manifest = {};+ __u64 k;+ int ret;++ ret = tree_next_segment_tag(c, repository, sealed_digest, &k);+ if (ret || !k)+ goto out;+ ret = tree_segment_tag(k, tag, sizeof(tag));+ if (!ret)+ ret = bpm_oci_url(c, repository, "manifests", sealed_digest,+ url, sizeof(url));+ if (!ret)+ ret = bpm_oci_get_memory(c, url, BPM_MANIFEST_MEDIA, &manifest);+ if (!ret && (bpm_sha256_hex(manifest.data, manifest.len, hex,+ sizeof(hex)) ||+ !bpm_digest_matches(sealed_digest, hex)))+ ret = -EKEYREJECTED;+ if (!ret)+ ret = bpm_oci_put_manifest(c, repository, tag, manifest.data,+ manifest.len, digest, sizeof(digest));+out:+ bpm_buffer_free(&manifest);+ if (ret)+ pr_err("bpm tree append: cannot tag the sealed segment %s",+ sealed_digest);+ return ret;+}++/*+ * The segment after sealed, whose manifest is sealed_digest, as it+ * starts: at the sealed head, with the history root there.+ */+static int tree_start_segment(const struct tree_publication *sealed,+ const char *sealed_digest,+ struct tree_publication *pub)+{+ *pub = (struct tree_publication){+ .schema = 1,+ .generation = sealed->generation,+ .base_seq = sealed->head_seq,+ .head_seq = sealed->head_seq,+ };+ bpm_copy_string(pub->tree_id, sizeof(pub->tree_id), sealed->tree_id);+ bpm_copy_string(pub->segment_manifest_digest,+ sizeof(pub->segment_manifest_digest), sealed_digest);+ return tree_history_at_head(sealed, pub->history_root);+}+static int cmd_bpm_tree_append(int argc, char **argv){const char *package = NULL, *raw_repository = NULL, *keys_dir_arg = NULL;@@ -892,10 +1191,14 @@ static int cmd_bpm_tree_append(int argc, char **argv)const char *key = NULL, *cert = NULL, *tree_id = NULL;const char *previous_cert = NULL;const char *reference = "stable", *operation = "add";+ const char *segment_ops_arg = NULL;char key_path[PATH_MAX], cert_path[PATH_MAX];char parent[BPM_MAX_DIGEST] = {}, digest[72];+ struct tree_publication *sealed = NULL;struct tree_xdp_classes *seen = NULL;struct tree_upload *uploads = NULL;+ int segment_ops = TREE_SEGMENT_OPS;+ size_t entries = 0;struct bpm_buffer previous = {};struct bpm_fixes *fixes = NULL;struct tree_emit_extra extra;@@ -945,6 +1248,10 @@ static int cmd_bpm_tree_append(int argc, char **argv)operation = argv[++i];} else if (!strncmp(a, "--op=", 5)) {operation = a + 5;+ } else if (!strcmp(a, "--segment-ops") && i + 1 < argc) {+ segment_ops_arg = argv[++i];+ } else if (!strncmp(a, "--segment-ops=", 14)) {+ segment_ops_arg = a + 14;} else if (a[0] == '-' || (package && raw_repository)) {tree_append_usage();return -EINVAL;@@ -966,6 +1273,17 @@ static int cmd_bpm_tree_append(int argc, char **argv)pr_err("bpm tree append: invalid --tree-id %s", tree_id);return -EINVAL;}+ if (segment_ops_arg) {+ __u64 n;++ if (parse_u64(segment_ops_arg, strlen(segment_ops_arg),+ TREE_MAX_OPS, &n) || !n) {+ pr_err("bpm tree append: --segment-ops must be 1 to %d",+ TREE_MAX_OPS);+ return -EINVAL;+ }+ segment_ops = (int)n;+ }unload = !strcmp(operation, "delete");if (!key || !cert) {const char *keys_dir = keys_dir_resolve(keys_dir_arg);@@ -1013,6 +1331,8 @@ static int cmd_bpm_tree_append(int argc, char **argv)pr_err("bpm tree append: cannot parse the Beefile of %s", package);goto out;}+ for (size_t i = 0; i < spec->n_upatches; i++)+ entries += spec->upatches[i].tree.present;ret = bpm_oci_parse_push_repo(repo_ref, &c, repository, sizeof(repository));if (ret) {pr_err("bpm tree append: the repository must be oci://registry/repository");@@ -1040,6 +1360,24 @@ static int cmd_bpm_tree_append(int argc, char **argv)ret = -EINVAL;goto out;}+ ret = tree_publication_verify(&pub);+ if (ret) {+ pr_err("bpm tree append: the publication at %s:%s does not verify",+ repo_ref, reference);+ goto out;+ }+ if (pub.n_operations >= segment_ops ||+ (size_t)pub.n_operations + entries > TREE_MAX_OPS) {+ sealed = xmalloc(sizeof(*sealed));+ if (!sealed) {+ ret = -ENOMEM;+ goto out;+ }+ *sealed = pub;+ ret = tree_start_segment(sealed, parent, &pub);+ if (ret)+ goto out;+ }if (check_add_overflow(pub.generation, 1, &pub.generation) ||pub.generation == INT64_MAX) {pr_err("bpm tree append: the tree's generation is exhausted");@@ -1061,7 +1399,8 @@ static int cmd_bpm_tree_append(int argc, char **argv)ret = -ENOMEM;goto out;}- if (previous.data && tree_read_fixes(&previous, &pub, fixes)) {+ if (previous.data && !sealed &&+ tree_read_fixes(&previous, &pub, fixes)) {pr_err("bpm tree append: the publication at %s:%s has a fixes list bpm tree append would not write, so it cannot carry it into the next generation",repo_ref, reference);ret = -EINVAL;@@ -1118,8 +1457,14 @@ static int cmd_bpm_tree_append(int argc, char **argv)elseret = tree_refuse_shared_xdp_class(&c, repository,repo_ref, &pub,- seen, op,+ NULL, seen, op,classes);+ if (!ret && classes)+ ret = tree_refuse_sealed_xdp_class(&c, repository,+ repo_ref,+ previous_cert,+ &pub, sealed,+ op, classes);}if (!ret)ret = tree_describe_artifact(repo_ref, body, body_len,@@ -1198,6 +1543,8 @@ static int cmd_bpm_tree_append(int argc, char **argv)json_arr_close(&e);json_obj_close(&e);ret = e.err;+ if (!ret && sealed)+ ret = tree_tag_sealed(&c, repository, parent);if (!ret)ret = bpm_oci_put_manifest(&c, repository, reference,(const __u8 *)manifest, e.len,@@ -1221,6 +1568,8 @@ out:xfree(fixes, n_fixes * sizeof(*fixes));bpm_buffer_free(&previous);tree_publication_free(&pub);+ tree_publication_free(sealed);+ xfree(sealed, sizeof(*sealed));bpm_build_spec_free(spec);xfree(beefile, len + 1);xfree(info.cert, info.cert_len + 1);diff --git a/util/bpm_tree.h b/util/bpm_tree.hindex 49557491..091b067f 100644--- a/util/bpm_tree.h+++ b/util/bpm_tree.h@@ -16,6 +16,15 @@#define TREE_MAX_SELECTOR_VALUES 16#define TREE_STRING_MAX 256+/*+ * The most operations a walk back through sealed segments may cover from+ * seq 0, as a node that joins a tree does: one past it is -E2BIG. A test+ * build sets it low.+ */+#ifndef TREE_MAX_JOIN_OPS+#define TREE_MAX_JOIN_OPS 1048576+#endif+struct json_emit;struct tree_kv {diff --git a/util/bpm_tree_overlap.c b/util/bpm_tree_overlap.cindex db6d2813..c6c54e4c 100644--- a/util/bpm_tree_overlap.c+++ b/util/bpm_tree_overlap.c@@ -147,17 +147,21 @@ static bool selector_covers(const struct tree_selector *outer,outer->labels, outer->n_labels);}-bool tree_add_live(const struct tree_publication *pub, int index)+bool tree_add_withdrawn(const struct tree_operation *add,+ const struct tree_operation *later, int n){- const struct tree_operation *add = &pub->operations[index];-- for (int i = index + 1; i < pub->n_operations; i++) {- const struct tree_operation *later = &pub->operations[i];-- if (!strcmp(later->op, "delete") &&- !strcmp(later->id, add->id) &&- selector_covers(&later->selector, &add->selector))- return false;+ for (int i = 0; i < n; i++) {+ if (!strcmp(later[i].op, "delete") &&+ !strcmp(later[i].id, add->id) &&+ selector_covers(&later[i].selector, &add->selector))+ return true;}- return true;+ return false;+}++bool tree_add_live(const struct tree_publication *pub, int index)+{+ return !tree_add_withdrawn(&pub->operations[index],+ &pub->operations[index + 1],+ pub->n_operations - index - 1);}diff --git a/util/bpm_tree_overlap.h b/util/bpm_tree_overlap.hindex 863f6962..5b5e6c81 100644--- a/util/bpm_tree_overlap.h+++ b/util/bpm_tree_overlap.h@@ -11,6 +11,7 @@#include <stdbool.h>+struct tree_operation;struct tree_publication;struct tree_selector;@@ -25,7 +26,12 @@ bool tree_selectors_disjoint(const struct tree_selector *a,/** Whether the add at index may still be loaded somewhere: no later* delete of its upatch reaches every node the add reaches.+ * tree_add_withdrawn() asks the opposite of the n operations at later,+ * which all come after the add, such as those of the segments after its+ * own.*/bool tree_add_live(const struct tree_publication *pub, int index);+bool tree_add_withdrawn(const struct tree_operation *add,+ const struct tree_operation *later, int n);#endif /* SHIRUDO_BPM_TREE_OVERLAP_H */diff --git a/util/chain.c b/util/chain.cindex 073e7ffd..91a5310c 100644--- a/util/chain.c+++ b/util/chain.c@@ -152,18 +152,6 @@ int chain_fold(__u8 chain[32], const __u8 event[32])return sha256_calc(cat, sizeof(cat), chain);}-int chain_history_step(const __u8 prev[32], const __u8 operation_digest[32],- __u8 out[32])-{- static const char tag[] = "shirudo-tree-history";- __u8 buf[sizeof(tag) + 64];-- memcpy(buf, tag, sizeof(tag));- memcpy(buf + sizeof(tag), prev, 32);- memcpy(buf + sizeof(tag) + 32, operation_digest, 32);- return sha256_calc(buf, sizeof(buf), out);-}-int chain_anchor(const __u8 name[TPM_NAME_LEN],char *out, size_t cap){diff --git a/util/chain_history.c b/util/chain_history.cnew file mode 100644index 00000000..aa8b2482--- /dev/null+++ b/util/chain_history.c@@ -0,0 +1,28 @@+// SPDX-License-Identifier: BSD-2-Clause+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * The history root of an upatch tree, apart from the register code of+ * chain.c, so that the publisher computes a segment's base without the TPM.+ */++#include <string.h>++#include "chain.h"+#include "crypto.h"++int chain_history_step(const __u8 prev[32], const __u8 operation_digest[32],+ __u8 out[32])+{+ static const char tag[] = "shirudo-tree-history";+ __u8 buf[sizeof(tag) + 64];+ int ret;++ memcpy(buf, tag, sizeof(tag));+ memcpy(buf + sizeof(tag), prev, 32);+ memcpy(buf + sizeof(tag) + 32, operation_digest, 32);+ ret = sha256_buffer(buf, sizeof(buf), out);+ if (ret)+ memset(out, 0, 32);+ return ret;+}